<?php
// STEP 1: Include the header. This handles all logic and security.
require_once 'header.php';

// STEP 2: Set the page-specific title.
$page_title = 'Dashboard';

// --- ADVANCED PAGE-SPECIFIC QUERIES ---
// Note: $user, $user_id, and $wallet_balance are available from header.php

// 1. Dynamic Greeting
date_default_timezone_set('Asia/Manila');
$current_hour = (int)date('G');
if ($current_hour < 12) { $greeting = "Good morning"; } 
elseif ($current_hour < 18) { $greeting = "Good afternoon"; } 
else { $greeting = "Good evening"; }

// 2. Fetch the user's single next upcoming trip
$upcoming_trip = null;
$sql = "
    (SELECT 'Hotel' as type, h.name as title, b.check_in_date as event_date, h.location as details, b.id FROM hotel_bookings b JOIN hotels h ON b.hotel_id = h.id WHERE b.user_id = ? AND b.check_in_date >= CURDATE() AND b.status = 'Confirmed')
    UNION
    (SELECT 'Tour' as type, t.title, b.booking_date as event_date, t.location as details, b.id FROM bookings b JOIN tours t ON b.tour_id = t.id WHERE b.user_id = ? AND b.booking_date >= CURDATE() AND b.status = 'Confirmed')
    ORDER BY event_date ASC LIMIT 1
";
if ($stmt_trip = $conn->prepare($sql)) {
    $stmt_trip->bind_param("ii", $user_id, $user_id);
    $stmt_trip->execute();
    $upcoming_trip = $stmt_trip->get_result()->fetch_assoc();
    $stmt_trip->close();
}

// 3. Fetch the user's last 4 recent bookings
$recent_bookings = [];
$sql_recent = "
    (SELECT 'Hotel' as type, h.name as title, b.check_in_date as event_date, b.status FROM hotel_bookings b JOIN hotels h ON b.hotel_id = h.id WHERE b.user_id = ?)
    UNION
    (SELECT 'Tour' as type, t.title, b.booking_date as event_date, b.status FROM bookings b JOIN tours t ON b.tour_id = t.id WHERE b.user_id = ?)
    ORDER BY event_date DESC LIMIT 4
";
if ($stmt_recent = $conn->prepare($sql_recent)) {
    $stmt_recent->bind_param("ii", $user_id, $user_id);
    $stmt_recent->execute();
    $recent_bookings = $stmt_recent->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt_recent->close();
}

// 4. Fetch data for the spending summary chart
$chart_data = [];
$chart_sql = "
    (SELECT 'Tours' as category, SUM(total_price) as total FROM bookings WHERE user_id = ? AND payment_status = 'Paid')
    UNION
    (SELECT 'Hotels' as category, SUM(total_price) as total FROM hotel_bookings WHERE user_id = ? AND payment_status = 'Paid')
";
if ($stmt_chart = $conn->prepare($chart_sql)) {
    $stmt_chart->bind_param("ii", $user_id, $user_id);
    $stmt_chart->execute();
    $chart_result = $stmt_chart->get_result()->fetch_all(MYSQLI_ASSOC);
    
    // Format for Chart.js
    foreach ($chart_result as $row) {
        if ($row['total'] > 0) { // Only add categories with spending
            $chart_data['labels'][] = $row['category'];
            $chart_data['values'][] = $row['total'];
        }
    }
}
?>

<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <div>
        <h1 class="h2"><?php echo $greeting; ?>, <?php echo htmlspecialchars(strtok($user['full_name'], ' ')); ?>!</h1>
        <p class="text-muted">Here's what's happening with your account today.</p>
    </div>
</div>

<div class="row mb-4">
    <div class="col-md-4 mb-2"><a href="../tours.php" class="btn btn-primary w-100 p-3"><i class="bi bi-compass-fill me-2"></i>Browse Tours</a></div>
    <div class="col-md-4 mb-2"><a href="../hotels.php" class="btn btn-success w-100 p-3"><i class="bi bi-building me-2"></i>Find a Hotel</a></div>
    <div class="col-md-4 mb-2"><a href="top-up.php" class="btn btn-warning w-100 p-3"><i class="bi bi-wallet2 me-2"></i>Top-Up Wallet</a></div>
</div>

