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

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

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

try {
    $pdo = getDBConnection();
    
    // Get all bookings for today (appointment_date = today)
    $bookings = $pdo->query("
        SELECT 
            a.id,
            a.user_name,
            a.user_mobile,
            a.time_slot,
            a.amount,
            a.status,
            a.consultation_type,
            a.created_at
        FROM appointments a
        WHERE DATE(a.appointment_date) = CURDATE()
        ORDER BY a.created_at DESC
    ")->fetchAll(PDO::FETCH_ASSOC);
    
    // Format the bookings
    foreach ($bookings as &$booking) {
        $booking['created_at'] = date('M d, Y H:i', strtotime($booking['created_at']));
        $booking['consultation_type'] = ucwords(str_replace('_', ' ', $booking['consultation_type']));
    }
    
    echo json_encode([
        'success' => true,
        'bookings' => $bookings,
        'count' => count($bookings)
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
?>
