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

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

if (['REQUEST_METHOD'] == 'OPTIONS') {
    exit(0);
}

 = ['action'] ?? '';

try {
     = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASS);
    ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    if ( == 'book') {
         = json_decode(file_get_contents('php://input'), true);
        
         = ['user_id'] ?? '';
         = ['user_name'] ?? '';
         = ['user_mobile'] ?? '';
         = ['appointment_date'] ?? '';
         = ['time_slot'] ?? '';
         = ['amount'] ?? 0;
         = ['no_of_persons'] ?? 1;

        if (empty() || empty() || empty()) {
            echo json_encode(["success" => false, "message" => "Missing required fields"]);
            exit;
        }

        // Check if tatkal is enabled
         = ->prepare("SELECT * FROM tatkal_settings WHERE id = 1");
        ->execute();
         = ->fetch(PDO::FETCH_ASSOC);

        if (! || ['is_enabled'] != 1) {
            echo json_encode(["success" => false, "message" => "Tatkal booking is currently disabled"]);
            exit;
        }

        // Check if date is within advance booking limit
         = new DateTime();
         = new DateTime();
         = ->diff()->days;
        
        if ( > ['advance_booking_days']) {
            echo json_encode(["success" => false, "message" => "Booking not allowed beyond " . ['advance_booking_days'] . " days"]);
            exit;
        }

        // Check if slot is available
         = ->prepare("SELECT COUNT(*) as count FROM tatkal_appointments WHERE appointment_date = ? AND time_slot = ?");
        ->execute([, ]);
         = ->fetch(PDO::FETCH_ASSOC)['count'];

        if ( >= ['max_slots_per_day']) {
            echo json_encode(["success" => false, "message" => "This time slot is fully booked"]);
            exit;
        }

        // Book the appointment
         = ->prepare("
            INSERT INTO tatkal_appointments 
            (user_id, user_name, user_mobile, appointment_date, time_slot, amount, no_of_persons, status, created_at) 
            VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', NOW())
        ");
        
         = ->execute([
            , , , , 
            , , 
        ]);

        if () {
            echo json_encode(["success" => true, "message" => "Tatkal appointment booked successfully"]);
        } else {
            echo json_encode(["success" => false, "message" => "Failed to book appointment"]);
        }

    } elseif ( == 'get_available_slots') {
         = ['date'] ?? '';
        
        if (empty()) {
            echo json_encode(["success" => false, "message" => "Date is required"]);
            exit;
        }

        // Get tatkal settings
         = ->prepare("SELECT * FROM tatkal_settings WHERE id = 1");
        ->execute();
         = ->fetch(PDO::FETCH_ASSOC);

        if (! || ['is_enabled'] != 1) {
            echo json_encode(["success" => false, "message" => "Tatkal booking is disabled"]);
            exit;
        }

        // Generate time slots (9 AM to 6 PM, 1 hour each)
         = [];
        for ( = 9;  < 18; ++) {
            [] = sprintf("%02d:00 - %02d:00", ,  + 1);
        }

        // Check booked slots
         = ->prepare("SELECT time_slot FROM tatkal_appointments WHERE appointment_date = ?");
        ->execute([]);
         = ->fetchAll(PDO::FETCH_COLUMN);

         = [];
        foreach ( as ) {
             = count(array_filter(, function() use () {
                return  === ;
            }));
            
            if ( < ['max_slots_per_day']) {
                [] = [
                    'time_slot' => ,
                    'available' => ['max_slots_per_day'] - ,
                    'price' => ['price']
                ];
            }
        }

        echo json_encode([
            "success" => true,
            "date" => ,
            "slots" => ,
            "price" => ['price']
        ]);

    } else {
        echo json_encode(["success" => false, "message" => "Invalid action"]);
    }

} catch (Exception ) {
    echo json_encode(["success" => false, "message" => "Error: " . ->getMessage()]);
}
?>
