<?php
// Remove BOM and set proper encoding
ob_clean();
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-cache, must-revalidate');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

// Handle preflight request
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    http_response_code(200);
    exit();
}

// Include database configuration
require_once '../config/database.php';

try {
    $pdo = getDBConnection();
} catch (Exception $e) {
    $response = ['success' => false, 'message' => 'Database connection failed: ' . $e->getMessage()];
    echo json_encode($response, JSON_UNESCAPED_UNICODE);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    
    // Debug log
    error_log('Tatkal booking request: ' . print_r($input, true));
    
    // Check if input is valid
    if (!$input) {
        $response = ['success' => false, 'message' => 'Invalid JSON input'];
        echo json_encode($response, JSON_UNESCAPED_UNICODE);
        exit();
    }
    
    // Validate required fields
    $required_fields = ['user_id', 'user_name', 'user_mobile', 'appointment_date', 'time_slot', 'amount', 'consultation_type'];
    foreach ($required_fields as $field) {
        if (!isset($input[$field]) || empty($input[$field])) {
            $response = ['success' => false, 'message' => "Missing required field: $field"];
            echo json_encode($response, JSON_UNESCAPED_UNICODE);
            exit();
        }
    }
    
    try {
        // Insert tatkal appointment using same structure as normal booking
        $sql = "INSERT INTO appointments (
            user_id, 
            user_name, 
            user_mobile, 
            appointment_date, 
            time_slot, 
            amount, 
            status
        ) VALUES (?, ?, ?, ?, ?, ?, 'confirmed')";
        
        $result = $pdo->prepare($sql)->execute([
            $input['user_id'],
            $input['user_name'],
            $input['user_mobile'],
            $input['appointment_date'],
            $input['time_slot'],
            $input['amount']
        ]);
        
        if ($result) {
            $appointment_id = $pdo->lastInsertId();
            $response = [
                'success' => true, 
                'message' => 'Tatkal appointment booked successfully',
                'appointment_id' => $appointment_id
            ];
            echo json_encode($response, JSON_UNESCAPED_UNICODE);
        } else {
            $response = ['success' => false, 'message' => 'Failed to book appointment'];
            echo json_encode($response, JSON_UNESCAPED_UNICODE);
        }
        
    } catch (Exception $e) {
        $response = ['success' => false, 'message' => 'Error: ' . $e->getMessage()];
        echo json_encode($response, JSON_UNESCAPED_UNICODE);
    }
} else {
    $response = ['success' => false, 'message' => 'Invalid request method'];
    echo json_encode($response, JSON_UNESCAPED_UNICODE);
}
?>