<?php
$pageTitle = 'Dashboard';
require_once __DIR__ . '/includes/header.php';

$db = Database::getInstance();

$totalRestaurants = $db->count('restaurants');
$activeRestaurants = $db->count('restaurants', "status = 'active'");
$suspendedRestaurants = $db->count('restaurants', "status = 'suspended'");
$trialRestaurants = $db->count('restaurants', "status = 'trial'");
$expiredRestaurants = $db->count('restaurants', "status = 'expired'");
$totalOrders = $db->count('orders');
$ordersToday = $db->count('orders', "DATE(created_at) = CURDATE()");
$totalEnquiries = $db->count('enquiries');
$newEnquiries = $db->count('enquiries', "status = 'new'");
$totalMenuItems = $db->count('menu_items');
$totalUsers = $db->count('users');

$stmtRevenue = $db->query("SELECT COALESCE(SUM(grand_total), 0) as total FROM orders WHERE payment_status = 'paid'");
$revenue = $stmtRevenue->fetch()['total'];

$startDate = $_GET['start_date'] ?? date('Y-m-01');
$endDate = $_GET['end_date'] ?? date('Y-m-d');

$stmtMonthlyRestaurants = $db->query("
    SELECT DATE_FORMAT(created_at, '%Y-%m') as month, COUNT(*) as count
    FROM restaurants
    WHERE created_at >= DATE_SUB(NOW(), INTERVAL 12 MONTH)
    GROUP BY DATE_FORMAT(created_at, '%Y-%m')
    ORDER BY month ASC
");
$monthlyRestaurants = $stmtMonthlyRestaurants->fetchAll();

$stmtMonthlyOrders = $db->query("
    SELECT DATE_FORMAT(created_at, '%Y-%m') as month, COUNT(*) as count
    FROM orders
    WHERE created_at >= DATE_SUB(NOW(), INTERVAL 12 MONTH)
    GROUP BY DATE_FORMAT(created_at, '%Y-%m')
    ORDER BY month ASC
");
$monthlyOrders = $stmtMonthlyOrders->fetchAll();

$stmtPlanDistribution = $db->query("
    SELECT sp.name, COUNT(r.id) as count
    FROM restaurants r
    LEFT JOIN subscription_plans sp ON r.plan_id = sp.id
    GROUP BY r.plan_id, sp.name
");
$planDistribution = $stmtPlanDistribution->fetchAll();

$stmtMonthlyRevenue = $db->query("
    SELECT DATE_FORMAT(created_at, '%Y-%m') as month, COALESCE(SUM(grand_total), 0) as total
    FROM orders
    WHERE payment_status = 'paid' AND created_at >= DATE_SUB(NOW(), INTERVAL 12 MONTH)
    GROUP BY DATE_FORMAT(created_at, '%Y-%m')
    ORDER BY month ASC
");
$monthlyRevenue = $stmtMonthlyRevenue->fetchAll();

$recentRestaurants = $db->query("
    SELECT r.*, sp.name as plan_name, u.name as owner_name
    FROM restaurants r
    LEFT JOIN subscription_plans sp ON r.plan_id = sp.id
    LEFT JOIN users u ON u.restaurant_id = r.id AND u.role_id = 2
    ORDER BY r.created_at DESC
    LIMIT 10
")->fetchAll();

$expiringSubscriptions = $db->query("
    SELECT r.*, sp.name as plan_name, u.name as owner_name
    FROM restaurants r
    LEFT JOIN subscription_plans sp ON r.plan_id = sp.id
    LEFT JOIN users u ON u.restaurant_id = r.id AND u.role_id = 2
    WHERE r.subscription_end IS NOT NULL
    AND r.subscription_end BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 30 DAY)
    AND r.status = 'active'
    ORDER BY r.subscription_end ASC
    LIMIT 10
")->fetchAll();

$recentEnquiries = $db->query("
    SELECT * FROM enquiries ORDER BY created_at DESC LIMIT 10
")->fetchAll();

$chartMonths = [];
$chartMonthLabels = [];
for ($i = 11; $i >= 0; $i--) {
    $chartMonths[] = date('Y-m', strtotime("-{$i} months"));
    $chartMonthLabels[] = date('M Y', strtotime("-{$i} months"));
}

$regData = [];
foreach ($chartMonths as $m) { $regData[$m] = 0; }
foreach ($monthlyRestaurants as $row) {
    if (isset($regData[$row['month']])) {
        $regData[$row['month']] = (int) $row['count'];
    }
}

$ordData = [];
foreach ($chartMonths as $m) { $ordData[$m] = 0; }
foreach ($monthlyOrders as $row) {
    if (isset($ordData[$row['month']])) {
        $ordData[$row['month']] = (int) $row['count'];
    }
}

$revData = [];
foreach ($chartMonths as $m) { $revData[$m] = 0; }
foreach ($monthlyRevenue as $row) {
    if (isset($revData[$row['month']])) {
        $revData[$row['month']] = (float) $row['total'];
    }
}

$planLabels = [];
$planCounts = [];
foreach ($planDistribution as $p) {
    $planLabels[] = $p['name'] ?? 'Unassigned';
    $planCounts[] = (int) $p['count'];
}
?>

<div class="row mb-3">
    <div class="col-md-12">
        <form class="d-flex align-items-end gap-2 mb-3" method="GET">
            <div>
                <label class="form-label small">From</label>
                <input type="date" class="form-control form-control-sm" name="start_date" value="<?php echo sanitize($startDate); ?>">
            </div>
            <div>
                <label class="form-label small">To</label>
                <input type="date" class="form-control form-control-sm" name="end_date" value="<?php echo sanitize($endDate); ?>">
            </div>
            <button type="submit" class="btn btn-sm btn-primary"><i class="fas fa-filter me-1"></i>Filter</button>
        </form>
    </div>
</div>

<div class="row mb-4">
    <div class="col-xl-2 col-md-4 col-sm-6 mb-3">
        <div class="stat-card" style="border-left-color:#4f46e5;">
            <div class="d-flex justify-content-between align-items-start">
                <div>
                    <div class="stat-value"><?php echo number_format($totalRestaurants); ?></div>
                    <div class="stat-label">Total Restaurants</div>
                </div>
                <div class="stat-icon" style="background:#eef2ff;color:#4f46e5;"><i class="fas fa-store"></i></div>
            </div>
        </div>
    </div>
    <div class="col-xl-2 col-md-4 col-sm-6 mb-3">
        <div class="stat-card" style="border-left-color:#10b981;">
            <div class="d-flex justify-content-between align-items-start">
                <div>
                    <div class="stat-value"><?php echo number_format($activeRestaurants); ?></div>
                    <div class="stat-label">Active</div>
                </div>
                <div class="stat-icon" style="background:#ecfdf5;color:#10b981;"><i class="fas fa-check-circle"></i></div>
            </div>
        </div>
    </div>
    <div class="col-xl-2 col-md-4 col-sm-6 mb-3">
        <div class="stat-card" style="border-left-color:#f59e0b;">
            <div class="d-flex justify-content-between align-items-start">
                <div>
                    <div class="stat-value"><?php echo number_format($trialRestaurants + $suspendedRestaurants + $expiredRestaurants); ?></div>
                    <div class="stat-label">Trial/Susp/Exp</div>
                </div>
                <div class="stat-icon" style="background:#fffbeb;color:#f59e0b;"><i class="fas fa-clock"></i></div>
            </div>
        </div>
    </div>
    <div class="col-xl-2 col-md-4 col-sm-6 mb-3">
        <div class="stat-card" style="border-left-color:#6366f1;">
            <div class="d-flex justify-content-between align-items-start">
                <div>
                    <div class="stat-value"><?php echo number_format($totalOrders); ?></div>
                    <div class="stat-label">Total Orders</div>
                </div>
                <div class="stat-icon" style="background:#eef2ff;color:#6366f1;"><i class="fas fa-receipt"></i></div>
            </div>
        </div>
    </div>
    <div class="col-xl-2 col-md-4 col-sm-6 mb-3">
        <div class="stat-card" style="border-left-color:#ec4899;">
            <div class="d-flex justify-content-between align-items-start">
                <div>
                    <div class="stat-value"><?php echo number_format($ordersToday); ?></div>
                    <div class="stat-label">Orders Today</div>
                </div>
                <div class="stat-icon" style="background:#fdf2f8;color:#ec4899;"><i class="fas fa-calendar-day"></i></div>
            </div>
        </div>
    </div>
    <div class="col-xl-2 col-md-4 col-sm-6 mb-3">
        <div class="stat-card" style="border-left-color:#14b8a6;">
            <div class="d-flex justify-content-between align-items-start">
                <div>
                    <div class="stat-value"><?php echo formatCurrency($revenue); ?></div>
                    <div class="stat-label">Revenue</div>
                </div>
                <div class="stat-icon" style="background:#f0fdfa;color:#14b8a6;"><i class="fas fa-dollar-sign"></i></div>
            </div>
        </div>
    </div>
</div>

<div class="row mb-4">
    <div class="col-xl-2 col-md-4 col-sm-6 mb-3">
        <div class="stat-card" style="border-left-color:#8b5cf6;">
            <div class="d-flex justify-content-between align-items-start">
                <div>
                    <div class="stat-value"><?php echo number_format($totalEnquiries); ?></div>
                    <div class="stat-label">Total Enquiries</div>
                </div>
                <div class="stat-icon" style="background:#f5f3ff;color:#8b5cf6;"><i class="fas fa-envelope"></i></div>
            </div>
        </div>
    </div>
    <div class="col-xl-2 col-md-4 col-sm-6 mb-3">
        <div class="stat-card" style="border-left-color:#ef4444;">
            <div class="d-flex justify-content-between align-items-start">
                <div>
                    <div class="stat-value"><?php echo number_format($newEnquiries); ?></div>
                    <div class="stat-label">New Enquiries</div>
                </div>
                <div class="stat-icon" style="background:#fef2f2;color:#ef4444;"><i class="fas fa-envelope-open"></i></div>
            </div>
        </div>
    </div>
    <div class="col-xl-2 col-md-4 col-sm-6 mb-3">
        <div class="stat-card" style="border-left-color:#0ea5e9;">
            <div class="d-flex justify-content-between align-items-start">
                <div>
                    <div class="stat-value"><?php echo number_format($totalMenuItems); ?></div>
                    <div class="stat-label">Total Menu Items</div>
                </div>
                <div class="stat-icon" style="background:#f0f9ff;color:#0ea5e9;"><i class="fas fa-utensils"></i></div>
            </div>
        </div>
    </div>
    <div class="col-xl-2 col-md-4 col-sm-6 mb-3">
        <div class="stat-card" style="border-left-color:#84cc16;">
            <div class="d-flex justify-content-between align-items-start">
                <div>
                    <div class="stat-value"><?php echo number_format($totalUsers); ?></div>
                    <div class="stat-label">Total Users</div>
                </div>
                <div class="stat-icon" style="background:#f7fee7;color:#84cc16;"><i class="fas fa-users"></i></div>
            </div>
        </div>
    </div>
</div>

<div class="row mb-4">
    <div class="col-xl-6 mb-3">
        <div class="chart-card">
            <div class="card-title"><i class="fas fa-chart-bar me-2"></i>Monthly Restaurant Registrations</div>
            <canvas id="regChart" height="250"></canvas>
        </div>
    </div>
    <div class="col-xl-6 mb-3">
        <div class="chart-card">
            <div class="card-title"><i class="fas fa-chart-line me-2"></i>Orders by Month</div>
            <canvas id="ordChart" height="250"></canvas>
        </div>
    </div>
</div>

<div class="row mb-4">
    <div class="col-xl-6 mb-3">
        <div class="chart-card">
            <div class="card-title"><i class="fas fa-chart-pie me-2"></i>Plan Distribution</div>
            <div style="max-width:350px;margin:0 auto;">
                <canvas id="planChart" height="250"></canvas>
            </div>
        </div>
    </div>
    <div class="col-xl-6 mb-3">
        <div class="chart-card">
            <div class="card-title"><i class="fas fa-chart-line me-2"></i>Revenue by Month</div>
            <canvas id="revChart" height="250"></canvas>
        </div>
    </div>
</div>

<div class="row mb-4">
    <div class="col-xl-8 mb-3">
        <div class="table-card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <span><i class="fas fa-store me-2"></i>Recent Restaurants</span>
                <a href="<?php echo $baseUrl; ?>/admin/restaurants.php" class="btn btn-sm btn-outline-primary">View All</a>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead class="table-light">
                            <tr>
                                <th>Name</th>
                                <th>Owner</th>
                                <th>Plan</th>
                                <th>Status</th>
                                <th>Created</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($recentRestaurants)): ?>
                                <tr><td colspan="5" class="text-center text-muted py-3">No restaurants found</td></tr>
                            <?php else: ?>
                                <?php foreach ($recentRestaurants as $rest): ?>
                                <tr>
                                    <td><a href="<?php echo $baseUrl; ?>/admin/restaurant_view.php?id=<?php echo $rest['id']; ?>"><?php echo sanitize($rest['name']); ?></a></td>
                                    <td><?php echo sanitize($rest['owner_name'] ?? 'N/A'); ?></td>
                                    <td><span class="badge bg-info"><?php echo sanitize($rest['plan_name'] ?? 'None'); ?></span></td>
                                    <td>
                                        <?php
                                        $statusClass = ['active'=>'success','trial'=>'warning','suspended'=>'danger','expired'=>'secondary','cancelled'=>'dark'];
                                        $cls = $statusClass[$rest['status']] ?? 'secondary';
                                        ?>
                                        <span class="badge bg-<?php echo $cls; ?>"><?php echo ucfirst(sanitize($rest['status'])); ?></span>
                                    </td>
                                    <td><?php echo timeAgo($rest['created_at']); ?></td>
                                </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    <div class="col-xl-4 mb-3">
        <div class="table-card">
            <div class="card-header"><i class="fas fa-clock me-2"></i>Expiring Subscriptions (30 days)</div>
            <div class="card-body">
                <?php if (empty($expiringSubscriptions)): ?>
                    <div class="text-center text-muted py-3">No expiring subscriptions</div>
                <?php else: ?>
                    <?php foreach ($expiringSubscriptions as $exp): ?>
                    <div class="d-flex justify-content-between align-items-center border-bottom py-2">
                        <div>
                            <strong class="small"><?php echo sanitize($exp['name']); ?></strong>
                            <div class="text-muted" style="font-size:12px;"><?php echo sanitize($exp['plan_name'] ?? 'N/A'); ?></div>
                        </div>
                        <div class="text-end">
                            <span class="badge bg-warning text-dark"><?php echo formatDate($exp['subscription_end']); ?></span>
                            <div class="text-muted" style="font-size:11px;"><?php echo (new DateTime($exp['subscription_end']))->diff(new DateTime())->days; ?> days left</div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<div class="row mb-4">
    <div class="col-xl-12">
        <div class="table-card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <span><i class="fas fa-envelope me-2"></i>Recent Enquiries</span>
                <a href="<?php echo $baseUrl; ?>/admin/enquiries.php" class="btn btn-sm btn-outline-primary">View All</a>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead class="table-light">
                            <tr>
                                <th>Name</th>
                                <th>Restaurant</th>
                                <th>Email</th>
                                <th>Plan</th>
                                <th>Status</th>
                                <th>Date</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($recentEnquiries)): ?>
                                <tr><td colspan="6" class="text-center text-muted py-3">No enquiries</td></tr>
                            <?php else: ?>
                                <?php foreach ($recentEnquiries as $enq): ?>
                                <tr>
                                    <td><?php echo sanitize($enq['name']); ?></td>
                                    <td><?php echo sanitize($enq['restaurant_name'] ?? 'N/A'); ?></td>
                                    <td><?php echo sanitize($enq['email']); ?></td>
                                    <td><?php echo sanitize($enq['preferred_plan'] ?? 'N/A'); ?></td>
                                    <td>
                                        <?php
                                        $eClass = ['new'=>'primary','read'=>'info','replied'=>'success'];
                                        ?>
                                        <span class="badge bg-<?php echo $eClass[$enq['status']] ?? 'secondary'; ?>"><?php echo ucfirst(sanitize($enq['status'])); ?></span>
                                    </td>
                                    <td><?php echo timeAgo($enq['created_at']); ?></td>
                                </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
var monthLabels = <?php echo json_encode($chartMonthLabels); ?>;
var regData = <?php echo json_encode(array_values($regData)); ?>;
var ordData = <?php echo json_encode(array_values($ordData)); ?>;
var revData = <?php echo json_encode(array_values($revData)); ?>;
var planLabels = <?php echo json_encode($planLabels); ?>;
var planCounts = <?php echo json_encode($planCounts); ?>;

new Chart(document.getElementById('regChart'), {
    type: 'bar',
    data: {
        labels: monthLabels,
        datasets: [{label: 'Restaurants', data: regData, backgroundColor: '#4f46e5', borderRadius: 6}]
    },
    options: {responsive: true, plugins: {legend: {display: false}}, scales: {y: {beginAtZero: true, ticks: {stepSize: 1}}}}
});

new Chart(document.getElementById('ordChart'), {
    type: 'line',
    data: {
        labels: monthLabels,
        datasets: [{label: 'Orders', data: ordData, borderColor: '#6366f1', backgroundColor: 'rgba(99,102,241,0.1)', fill: true, tension: 0.4}]
    },
    options: {responsive: true, plugins: {legend: {display: false}}, scales: {y: {beginAtZero: true, ticks: {stepSize: 1}}}}
});

new Chart(document.getElementById('planChart'), {
    type: 'doughnut',
    data: {
        labels: planLabels.length ? planLabels : ['No Data'],
        datasets: [{data: planCounts.length ? planCounts : [1], backgroundColor: ['#4f46e5', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6', '#0ea5e9']}]
    },
    options: {responsive: true, plugins: {legend: {position: 'bottom'}}}
});

new Chart(document.getElementById('revChart'), {
    type: 'line',
    data: {
        labels: monthLabels,
        datasets: [{label: 'Revenue', data: revData, borderColor: '#10b981', backgroundColor: 'rgba(16,185,129,0.1)', fill: true, tension: 0.4}]
    },
    options: {responsive: true, plugins: {legend: {display: false}}, scales: {y: {beginAtZero: true}}}
});
</script>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
