<?php
// process_leads.php
require 'system/db_connect.php'; 

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// Auto-Loader Logic (Keep your existing loader here)
if (file_exists('vendor/autoload.php')) { require 'vendor/autoload.php'; }
elseif (file_exists('PHPMailer/src/PHPMailer.php')) { require 'PHPMailer/src/Exception.php'; require 'PHPMailer/src/PHPMailer.php'; require 'PHPMailer/src/SMTP.php'; }
else { die(json_encode(['status' => 'error', 'message' => 'Mailer not found'])); }

// Helper to send JSON response
function sendResponse($status, $message) {
    if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
        // AJAX Request -> Return JSON
        header('Content-Type: application/json');
        echo json_encode(['status' => $status, 'message' => $message]);
        exit();
    } else {
        // Normal Request -> Browser Redirect
        header("Location: index.php?status=$status&msg=" . urlencode($message));
        exit();
    }
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $parent_name = htmlspecialchars(strip_tags(trim($_POST['parent_name'] ?? '')), ENT_QUOTES, 'UTF-8');
    $phone       = htmlspecialchars(strip_tags(trim($_POST['phone'] ?? '')), ENT_QUOTES, 'UTF-8');
    $class       = htmlspecialchars(strip_tags(trim($_POST['class'] ?? '')), ENT_QUOTES, 'UTF-8');
    $source      = htmlspecialchars(strip_tags(trim($_POST['source'] ?? '')), ENT_QUOTES, 'UTF-8');

    if (empty($parent_name) || empty($phone) || empty($class)) {
        sendResponse('error', 'All fields are required.');
    }

    // Validate Phone strictly
    if (!preg_match('/^[0-9]{10}$/', $phone)) {
        sendResponse('error', 'Invalid phone number format.');
    }

    try {
        $sql = "INSERT INTO leads (parent_name, phone, class_grade, source, created_at) VALUES (:name, :phone, :class, :source, NOW())";
        $stmt = $pdo->prepare($sql);
        $result = $stmt->execute([':name' => $parent_name, ':phone' => $phone, ':class' => $class, ':source' => $source]);

        if ($result) {
            if (defined('SMTP_HOST') && !empty(SMTP_HOST) && !empty(SMTP_USER) && !empty(SMTP_PASS)) {
                // ... (Your existing sendNotificationEmail function call here) ...
                sendNotificationEmail($parent_name, $phone, $class, $source);
            }
            sendResponse('success', 'Application received successfully!');
        } else {
            sendResponse('error', 'Database error.');
        }
    } catch (Exception $e) {
        error_log($e->getMessage());
        sendResponse('error', 'Server error occurred.');
    }
} else {
    header("Location: index.php");
    exit();
}

// ... (Keep your sendNotificationEmail function exactly as it is) ...
function sendNotificationEmail($name, $phone, $class, $source) {
    // ... Copy your existing mail logic here ...
    // Just ensure you add the mailer logic back in
     $mail = new PHPMailer(true);
    // ... rest of mail code ...
     try {
        $mail->isSMTP();
        $mail->Host       = SMTP_HOST;
        $mail->SMTPAuth   = true;
        $mail->Username   = SMTP_USER;
        $mail->Password   = SMTP_PASS;
        $mail->SMTPSecure = (defined('SMTP_SECURE') && SMTP_SECURE == 'ssl') ? PHPMailer::ENCRYPTION_SMTPS : PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port       = SMTP_PORT;

        $mail->setFrom(MAIL_FROM_EMAIL, MAIL_FROM_NAME);
        $mail->addAddress(ADMIN_EMAIL);
        
        if (defined('CC_EMAIL') && !empty(CC_EMAIL)) {
            $mail->addAddress(CC_EMAIL);
        }

        $mail->isHTML(true);
        $mail->Subject = "New Admission Lead: $name ($class)";
        $mail->Body    = "<h3>New Lead</h3><p>Name: $name</p><p>Phone: $phone</p><p>Class: $class</p>";

        $mail->send();
    } catch (Exception $e) {
        error_log("Mail Error: {$mail->ErrorInfo}");
    }
}
?>