<?php
header('Access-Control-Allow-Origin: *'); // Allow from Unbounce
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
header('Content-Type: application/json');

// Database Configuration
$host = 'localhost';
$user = 'penta_taxhardshipcenter'; // Update with your DB Username
$pass = '@ADmin12!';     // Update with your DB Password
$dbname = 'penta_taxhardshipcenter'; // Update with your DB Name

$conn = new mysqli($host, $user, $pass, $dbname);

if ($conn->connect_error) {
    echo json_encode(['status' => 'error', 'message' => 'Database connection failed']);
    exit;
}

// Handle Verification Action
if (isset($_REQUEST['action']) && $_REQUEST['action'] === 'verify') {
    handleVerification($conn);
} else {
    // Default: Handle New Lead & Send OTP
    handleNewLead($conn);
}

function handleNewLead($conn) {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        echo json_encode(['status' => 'error', 'message' => 'Invalid Request']);
        exit;
    }

    // 1. Sanitize Input
    $full_name = filter_input(INPUT_POST, 'full_name', FILTER_SANITIZE_SPECIAL_CHARS);
    $email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
    $phone = filter_input(INPUT_POST, 'phone_number', FILTER_SANITIZE_SPECIAL_CHARS);
    
    // Fallback if keys are different
    if (!$full_name) $full_name = $_POST['full_name'] ?? 'Unknown';
    if (!$email) $email = $_POST['email'] ?? '';
    if (!$phone) $phone = $_POST['phone'] ?? $_POST['phone_number'] ?? '';

    if (!$email || !$phone) {
        echo json_encode(['status' => 'error', 'message' => 'Email and Phone are required']);
        exit;
    }

    // 2. Generate OTP
    $otp = str_pad(mt_rand(0, 999999), 6, '0', STR_PAD_LEFT);

    // 3. Store in Database
    // Storing full request data as JSON for backup
    $all_data = json_encode($_POST);
    
    $stmt = $conn->prepare("INSERT INTO leads_otp (full_name, email, phone_number, otp_code, form_data) VALUES (?, ?, ?, ?, ?)");
    $stmt->bind_param("sssss", $full_name, $email, $phone, $otp, $all_data);
    
    if ($stmt->execute()) {
        // 4. Send Email
        $subject = "Your Verification Code";
        $message = "Hello $full_name,\n\nYour verification code is: $otp\n\nPlease enter this code to complete your submission.\n\nThank you.";
        $headers = "From: no-reply@webycart.pk\r\n";
        $headers .= "Reply-To: no-reply@webycart.pk\r\n";
        
        // Mail Function
        $mailSent = mail($email, $subject, $message, $headers);

        if ($mailSent) {
            echo json_encode(['status' => 'success', 'message' => 'OTP sent successfully']);
        } else {
            // Still return success to UI so they can try (or mock), but log error internally
            echo json_encode(['status' => 'success', 'message' => 'OTP generated (Email failed)']); 
        }
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Failed to save data']);
    }
    $stmt->close();
}

function handleVerification($conn) {
    $otp = $_POST['otp'] ?? '';
    $phone = $_POST['phone'] ?? ''; // or email, using phone as identifier

    if (!$otp || !$phone) {
        echo json_encode(['status' => 'error', 'message' => 'Missing OTP or Phone']);
        exit;
    }

    // check strictly latest OTP for this phone
    $stmt = $conn->prepare("SELECT id, otp_code FROM leads_otp WHERE phone_number = ? ORDER BY id DESC LIMIT 1");
    $stmt->bind_param("s", $phone);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($row = $result->fetch_assoc()) {
        if ($row['otp_code'] === $otp) {
            // Mark as Verified
            $update = $conn->prepare("UPDATE leads_otp SET is_verified = 1 WHERE id = ?");
            $update->bind_param("i", $row['id']);
            $update->execute();
            
            echo json_encode(['status' => 'success', 'message' => 'Verified']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Invalid OTP']);
        }
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Record not found']);
    }
    $stmt->close();
}

$conn->close();
?>
