<?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 statistics
    $stats = [];
    
    // Total users
    $userCount = $pdo->query("SELECT COUNT(*) FROM users")->fetchColumn();
    $stats['total_users'] = (int)$userCount;
    
    // Today's bookings (appointments created today)
    $todayBookings = $pdo->query("SELECT COUNT(*) FROM appointments WHERE DATE(created_at) = CURDATE()")->fetchColumn();
    $stats['today_bookings'] = (int)$todayBookings;
    
    // Total bookings
    $totalBookings = $pdo->query("SELECT COUNT(*) FROM appointments")->fetchColumn();
    $stats['total_bookings'] = (int)$totalBookings;
    
    // Today's revenue (from confirmed bookings created today)
    $todayRevenue = $pdo->query("SELECT COALESCE(SUM(amount), 0) FROM appointments WHERE DATE(created_at) = CURDATE() AND status = 'confirmed'")->fetchColumn();
    $stats['today_revenue'] = (float)$todayRevenue;
    
    // Total revenue
    $totalRevenue = $pdo->query("SELECT COALESCE(SUM(amount), 0) FROM appointments WHERE status = 'confirmed'")->fetchColumn();
    $stats['total_revenue'] = (float)$totalRevenue;
    
    // Tatkal bookings today (check time_slot = 'tatkal')
    $tatkalToday = $pdo->query("SELECT COUNT(*) FROM appointments WHERE time_slot = 'tatkal' AND DATE(created_at) = CURDATE()")->fetchColumn();
    $stats['tatkal_today'] = (int)$tatkalToday;
    
    // Pending bookings
    $pendingBookings = $pdo->query("SELECT COUNT(*) FROM appointments WHERE status = 'pending'")->fetchColumn();
    $stats['pending_bookings'] = (int)$pendingBookings;
    
    // Confirmed bookings today
    $confirmedToday = $pdo->query("SELECT COUNT(*) FROM appointments WHERE DATE(appointment_date) = CURDATE() AND status = 'confirmed'")->fetchColumn();
    $stats['confirmed_today'] = (int)$confirmedToday;
    
    // Revenue from confirmed bookings today
    $confirmedRevenueToday = $pdo->query("SELECT COALESCE(SUM(amount), 0) FROM appointments WHERE DATE(appointment_date) = CURDATE() AND status = 'confirmed'")->fetchColumn();
    $stats['confirmed_revenue_today'] = (float)$confirmedRevenueToday;
    
    // Recent bookings with user names
    $recentBookings = $pdo->query("
        SELECT 
            a.appointment_date, 
            a.time_slot, 
            a.amount, 
            a.status, 
            a.consultation_type, 
            a.created_at,
            u.name as user_name
        FROM appointments a
        LEFT JOIN users u ON a.user_id = u.id
        ORDER BY a.created_at DESC 
        LIMIT 10
    ")->fetchAll(PDO::FETCH_ASSOC);
    
    // Format recent bookings
    foreach ($recentBookings as &$booking) {
        $booking['appointment_date'] = date('M d, Y', strtotime($booking['appointment_date']));
        $booking['created_at'] = date('M d, Y H:i', strtotime($booking['created_at']));
        $booking['consultation_type'] = ucwords(str_replace('_', ' ', $booking['consultation_type']));
        $booking['user_name'] = $booking['user_name'] ?: 'Unknown User';
    }
    
    echo json_encode([
        'success' => true,
        'stats' => $stats,
        'recent_bookings' => $recentBookings
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
?>
