<?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 {
    // Get database connection
    $pdo = getDBConnection();
    
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input) {
        throw new Exception('Invalid JSON input');
    }
    
    // Basic validation only
    if (empty($input['user_id']) || empty($input['user_name']) || empty($input['user_mobile']) || 
        empty($input['appointment_date']) || empty($input['time_slot']) || empty($input['amount'])) {
        throw new Exception('Required fields missing');
    }
    
    // Validate user_id is numeric
    if (!is_numeric($input['user_id'])) {
        throw new Exception('Invalid user ID');
    }
    
    // Validate amount is numeric
    if (!is_numeric($input['amount'])) {
        throw new Exception('Invalid amount');
    }
    
    // Check if slot is still available (only block confirmed/completed)
    $stmt = $pdo->prepare("
        SELECT id FROM appointments 
        WHERE appointment_date = ? AND time_slot = ? 
        AND status IN ('confirmed', 'completed')
    ");
    $stmt->execute([$input['appointment_date'], $input['time_slot']]);
    if ($stmt->fetch()) {
        throw new Exception('This time slot is no longer available');
    }

    // Insert appointment directly without any checks
    $stmt = $pdo->prepare("
        INSERT INTO appointments (
            user_id, user_name, user_mobile, appointment_date, 
            time_slot, amount, status, consultation_type, created_at
        ) VALUES (?, ?, ?, ?, ?, ?, 'pending', ?, NOW())
    ");
    
    $result = $stmt->execute([
        intval($input['user_id']),
        trim($input['user_name']),
        trim($input['user_mobile']),
        trim($input['appointment_date']),
        trim($input['time_slot']),
        floatval($input['amount']),
        $input['consultation_type'] ?? 'office_meeting'
    ]);
    
    if (!$result) {
        throw new Exception('Failed to insert appointment');
    }
    
    $appointmentId = $pdo->lastInsertId();
    
    echo json_encode([
        'success' => true,
        'message' => 'Appointment booked successfully',
        'appointment_id' => $appointmentId,
        'appointment_date' => $input['appointment_date'],
        'time_slot' => $input['time_slot'],
        'amount' => $input['amount']
    ]);
    
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Database error occurred'
    ]);
}
?>
