<?php
// 1. Headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

// Handle Preflight Request (Browser check)
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    http_response_code(200);
    exit();
}

// 2. Connect to Database
include_once 'db_connect.php';

// 3. Get JSON Input
$data = json_decode(file_get_contents("php://input"));

// 4. Validate Input
if (
    !empty($data->name) &&
    !empty($data->phone) &&
    !empty($data->email) &&
    !empty($data->message)
) {
    // Sanitize
    $name = htmlspecialchars(strip_tags($data->name));
    $phone = htmlspecialchars(strip_tags($data->phone));
    $email = htmlspecialchars(strip_tags($data->email));
    $subject = !empty($data->subject) ? htmlspecialchars(strip_tags($data->subject)) : "General Enquiry";
    $message = htmlspecialchars(strip_tags($data->message));

    // 5. Insert into Database
    $query = "INSERT INTO enquiries (name, phone, email, subject, message) VALUES (?, ?, ?, ?, ?)";
    $stmt = $conn->prepare($query);
    
    // Bind parameters (s = string)
    $stmt->bind_param("sssss", $name, $phone, $email, $subject, $message);

    if ($stmt->execute()) {
        
        // 6. Optional: Send Email Notification to School Admin
        // Note: This requires a configured mail server (works best on live hosting)
        $to = "1702pjpearljoy@gmail.com"; // REPLACE with your actual email
        $email_subject = "New Website Enquiry: " . $subject;
        $email_body = "You have received a new message.\n\nName: $name\nPhone: $phone\nEmail: $email\n\nMessage:\n$message";
        $headers = "From: no-reply@elitehighschentebbe.com";
        
        // Suppress errors with @ in case local server doesn't have mail set up
        @mail($to, $email_subject, $email_body, $headers);

        // Success Response
        http_response_code(201);
        echo json_encode(["message" => "Message sent successfully.", "success" => true]);
    } else {
        // Database Error
        http_response_code(503);
        echo json_encode(["message" => "Unable to save message.", "success" => false]);
    }

    $stmt->close();
} else {
    // Validation Error
    http_response_code(400);
    echo json_encode(["message" => "Incomplete data. Please fill all required fields.", "success" => false]);
}

$conn->close();
?>