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

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

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

try {
    $pdo = getDBConnection();
    
    // Get the latest appointment
    $stmt = $pdo->prepare("
        SELECT id, user_id, user_name, appointment_date, time_slot, amount, status, created_at, updated_at
        FROM appointments 
        ORDER BY created_at DESC 
        LIMIT 1
    ");
    $stmt->execute();
    $latestAppointment = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // Get all appointments from today
    $stmt = $pdo->prepare("
        SELECT id, user_id, user_name, appointment_date, time_slot, amount, status, created_at, updated_at
        FROM appointments 
        WHERE DATE(created_at) = CURDATE()
        ORDER BY created_at DESC
    ");
    $stmt->execute();
    $todayAppointments = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Check database schema
    $stmt = $pdo->prepare("
        SHOW COLUMNS FROM appointments LIKE 'status'
    ");
    $stmt->execute();
    $statusColumn = $stmt->fetch(PDO::FETCH_ASSOC);
    
    echo json_encode([
        'success' => true,
        'latest_appointment' => $latestAppointment,
        'today_appointments' => $todayAppointments,
        'status_column_info' => $statusColumn,
        'total_today' => count($todayAppointments)
    ]);
    
} 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: ' . $e->getMessage()
    ]);
}
?>
