<?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 users with their booking count
    $users = $pdo->query("
        SELECT 
            u.id,
            u.name,
            u.mobile,
            u.email,
            u.created_at,
            COUNT(a.id) as total_bookings
        FROM users u
        LEFT JOIN appointments a ON u.id = a.user_id
        GROUP BY u.id, u.name, u.mobile, u.email, u.created_at
        ORDER BY u.created_at DESC
    ")->fetchAll(PDO::FETCH_ASSOC);
    
    // Format the users
    foreach ($users as &$user) {
        $user['created_at'] = date('M d, Y', strtotime($user['created_at']));
    }
    
    echo json_encode([
        'success' => true,
        'users' => $users,
        'count' => count($users)
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
?>
