<?php
// Data Sync Script for Admin Panel
// This script syncs contact form data with the admin panel localStorage system

header('Content-Type: application/json');

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Function to read JSON file safely
function read_json_file($file_path) {
    if (!file_exists($file_path)) {
        return [];
    }
    
    $content = file_get_contents($file_path);
    if ($content === false) {
        return [];
    }
    
    $data = json_decode($content, true);
    return $data !== null ? $data : [];
}

// Function to write JSON file safely
function write_json_file($file_path, $data) {
    $json_content = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    return file_put_contents($file_path, $json_content, LOCK_EX) !== false;
}

// Get action from request
$action = $_GET['action'] ?? 'sync';

try {
    switch ($action) {
        case 'sync':
            // Sync contact data to quotes format
            $contacts_file = __DIR__ . '/data/contacts.json';
            $quotes_file = __DIR__ . '/data/quotes.json';
            
            $contacts = read_json_file($contacts_file);
            $quotes = read_json_file($quotes_file);
            
            // Convert contacts to quotes format and merge
            $contact_quotes = array_map(function($contact) {
                return [
                    'id' => $contact['id'],
                    'company' => $contact['company'] ?? 'General Inquiry',
                    'name' => $contact['name'],
                    'job_title' => $contact['job_title'] ?? 'Contact Form',
                    'email' => $contact['email'],
                    'phone' => $contact['phone'],
                    'industry' => $contact['industry'] ?? 'general',
                    'employees' => $contact['employees'] ?? 'unknown',
                    'country' => $contact['country'] ?? 'Not specified',
                    'selected_plan' => $contact['selected_plan'] ?? 'general_inquiry',
                    'modules' => $contact['modules'] ?? [],
                    'message' => $contact['message'],
                    'status' => $contact['status'] ?? 'pending',
                    'timestamp' => $contact['timestamp'],
                    'type' => $contact['type'] ?? 'contact_form'
                ];
            }, $contacts);
            
            // Merge with existing quotes, avoiding duplicates
            $existing_ids = array_column($quotes, 'id');
            $new_quotes = array_filter($contact_quotes, function($quote) use ($existing_ids) {
                return !in_array($quote['id'], $existing_ids);
            });
            
            $all_quotes = array_merge($quotes, $new_quotes);
            
            // Sort by timestamp (newest first)
            usort($all_quotes, function($a, $b) {
                return strtotime($b['timestamp']) - strtotime($a['timestamp']);
            });
            
            // Save updated quotes
            write_json_file($quotes_file, $all_quotes);
            
            echo json_encode([
                'success' => true,
                'message' => 'Data synchronized successfully',
                'synced_count' => count($new_quotes),
                'total_quotes' => count($all_quotes)
            ]);
            break;
            
        case 'get_contacts':
            // Get all contact submissions
            $contacts_file = __DIR__ . '/data/contacts.json';
            $contacts = read_json_file($contacts_file);
            
            echo json_encode([
                'success' => true,
                'data' => $contacts
            ]);
            break;
            
        case 'get_quotes':
            // Get all quotes (including contact forms)
            $quotes_file = __DIR__ . '/data/quotes.json';
            $quotes = read_json_file($quotes_file);
            
            echo json_encode([
                'success' => true,
                'data' => $quotes
            ]);
            break;
            
        case 'update_status':
            // Update status of a quote/contact
            if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
                throw new Exception('Method not allowed');
            }
            
            $input = json_decode(file_get_contents('php://input'), true);
            $id = $input['id'] ?? '';
            $status = $input['status'] ?? '';
            
            if (empty($id) || empty($status)) {
                throw new Exception('ID and status are required');
            }
            
            // Update in contacts file
            $contacts_file = __DIR__ . '/data/contacts.json';
            $contacts = read_json_file($contacts_file);
            
            foreach ($contacts as &$contact) {
                if ($contact['id'] === $id) {
                    $contact['status'] = $status;
                    break;
                }
            }
            write_json_file($contacts_file, $contacts);
            
            // Update in quotes file
            $quotes_file = __DIR__ . '/data/quotes.json';
            $quotes = read_json_file($quotes_file);
            
            foreach ($quotes as &$quote) {
                if ($quote['id'] === $id) {
                    $quote['status'] = $status;
                    break;
                }
            }
            write_json_file($quotes_file, $quotes);
            
            echo json_encode([
                'success' => true,
                'message' => 'Status updated successfully'
            ]);
            break;
            
        case 'delete':
            // Delete a quote/contact
            if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
                throw new Exception('Method not allowed');
            }
            
            $input = json_decode(file_get_contents('php://input'), true);
            $id = $input['id'] ?? '';
            
            if (empty($id)) {
                throw new Exception('ID is required');
            }
            
            // Delete from contacts file
            $contacts_file = __DIR__ . '/data/contacts.json';
            $contacts = read_json_file($contacts_file);
            $contacts = array_filter($contacts, function($contact) use ($id) {
                return $contact['id'] !== $id;
            });
            write_json_file($contacts_file, $contacts);
            
            // Delete from quotes file
            $quotes_file = __DIR__ . '/data/quotes.json';
            $quotes = read_json_file($quotes_file);
            $quotes = array_filter($quotes, function($quote) use ($id) {
                return $quote['id'] !== $id;
            });
            write_json_file($quotes_file, $quotes);
            
            echo json_encode([
                'success' => true,
                'message' => 'Item deleted successfully'
            ]);
            break;
            
        default:
            throw new Exception('Invalid action');
    }
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>