<div class="row">
    <div class="col-lg-7">
        <div class="card shadow-sm border-0 mb-4">
            <div class="card-header bg-white border-0 pt-3"><h5 class="mb-0"><i class="bi bi-pin-map-fill me-2 text-primary"></i>Upcoming Trip</h5></div>
            <div class="card-body">
                <?php if ($upcoming_trip): 
                    $style = get_booking_style($upcoming_trip['type']);
                ?>
                    <div class="d-flex align-items-center">
                        <div class="flex-shrink-0 me-3"><i class="bi <?php echo $style['icon']; ?> fs-1 text-<?php echo $style['color']; ?>"></i></div>
                        <div class="flex-grow-1">
                            <strong class="d-block"><?php echo htmlspecialchars($upcoming_trip['title']); ?></strong>
                            <span class="text-muted">On <?php echo date('F j, Y', strtotime($upcoming_trip['event_date'])); ?></span>
                        </div>
                        <a href="#" class="btn btn-sm btn-outline-primary">View Details</a>
                    </div>
                <?php else: ?>
                    <p class="text-muted text-center p-3 mb-0">You have no upcoming confirmed trips.</p>
                <?php endif; ?>
            </div>
        </div>
        
        <div class="card shadow-sm border-0 mb-4">
            <div class="card-header bg-white border-0 pt-3"><h5 class="mb-0"><i class="bi bi-pie-chart-fill me-2 text-success"></i>Spending Summary</h5></div>
            <div class="card-body">
                <?php if (!empty($chart_data['values'])): ?>
                    <canvas id="spendingChart"></canvas>
                <?php else: ?>
                    <p class="text-muted text-center p-3 mb-0">Your spending summary will appear here once you make a booking.</p>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <div class="col-lg-5">
        <div class="card shadow-sm border-0 mb-4">
            <div class="card-header bg-white border-0 pt-3"><h5 class="mb-0"><i class="bi bi-clock-history me-2"></i>Recent Bookings</h5></div>
            <div class="list-group list-group-flush">
                <?php if (empty($recent_bookings)): ?>
                    <div class="list-group-item text-center text-muted p-4">No recent bookings found.</div>
                <?php else: ?>
                    <?php foreach ($recent_bookings as $booking): 
                        $style = get_booking_style($booking['type']);
                    ?>
                        <a href="#" class="list-group-item list-group-item-action d-flex align-items-center">
                            <i class="bi <?php echo $style['icon']; ?> fs-3 me-3 text-<?php echo $style['color']; ?>"></i>
                            <div>
                                <strong class="d-block"><?php echo htmlspecialchars($booking['title']); ?></strong>
                                <small class="text-muted">Booked on <?php echo date('M d, Y', strtotime($booking['event_date'])); ?></small>
                            </div>
                        </a>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>

        <div class="card shadow-sm border-0">
            <div class="card-body">
                <h5 class="card-title"><i class="bi bi-people-fill me-2 text-warning"></i>Affiliate Program</h5>
                <p class="text-muted">Share your code to earn rewards!</p>
                <div class="input-group">
                    <input type="text" class="form-control" value="<?php echo htmlspecialchars($user['affiliate_code'] ?? 'N/A'); ?>" readonly>
                    <button class="btn btn-outline-secondary" type="button">Copy</button>
                </div>
                <div class="mt-2"><strong>Earnings:</strong> <?php echo format_price($user['affiliate_earnings'] ?? 0); ?></div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
    <?php if (!empty($chart_data['values'])): ?>
    document.addEventListener('DOMContentLoaded', function() {
        const ctx = document.getElementById('spendingChart');
        new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: <?php echo json_encode($chart_data['labels']); ?>,
                datasets: [{
                    label: 'Spending',
                    data: <?php echo json_encode($chart_data['values']); ?>,
                    backgroundColor: [
                        'rgba(59, 130, 246, 0.8)', // Primary Blue
                        'rgba(22, 163, 74, 0.8)',  // Green
                        'rgba(239, 68, 68, 0.8)',  // Red
                        'rgba(245, 158, 11, 0.8)'  // Amber
                    ],
                    borderColor: '#ffffff',
                    borderWidth: 2
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        position: 'bottom',
                    }
                }
            }
        });
    });
    <?php endif; ?>
</script>

<?php 
require_once 'footer.php'; 
?>
