<?php
/**
 * Test Dashboard Data Fetching
 * This file tests whether room reservations and service reservations are fetching correctly
 */

session_start();

// Include database and helper functions
require_once 'config/database.php';
require_once 'config/session.php';

// Check if user is logged in
if (!isLoggedIn()) {
    echo json_encode([
        'success' => false,
        'error' => 'Not logged in'
    ]);
    exit;
}

$userId = getCurrentUserId();
$results = [
    'user_id' => $userId,
    'room_reservations' => [],
    'service_reservations' => [],
    'errors' => [],
    'debug_info' => []
];

try {
    // Test Room Reservations Query
    $results['debug_info'][] = "Testing room reservations query for user_id: $userId";
    
    $sql = "SELECT r.id, r.user_id, r.room_id, r.check_in_date, r.check_out_date, 
                   r.number_of_guests, r.number_of_rooms, r.total_price, r.status, 
                   r.special_requests, r.payment_status, r.payment_method, r.transaction_id,
                   r.created_at, r.updated_at,
                   ro.room_number, ro.room_type, ro.description, ro.max_guests, 
                   ro.price_per_night, ro.size_sqft, ro.floor_number, ro.view_type, ro.image_url
            FROM reservations r
            JOIN rooms ro ON r.room_id = ro.id
            WHERE r.user_id = ?
            ORDER BY r.check_in_date DESC";
    
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        $results['errors'][] = "Room reservations query prepare failed: " . $conn->error;
    } else {
        $stmt->bind_param('i', $userId);
        $stmt->execute();
        $result = $stmt->get_result();
        $results['room_reservations'] = $result->fetch_all(MYSQLI_ASSOC);
        $results['debug_info'][] = "Room reservations found: " . count($results['room_reservations']);
        
        if (count($results['room_reservations']) > 0) {
            $first_res = $results['room_reservations'][0];
            $results['debug_info'][] = "First reservation keys: " . implode(", ", array_keys($first_res));
        }
    }
    
    // Test Service Reservations Query
    $results['debug_info'][] = "Testing service reservations query for user_id: $userId";
    
    $sql = "SELECT sr.id, sr.user_id, sr.facility_id, sr.service_start_date, sr.service_end_date, 
                   sr.number_of_guests, sr.service_price, sr.total_price, sr.status, sr.special_requests,
                   sr.created_at, sr.updated_at,
                   f.id as facility_id_check, f.name as facility_name, f.icon, f.description, f.image_url
            FROM service_reservations sr
            JOIN facilities f ON sr.facility_id = f.id
            WHERE sr.user_id = ?
            ORDER BY sr.service_start_date DESC";
    
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        $results['errors'][] = "Service reservations query prepare failed: " . $conn->error;
    } else {
        $stmt->bind_param('i', $userId);
        $stmt->execute();
        $result = $stmt->get_result();
        $results['service_reservations'] = $result->fetch_all(MYSQLI_ASSOC);
        $results['debug_info'][] = "Service reservations found: " . count($results['service_reservations']);
        
        if (count($results['service_reservations']) > 0) {
            $first_service = $results['service_reservations'][0];
            $results['debug_info'][] = "First service keys: " . implode(", ", array_keys($first_service));
        }
    }
    
} catch (Exception $e) {
    $results['errors'][] = "Exception: " . $e->getMessage();
}

