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

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

try {
    // Get user ID from query parameter
    $userId = isset($_GET['user_id']) ? (int)$_GET['user_id'] : 0;
    
    if ($userId <= 0) {
        echo json_encode([
            'success' => false,
            'message' => 'Valid user ID is required'
        ]);
        exit;
    }
    
    // Get database connection
    $pdo = getDBConnection();
    
    // Query to get booking history for the user
    $sql = "SELECT 
                id,
                appointment_date,
                time_slot,
                amount,
                status,
                consultation_type,
                created_at
            FROM appointments 
            WHERE user_id = :user_id 
            ORDER BY created_at DESC";
    
    $stmt = $pdo->prepare($sql);
    $stmt->bindParam(':user_id', $userId, PDO::PARAM_INT);
    $stmt->execute();
    
    $bookings = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Process bookings to clean up data
    foreach ($bookings as &$booking) {
        // Clean up consultation_type - remove all invalid values
        if (empty($booking['consultation_type']) || 
            $booking['consultation_type'] === 'N/A' || 
            $booking['consultation_type'] === null ||
            $booking['consultation_type'] === 'null' ||
            trim($booking['consultation_type']) === '') {
            $booking['consultation_type'] = null;
        }
        
        // Ensure amount is properly formatted
        if (isset($booking['amount'])) {
            $booking['amount'] = (float)$booking['amount'];
        }
    }
    
    // Format the response
    $response = [
        'success' => true,
        'bookings' => $bookings,
        'total_bookings' => count($bookings)
    ];
    
    echo json_encode($response);
    
} catch (Exception $e) {
    error_log("Error in get_booking_history.php: " . $e->getMessage());
    
    echo json_encode([
        'success' => false,
        'message' => 'Database error occurred',
        'error' => $e->getMessage()
    ]);
}
?>
