<?php 
include 'header.php'; 

// --- DYNAMIC DATA FETCHING FOR PARTNER DASHBOARD ---
$first_day_of_month = date('Y-m-01 00:00:00');
$chart_labels = [];
$chart_data = [];

if ($partner_role == 'tour_partner') {
    $my_listings_count = $conn->query("SELECT COUNT(*) as total FROM tours WHERE partner_id = $partner_id")->fetch_assoc()['total'];
    $my_bookings_month = $conn->query("SELECT COUNT(*) as total FROM bookings WHERE tour_id IN (SELECT id FROM tours WHERE partner_id = $partner_id) AND created_at >= '$first_day_of_month'")->fetch_assoc()['total'];
    $my_revenue_month = $conn->query("SELECT SUM(total_price) as total FROM bookings WHERE tour_id IN (SELECT id FROM tours WHERE partner_id = $partner_id) AND payment_status = 'Paid' AND created_at >= '$first_day_of_month'")->fetch_assoc()['total'];
    
    // Chart Data for Tours
    for ($i = 6; $i >= 0; $i--) {
        $date = date('Y-m-d', strtotime("-$i days"));
        $chart_labels[] = date('M d', strtotime($date));
        $daily_rev = $conn->query("SELECT SUM(total_price) as total FROM bookings WHERE tour_id IN (SELECT id FROM tours WHERE partner_id = $partner_id) AND payment_status = 'Paid' AND DATE(created_at) = '$date'")->fetch_assoc()['total'];
        $chart_data[] = $daily_rev ?? 0;
    }
} elseif ($partner_role == 'hotel_partner') {
    $my_listings_count = $conn->query("SELECT COUNT(*) as total FROM hotels WHERE partner_id = $partner_id")->fetch_assoc()['total'];
    $my_bookings_month = $conn->query("SELECT COUNT(*) as total FROM hotel_bookings WHERE hotel_id IN (SELECT id FROM hotels WHERE partner_id = $partner_id) AND created_at >= '$first_day_of_month'")->fetch_assoc()['total'];
    $my_revenue_month = $conn->query("SELECT SUM(total_price) as total FROM hotel_bookings WHERE hotel_id IN (SELECT id FROM hotels WHERE partner_id = $partner_id) AND payment_status = 'Paid' AND created_at >= '$first_day_of_month'")->fetch_assoc()['total'];

    // Chart Data for Hotels
    for ($i = 6; $i >= 0; $i--) {
        $date = date('Y-m-d', strtotime("-$i days"));
        $chart_labels[] = date('M d', strtotime($date));
        $daily_rev = $conn->query("SELECT SUM(total_price) as total FROM hotel_bookings WHERE hotel_id IN (SELECT id FROM hotels WHERE partner_id = $partner_id) AND payment_status = 'Paid' AND DATE(created_at) = '$date'")->fetch_assoc()['total'];
        $chart_data[] = $daily_rev ?? 0;
    }
}
?>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<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">Dashboard</h1>
        <p class="text-muted">Welcome to your business overview, <?php echo htmlspecialchars($partner_name); ?>.</p>
    </div>
    <?php if ($user['is_verified']): ?><span class="verified-badge fs-6"><i class="bi bi-patch-check-fill"></i> Verified Partner</span><?php endif; ?>
</div>

<div class="row row-deck">
    <div class="col-md-4 mb-4">
        <div class="card kpi-card shadow-sm" style="--bs-primary: #6f42c1;"><div class="card-body"><div class="row align-items-center"><div class="col"><div class="card-title">My Listings</div><div class="card-text"><?php echo $my_listings_count ?? 0; ?></div></div><div class="col-auto"><i class="bi bi-card-list kpi-icon"></i></div></div></div></div>
    </div>
    <div class="col-md-4 mb-4">
        <div class="card kpi-card shadow-sm" style="--bs-primary: #0d6efd;"><div class="card-body"><div class="row align-items-center"><div class="col"><div class="card-title">Bookings (This Month)</div><div class="card-text"><?php echo $my_bookings_month ?? 0; ?></div></div><div class="col-auto"><i class="bi bi-calendar-check kpi-icon"></i></div></div></div></div>
    </div>
    <div class="col-md-4 mb-4">
        <div class="card kpi-card shadow-sm" style="--bs-primary: #198754;"><div class="card-body"><div class="row align-items-center"><div class="col"><div class="card-title">Gross Revenue (Month)</div><div class="card-text">₱<?php echo number_format($my_revenue_month ?? 0, 2); ?></div></div><div class="col-auto"><i class="bi bi-cash-coin kpi-icon"></i></div></div></div></div>
    </div>
</div>

<div class="row">
    <div class="col-lg-8 mb-4">
        <div class="card shadow-sm h-100">
            <div class="card-header fw-bold"><i class="bi bi-bar-chart-line-fill me-2"></i>Gross Revenue (Last 7 Days)</div>
            <div class="card-body" style="min-height: 350px;"><canvas id="performanceChart"></canvas></div>
        </div>
    </div>
    <div class="col-lg-4 mb-4">
         <?php if ($user['profile_page_status'] == 'Active'): ?>
        <div class="card shadow-sm mb-4 bg-success text-white">
            <div class="card-body text-center">
                <i class="bi bi-shop fs-1"></i><h5 class="card-title mt-2">Your Storefront is Live!</h5>
                <p>View your public profile page to see all your listings.</p>
                <a href="/partners/<?php echo htmlspecialchars($user['profile_slug']); ?>" class="btn btn-light" target="_blank">View My Storefront</a>
            </div>
        </div>
        <?php endif; ?>
        <div class="card shadow-sm">
            <div class="card-header fw-bold"><i class="bi bi-plus-circle-fill me-2"></i>Manage My Listings</div>
            <div class="card-body text-center d-flex flex-column justify-content-center">
                 <?php if ($partner_role == 'tour_partner'): ?><a href="manage-tours.php" class="btn btn-primary btn-lg">Add / Edit My Tours</a>
                <?php elseif ($partner_role == 'hotel_partner'): ?><a href="manage-hotels.php" class="btn btn-primary btn-lg">Add / Edit My Hotels</a><?php endif; ?>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener("DOMContentLoaded", function() {
    const ctx = document.getElementById('performanceChart')?.getContext('2d');
    if (ctx) {
        new Chart(ctx, {
            type: 'line', data: { labels: <?php echo json_encode($chart_labels); ?>, datasets: [{ label: 'Gross Revenue', data: <?php echo json_encode($chart_data); ?>, backgroundColor: 'rgba(54, 162, 235, 0.2)', borderColor: 'rgba(54, 162, 235, 1)', borderWidth: 2, tension: 0.3, fill: true }] },
            options: { responsive: true, maintainAspectRatio: false, scales: { y: { beginAtZero: true } }, plugins: { legend: { display: false } } }
        });
    }
});
</script>
<?php include 'footer.php'; ?>
