<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

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

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

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

try {
    $userId = $_GET['user_id'] ?? null;
    
    if (!$userId) {
        throw new Exception('User ID parameter is required');
    }
    
    // Validate user_id
    if (!is_numeric($userId) || $userId <= 0) {
        throw new Exception('Invalid user ID');
    }
    
    $pdo = getDBConnection();
    
    // Verify user exists
    $stmt = $pdo->prepare("SELECT id FROM users WHERE id = ?");
    $stmt->execute([$userId]);
    if (!$stmt->fetch()) {
        throw new Exception('User not found');
    }
    
    // Get user appointments
    $stmt = $pdo->prepare("
        SELECT 
            id, user_id, user_name, user_mobile, appointment_date, 
            time_slot, amount, status, created_at
        FROM appointments 
        WHERE user_id = ? 
        ORDER BY appointment_date DESC, created_at DESC
    ");
    $stmt->execute([$userId]);
    
    $appointments = $stmt->fetchAll();
    
    // Format dates for better readability
    foreach ($appointments as &$appointment) {
        $appointment['appointment_date_formatted'] = date('l, M d, Y', strtotime($appointment['appointment_date']));
        $appointment['created_at_formatted'] = date('M d, Y H:i', strtotime($appointment['created_at']));
    }
    
    echo json_encode([
        'success' => true,
        'user_id' => $userId,
        'appointments' => $appointments,
        'total_appointments' => count($appointments)
    ]);
    
} 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'
    ]);
}
?>