<?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");

if ($_SERVER["REQUEST_METHOD"] === "OPTIONS") {
    exit(0);
}

if ($_SERVER["REQUEST_METHOD"] !== "POST") {
    http_response_code(405);
    echo json_encode(["success" => false, "message" => "Method not allowed"]);
    exit;
}

require_once "../config/database.php";

try {
    $pdo = getDBConnection();
    
    $input = json_decode(file_get_contents("php://input"), true);
    
    if (!$input) {
        throw new Exception("Invalid JSON input");
    }
    
    // Validate required fields
    $required_fields = ["user_id", "user_name", "user_mobile", "appointment_date", "amount", "consultation_type"];
    foreach ($required_fields as $field) {
        if (empty($input[$field])) {
            throw new Exception("Field \"$field\" is required");
        }
    }
    
    // Check if tatkal is enabled
    $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = \"tatkal_enabled\"");
    $stmt->execute();
    $tatkal_enabled = $stmt->fetchColumn();
    
    if ($tatkal_enabled !== "1") {
        throw new Exception("Tatkal booking is currently disabled");
    }
    
    // Validate appointment date
    if (!preg_match("/^\d{4}-\d{2}-\d{2}$/", $input["appointment_date"])) {
        throw new Exception("Invalid appointment date format");
    }
    
    $appointmentDate = new DateTime($input["appointment_date"]);
    $today = new DateTime();
    $today->setTime(0, 0, 0);
    
    if ($appointmentDate < $today) {
        throw new Exception("Cannot book appointments for past dates");
    }
    
    // Check advance booking days
    $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = \"tatkal_advance_days\"");
    $stmt->execute();
    $advanceDays = (int)$stmt->fetchColumn() ?: 7;
    
    $maxDate = $today->add(new DateInterval("P{$advanceDays}D"));
    if ($appointmentDate > $maxDate) {
        throw new Exception("Tatkal bookings are only allowed up to $advanceDays days in advance");
    }
    
    // Check if this day is enabled for tatkal booking
    $day_name = strtolower($appointmentDate->format("l"));
    $day_setting_key = "tatkal_" . $day_name . "_enabled";
    
    $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = ?");
    $stmt->execute([$day_setting_key]);
    $day_enabled = $stmt->fetchColumn();
    
    if ($day_enabled !== "1") {
        throw new Exception("Tatkal bookings are not allowed on " . ucfirst($day_name));
    }
    
    // Check tatkal slots availability for the day
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM appointments WHERE appointment_date = ? AND is_tatkal = 1");
    $stmt->execute([$input["appointment_date"]]);
    $booked_slots = $stmt->fetchColumn();
    
    $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = \"tatkal_slots\"");
    $stmt->execute();
    $max_slots = (int)$stmt->fetchColumn() ?: 5;
    
    if ($booked_slots >= $max_slots) {
        throw new Exception("No tatkal slots available for this date");
    }
    
    // Insert tatkal appointment
    $stmt = $pdo->prepare("
        INSERT INTO appointments (
            user_id, user_name, user_mobile, appointment_date, 
            time_slot, amount, status, consultation_type, is_tatkal, notes
        ) VALUES (?, ?, ?, ?, \"Tatkal\", ?, \"pending\", ?, 1, ?)
    ");
    
    $notes = "Tatkal booking - Number of persons: " . ($input["number_of_persons"] ?? 1);
    if (!empty($input["city"])) {
        $notes .= ", City: " . $input["city"];
    }
    
    $stmt->execute([
        $input["user_id"],
        $input["user_name"],
        $input["user_mobile"],
        $input["appointment_date"],
        $input["amount"],
        $input["consultation_type"],
        $notes
    ]);
    
    $appointment_id = $pdo->lastInsertId();
    
    echo json_encode([
        "success" => true,
        "message" => "Tatkal appointment booked successfully",
        "appointment_id" => $appointment_id,
        "amount" => $input["amount"]
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        "success" => false,
        "message" => $e->getMessage()
    ]);
}
?>