// Display results
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard Data Test</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <style>
        body { padding: 20px; }
        .section { margin-bottom: 30px; padding: 15px; border: 1px solid #ddd; border-radius: 5px; }
        .error { color: #d32f2f; background-color: #ffebee; padding: 10px; border-radius: 3px; margin-bottom: 10px; }
        .success { color: #388e3c; background-color: #e8f5e9; padding: 10px; border-radius: 3px; margin-bottom: 10px; }
        .debug { color: #1976d2; background-color: #e3f2fd; padding: 10px; border-radius: 3px; margin: 5px 0; font-family: monospace; font-size: 12px; }
        .reservation-item { padding: 10px; background-color: #f5f5f5; margin: 10px 0; border-radius: 3px; }
        .field { margin: 5px 0; }
        .field-name { font-weight: bold; color: #333; }
        .field-value { color: #666; }
    </style>
</head>
<body>
    <div class="container">
        <h1>Dashboard Data Fetching Test</h1>
        
        <div class="section">
            <h2>Test Status</h2>
            <?php if (empty($results['errors'])): ?>
                <div class="success">✓ No errors encountered</div>
            <?php else: ?>
                <div class="error">✗ Errors found:</div>
                <?php foreach ($results['errors'] as $error): ?>
                    <div class="error"><?php echo htmlspecialchars($error); ?></div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
        
        <div class="section">
            <h2>Debug Information</h2>
            <?php foreach ($results['debug_info'] as $info): ?>
                <div class="debug"><?php echo htmlspecialchars($info); ?></div>
            <?php endforeach; ?>
        </div>
        
        <div class="section">
            <h2>Room Reservations (<?php echo count($results['room_reservations']); ?> found)</h2>
            <?php if (empty($results['room_reservations'])): ?>
                <p><em>No room reservations found for this user</em></p>
            <?php else: ?>
                <?php foreach ($results['room_reservations'] as $res): ?>
                    <div class="reservation-item">
                        <h4><?php echo htmlspecialchars($res['room_type'] ?? 'Room'); ?> - Room #<?php echo htmlspecialchars($res['room_number'] ?? 'N/A'); ?></h4>
                        <div class="field">
                            <span class="field-name">ID:</span>
                            <span class="field-value"><?php echo htmlspecialchars($res['id']); ?></span>
                        </div>
                        <div class="field">
                            <span class="field-name">Check-in:</span>
                            <span class="field-value"><?php echo htmlspecialchars($res['check_in_date']); ?></span>
                        </div>
                        <div class="field">
                            <span class="field-name">Check-out:</span>
                            <span class="field-value"><?php echo htmlspecialchars($res['check_out_date']); ?></span>
                        </div>
                        <div class="field">
                            <span class="field-name">Guests:</span>
                            <span class="field-value"><?php echo htmlspecialchars($res['number_of_guests']); ?></span>
                        </div>
                        <div class="field">
                            <span class="field-name">Total Price:</span>
                            <span class="field-value">$<?php echo number_format($res['total_price'], 2); ?></span>
                        </div>
                        <div class="field">
                            <span class="field-name">Status:</span>
                            <span class="field-value"><?php echo htmlspecialchars($res['status']); ?></span>
                        </div>
                        <div class="field">
                            <span class="field-name">Payment Status:</span>
                            <span class="field-value"><?php echo htmlspecialchars($res['payment_status']); ?></span>
                        </div>
                        <details>
                            <summary>All Fields</summary>
                            <pre><?php echo htmlspecialchars(json_encode($res, JSON_PRETTY_PRINT)); ?></pre>
                        </details>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
        
        <div class="section">
            <h2>Service Reservations (<?php echo count($results['service_reservations']); ?> found)</h2>
            <?php if (empty($results['service_reservations'])): ?>
                <p><em>No service reservations found for this user</em></p>
            <?php else: ?>
                <?php foreach ($results['service_reservations'] as $service): ?>
                    <div class="reservation-item">
                        <h4><?php echo htmlspecialchars($service['facility_name'] ?? 'Service'); ?></h4>
                        <div class="field">
                            <span class="field-name">ID:</span>
                            <span class="field-value"><?php echo htmlspecialchars($service['id']); ?></span>
                        </div>
                        <div class="field">
                            <span class="field-name">Start Date:</span>
                            <span class="field-value"><?php echo htmlspecialchars($service['service_start_date']); ?></span>
                        </div>
                        <div class="field">
                            <span class="field-name">End Date:</span>
                            <span class="field-value"><?php echo htmlspecialchars($service['service_end_date']); ?></span>
                        </div>
                        <div class="field">
                            <span class="field-name">Guests:</span>
                            <span class="field-value"><?php echo htmlspecialchars($service['number_of_guests']); ?></span>
                        </div>
                        <div class="field">
                            <span class="field-name">Total Price:</span>
                            <span class="field-value">$<?php echo number_format($service['total_price'], 2); ?></span>
                        </div>
                        <div class="field">
                            <span class="field-name">Status:</span>
                            <span class="field-value"><?php echo htmlspecialchars($service['status']); ?></span>
                        </div>
                        <details>
                            <summary>All Fields</summary>
                            <pre><?php echo htmlspecialchars(json_encode($service, JSON_PRETTY_PRINT)); ?></pre>
                        </details>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
        
        <div class="section">
            <a href="dashboard.php" class="btn btn-primary">Back to Dashboard</a>
        </div>
    </div>
</body>
</html>
