<?php
/**
 * Admin Dashboard - Live Monitoring
 * VeloDrive System
 */

$page_title = 'Dashboard';
require_once 'includes/header.php';

$success_message = '';
$error_message = '';

// Handle verification from dashboard
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['verify_payment'])) {
    try {
        $pdo = getDBConnection();
        $stmt = $pdo->prepare("UPDATE payments SET status = 'verified', verified_at = CURRENT_TIMESTAMP WHERE id = ?");
        $stmt->execute([$_POST['payment_id']]);

        // Also update booking status if it was pending downpayment
        $stmt = $pdo->prepare("UPDATE bookings SET downpayment_paid = 1, booking_status = 'confirmed'
                             WHERE id = (SELECT booking_id FROM payments WHERE id = ?)");
        $stmt->execute([$_POST['payment_id']]);

        $success_message = 'Payment verified successfully!';
    } catch (PDOException $e) {
        $error_message = 'Error verifying payment: ' . $e->getMessage();
    }
}

// Handle rejection from dashboard
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reject_payment'])) {
    try {
        $pdo = getDBConnection();
        $stmt = $pdo->prepare("UPDATE payments SET status = 'rejected' WHERE id = ?");
        $stmt->execute([$_POST['payment_id']]);
        $success_message = 'Payment rejected!';
    } catch (PDOException $e) {
        $error_message = 'Error rejecting payment: ' . $e->getMessage();
    }
}

// Get dashboard statistics
$monthly_revenue = 0;
$last_month_revenue = 0;
$revenue_growth = 0;
$active_rentals = 0;
$this_week_bookings = 0;
$last_week_bookings = 0;
$booking_trend = 0;
$pending_payments = 0;
$available_vehicles = 0;
$recent_bookings = [];
$recent_payments = [];
$revenue_chart_labels = [];
$revenue_chart_data = [];
$vehicle_status = [];

try {
    $pdo = getDBConnection();
    
    // Total revenue this month
    try {
        $stmt = $pdo->query("SELECT COALESCE(SUM(total_amount), 0) as total FROM bookings WHERE MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE()) AND booking_status = 'completed'");
        $monthly_revenue = $stmt->fetch()['total'] ?? 0;

        // Total revenue last month
        $stmt = $pdo->query("SELECT COALESCE(SUM(total_amount), 0) as total FROM bookings WHERE MONTH(created_at) = MONTH(DATE_SUB(CURDATE(), INTERVAL 1 MONTH)) AND YEAR(created_at) = YEAR(DATE_SUB(CURDATE(), INTERVAL 1 MONTH)) AND booking_status = 'completed'");
        $last_month_revenue = $stmt->fetch()['total'] ?? 0;

        // Revenue growth percentage
        if ($last_month_revenue > 0) {
            $revenue_growth = (($monthly_revenue - $last_month_revenue) / $last_month_revenue) * 100;
        } elseif ($monthly_revenue > 0) {
            $revenue_growth = 100;
        }
    } catch (Exception $e) {}
    
    // Active rentals
    try {
        $stmt = $pdo->query("SELECT COUNT(*) as count FROM bookings WHERE booking_status = 'active'");
        $active_rentals = $stmt->fetch()['count'] ?? 0;
    } catch (Exception $e) {}

    // Bookings trend
    try {
        $stmt = $pdo->query("SELECT COUNT(*) as count FROM bookings WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)");
        $this_week_bookings = $stmt->fetch()['count'] ?? 0;

        $stmt = $pdo->query("SELECT COUNT(*) as count FROM bookings WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL 14 DAY) AND created_at < DATE_SUB(CURDATE(), INTERVAL 7 DAY)");
        $last_week_bookings = $stmt->fetch()['count'] ?? 0;

        if ($last_week_bookings > 0) {
            $booking_trend = (($this_week_bookings - $last_week_bookings) / $last_week_bookings) * 100;
        } elseif ($this_week_bookings > 0) {
            $booking_trend = 100;
        }
    } catch (Exception $e) {}
    
    // Pending approvals
    try {
        $stmt = $pdo->query("SELECT COUNT(*) as count FROM payments WHERE status = 'pending'");
        $pending_payments = $stmt->fetch()['count'] ?? 0;
    } catch (Exception $e) {}
    
    // Available vehicles
    try {
        $stmt = $pdo->query("SELECT COUNT(*) as count FROM vehicles WHERE status = 'available'");
        $available_vehicles = $stmt->fetch()['count'] ?? 0;
    } catch (Exception $e) {}
    
    // Recent bookings
    try {
        $stmt = $pdo->query("SELECT b.*, u.first_name, u.last_name, v.make, v.model,
                             ds.service_name as delivery_service_name
                             FROM bookings b
                             LEFT JOIN users u ON b.user_id = u.id
                             LEFT JOIN vehicles v ON b.vehicle_id = v.id
                             LEFT JOIN delivery_services ds ON b.delivery_service_id = ds.id
                             ORDER BY b.created_at DESC LIMIT 10");
        $recent_bookings = $stmt->fetchAll();
    } catch (Exception $e) {}
    
    // Recent payments (Pending only)
    try {
        $stmt = $pdo->query("SELECT p.*, b.reference_number as booking_ref
                             FROM payments p
                             LEFT JOIN bookings b ON p.booking_id = b.id
                             WHERE p.status = 'pending'
                             ORDER BY p.created_at DESC LIMIT 5");
        $recent_payments = $stmt->fetchAll();
    } catch (Exception $e) {}
    
    // Daily revenue for chart (last 7 days)
    try {
        $stmt = $pdo->query("SELECT DATE(created_at) as date, SUM(total_amount) as revenue
                             FROM bookings
                             WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL 6 DAY)
                             AND booking_status = 'completed'
                             GROUP BY DATE(created_at)");
        $raw_revenue_data = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

        for ($i = 6; $i >= 0; $i--) {
            $date = date('Y-m-d', strtotime("-$i days"));
            $day_name = date('D', strtotime("-$i days"));
            $revenue_chart_labels[] = $day_name;
            $revenue_chart_data[] = (float)($raw_revenue_data[$date] ?? 0);
        }
    } catch (Exception $e) {
        $revenue_chart_labels = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
        $revenue_chart_data = [0,0,0,0,0,0,0];
    }
    
    // Vehicle status distribution
    try {
        $stmt = $pdo->query("SELECT status, COUNT(*) as count FROM vehicles GROUP BY status");
        $vehicle_status = $stmt->fetchAll();
    } catch (Exception $e) {}
    
} catch (PDOException $e) {
    $error_message = "Database error: " . $e->getMessage();
}
?>

<div class="flex h-screen overflow-hidden bg-background-light dark:bg-background-dark">
    <?php include 'includes/sidebar.php'; ?>
    
    <div class="flex-1 flex flex-col overflow-hidden">
        <!-- TopAppBar -->
        <header class="sticky top-0 z-30 flex items-center bg-white/80 dark:bg-background-dark/80 backdrop-blur-xl p-4 justify-between border-b border-slate-200/50 dark:border-slate-800/50 lg:px-8">
            <div class="flex items-center gap-4">
                <button class="text-slate-900 dark:text-white flex size-10 items-center justify-center hover:bg-slate-100 dark:hover:bg-slate-800 rounded-xl transition-all active:scale-95 lg:hidden" onclick="toggleSidebar()">
                    <span class="material-symbols-outlined">menu</span>
                </button>
                <div class="hidden lg:block">
                    <h2 class="text-slate-900 dark:text-white text-clamp-lg font-bold leading-tight tracking-tight">Dashboard Overview</h2>
                    <p class="text-[10px] font-bold text-slate-400 uppercase tracking-widest mt-0.5">Real-time System Monitoring</p>
                </div>
            </div>

            <div class="flex items-center gap-3 sm:gap-6">
                <div class="hidden sm:flex items-center gap-3 bg-slate-100/50 dark:bg-slate-800/50 rounded-xl px-4 py-2 border border-slate-200/50 dark:border-slate-700/50 group transition-all hover:border-primary/50">
                    <span class="material-symbols-outlined text-sm text-primary group-hover:scale-110 transition-transform">attach_money</span>
                    <select onchange="window.location.href='?currency='+this.value" class="bg-transparent border-none text-xs font-bold focus:ring-0 outline-none p-0 cursor-pointer">
                        <?php foreach($CURRENCY_SYMBOLS as $code => $sym): ?>
                            <option value="<?= $code ?>" <?= $selected_currency === $code ? 'selected' : '' ?> class="dark:bg-slate-900"><?= $code ?> (<?= $sym ?>)</option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="flex items-center gap-3 pl-3 sm:pl-6 border-l border-slate-200 dark:border-slate-800">
                    <div class="text-right hidden xs:block">
                        <p class="text-xs font-bold leading-none">Admin User</p>
                        <p class="text-[9px] text-emerald-500 font-bold uppercase mt-1">Super Admin</p>
                    </div>
                    <div class="size-10 rounded-xl overflow-hidden bg-gradient-to-br from-primary to-blue-600 p-0.5 shadow-lg shadow-primary/20">
                        <img class="w-full h-full object-cover rounded-[9px]" src="https://ui-avatars.com/api/?name=Admin+User&background=137fec&color=fff"/>
                    </div>
                </div>
            </div>
        </header>

        <!-- Main Content -->
        <main class="flex-1 overflow-y-auto pb-32 lg:p-8 admin-content no-scrollbar">
            <!-- Welcome Section -->
            <div class="px-4 pt-8 pb-4 lg:px-0">
                <div class="flex flex-col sm:flex-row sm:items-end justify-between gap-4">
                    <div>
                        <p class="text-primary text-[10px] font-bold uppercase tracking-[0.2em] mb-1">CJM Car Rental</p>
                        <h1 class="text-clamp-2xl font-black dark:text-white tracking-tighter">System Status <span class="text-primary">.</span></h1>
                    </div>
                    <div class="flex gap-2">
                        <div class="bg-white dark:bg-surface-dark px-4 py-2 rounded-xl shadow-sm border border-slate-200 dark:border-slate-800 flex items-center gap-3">
                            <span class="size-2 rounded-full bg-emerald-500"></span>
                            <span class="text-xs font-bold text-slate-500"><?= date('M d, Y') ?></span>
                        </div>
                    </div>
                </div>
            </div>

            <?php if ($success_message): ?>
                <div class="mx-4 lg:mx-0 mb-6 bg-emerald-500/10 border border-emerald-500/20 text-emerald-500 px-6 py-4 rounded-2xl flex items-center gap-4 animate-in fade-in slide-in-from-top-4 duration-300">
                    <span class="material-symbols-outlined fill-1">check_circle</span>
                    <p class="text-sm font-bold"><?= htmlspecialchars($success_message) ?></p>
                </div>
            <?php endif; ?>

            <?php if ($error_message): ?>
                <div class="mx-4 lg:mx-0 mb-6 bg-rose-500/10 border border-rose-500/20 text-rose-500 px-6 py-4 rounded-2xl flex items-center gap-4 animate-in fade-in slide-in-from-top-4 duration-300">
                    <span class="material-symbols-outlined fill-1">error</span>
                    <p class="text-sm font-bold"><?= htmlspecialchars($error_message) ?></p>
                </div>
            <?php endif; ?>

            <!-- Stats Section -->
            <div class="flex overflow-x-auto gap-6 p-4 no-scrollbar lg:px-0 lg:grid lg:grid-cols-2 2xl:grid-cols-4 lg:overflow-visible">
                <!-- Revenue -->
                <a href="reports.php" class="group relative flex min-w-[300px] lg:min-w-0 flex-col gap-4 rounded-3xl p-8 bg-white dark:bg-surface-dark border border-slate-200 dark:border-slate-800 shadow-xl shadow-slate-200/50 dark:shadow-none hover:shadow-2xl hover:shadow-primary/10 transition-all duration-500 block overflow-hidden">
                    <div class="absolute -right-4 -top-4 size-32 bg-primary/5 rounded-full group-hover:scale-125 transition-transform duration-700"></div>
                    <div class="flex justify-between items-center relative z-10">
                        <div class="size-12 rounded-2xl bg-primary/10 text-primary flex items-center justify-center group-hover:bg-primary group-hover:text-white transition-all duration-500">
                            <span class="material-symbols-outlined text-2xl">payments</span>
                        </div>
                        <span class="text-[10px] font-black text-slate-400 uppercase tracking-widest">Monthly</span>
                    </div>
                    <div class="mt-4 relative z-10">
                        <p class="text-slate-500 dark:text-slate-400 text-[10px] font-bold uppercase tracking-widest mb-1">Revenue</p>
                        <p class="text-slate-900 dark:text-white tracking-tighter text-clamp-3xl font-black leading-none" data-stat="monthly-revenue">
                            <?= formatCurrency(convertCurrency($monthly_revenue, 'PHP', $selected_currency), $selected_currency) ?>
                        </p>
                    </div>
                    <div class="flex items-center gap-2 mt-2 relative z-10">
                        <div class="flex items-center gap-1 px-2 py-1 rounded-lg <?= $revenue_growth >= 0 ? 'bg-emerald-500/10 text-emerald-500' : 'bg-rose-500/10 text-rose-500' ?>">
                            <span class="material-symbols-outlined text-sm font-bold" data-stat="revenue-icon">
                                <?= $revenue_growth >= 0 ? 'trending_up' : 'trending_down' ?>
                            </span>
                            <p class="text-[10px] font-black" data-stat="revenue-growth">
                                <?= ($revenue_growth >= 0 ? '+' : '') . number_format($revenue_growth, 1) ?>%
                            </p>
                        </div>
                        <p class="text-[10px] text-slate-400 font-bold uppercase tracking-tighter">vs last month</p>
                    </div>
                </a>

                <!-- Active Rentals -->
                <a href="bookings.php?status=active" class="group relative flex min-w-[300px] lg:min-w-0 flex-col gap-4 rounded-3xl p-8 bg-white dark:bg-surface-dark border border-slate-200 dark:border-slate-800 shadow-xl shadow-slate-200/50 dark:shadow-none hover:shadow-2xl hover:shadow-emerald-500/10 transition-all duration-500 block overflow-hidden">
                    <div class="absolute -right-4 -top-4 size-32 bg-emerald-500/5 rounded-full group-hover:scale-125 transition-transform duration-700"></div>
                    <div class="flex justify-between items-center relative z-10">
                        <div class="size-12 rounded-2xl bg-emerald-500/10 text-emerald-500 flex items-center justify-center group-hover:bg-emerald-500 group-hover:text-white transition-all duration-500">
                            <span class="material-symbols-outlined text-2xl">key</span>
                        </div>
                        <span class="text-[10px] font-black text-slate-400 uppercase tracking-widest">Live</span>
                    </div>
                    <div class="mt-4 relative z-10">
                        <p class="text-slate-500 dark:text-slate-400 text-[10px] font-bold uppercase tracking-widest mb-1">Active Rentals</p>
                        <p class="text-slate-900 dark:text-white tracking-tighter text-clamp-3xl font-black leading-none" data-stat="active-rentals"><?= $active_rentals ?></p>
                    </div>
                    <div class="flex items-center gap-2 mt-2 relative z-10">
                        <div class="flex items-center gap-1 px-2 py-1 rounded-lg <?= $booking_trend >= 0 ? 'bg-emerald-500/10 text-emerald-500' : 'bg-rose-500/10 text-rose-500' ?>">
                            <span class="material-symbols-outlined text-sm font-bold" data-stat="trend-icon">
                                <?= $booking_trend >= 0 ? 'trending_up' : 'trending_down' ?>
                            </span>
                            <p class="text-[10px] font-black" data-stat="booking-trend">
                                <?= ($booking_trend >= 0 ? '+' : '') . number_format($booking_trend, 1) ?>%
                            </p>
                        </div>
                        <p class="text-[10px] text-slate-400 font-bold uppercase tracking-tighter">this week</p>
                    </div>
                </a>

                <!-- Pending -->
                <a href="payments.php?status=pending" class="group relative flex min-w-[300px] lg:min-w-0 flex-col gap-4 rounded-3xl p-8 bg-white dark:bg-surface-dark border border-slate-200 dark:border-slate-800 shadow-xl shadow-slate-200/50 dark:shadow-none hover:shadow-2xl hover:shadow-orange-500/10 transition-all duration-500 block overflow-hidden">
                    <div class="absolute -right-4 -top-4 size-32 bg-orange-500/5 rounded-full group-hover:scale-125 transition-transform duration-700"></div>
                    <div class="flex justify-between items-center relative z-10">
                        <div class="size-12 rounded-2xl bg-orange-500/10 text-orange-500 flex items-center justify-center group-hover:bg-orange-500 group-hover:text-white transition-all duration-500">
                            <span class="material-symbols-outlined text-2xl">pending_actions</span>
                        </div>
                        <span class="text-[10px] font-black text-slate-400 uppercase tracking-widest">Action</span>
                    </div>
                    <div class="mt-4 relative z-10">
                        <p class="text-slate-500 dark:text-slate-400 text-[10px] font-bold uppercase tracking-widest mb-1">Approvals</p>
                        <p class="text-slate-900 dark:text-white tracking-tighter text-clamp-3xl font-black leading-none" data-stat="pending-payments"><?= $pending_payments ?></p>
                    </div>
                    <div class="flex items-center gap-2 mt-2 relative z-10">
                        <div class="flex items-center gap-1 px-2 py-1 rounded-lg bg-orange-500/10 text-orange-500">
                            <span class="material-symbols-outlined text-sm font-bold">notification_important</span>
                            <p class="text-[10px] font-black uppercase">Requires Attention</p>
                        </div>
                    </div>
                </a>

                <!-- Fleet -->
                <a href="fleet.php?status=available" class="group relative flex min-w-[300px] lg:min-w-0 flex-col gap-4 rounded-3xl p-8 bg-white dark:bg-surface-dark border border-slate-200 dark:border-slate-800 shadow-xl shadow-slate-200/50 dark:shadow-none hover:shadow-2xl hover:shadow-purple-500/10 transition-all duration-500 block overflow-hidden">
                    <div class="absolute -right-4 -top-4 size-32 bg-purple-500/5 rounded-full group-hover:scale-125 transition-transform duration-700"></div>
                    <div class="flex justify-between items-center relative z-10">
                        <div class="size-12 rounded-2xl bg-purple-500/10 text-purple-500 flex items-center justify-center group-hover:bg-purple-500 group-hover:text-white transition-all duration-500">
                            <span class="material-symbols-outlined text-2xl">directions_car</span>
                        </div>
                        <span class="text-[10px] font-black text-slate-400 uppercase tracking-widest">Fleet</span>
                    </div>
                    <div class="mt-4 relative z-10">
                        <p class="text-slate-500 dark:text-slate-400 text-[10px] font-bold uppercase tracking-widest mb-1">Available Vehicles</p>
                        <p class="text-slate-900 dark:text-white tracking-tighter text-clamp-3xl font-black leading-none" data-stat="available-vehicles"><?= $available_vehicles ?></p>
                    </div>
                    <div class="flex items-center gap-2 mt-2 relative z-10">
                        <div class="flex items-center gap-1 px-2 py-1 rounded-lg bg-emerald-500/10 text-emerald-500">
                            <span class="material-symbols-outlined text-sm font-bold">check_circle</span>
                            <p class="text-[10px] font-black uppercase">Ready to Rent</p>
                        </div>
                    </div>
                </a>
            </div>

            <!-- Charts Row -->
            <div class="grid grid-cols-1 lg:grid-cols-3 gap-8 px-4 py-8 lg:px-0">
                <!-- Revenue Chart -->
                <div class="lg:col-span-2 bg-white dark:bg-surface-dark rounded-[2.5rem] p-8 border border-slate-200 dark:border-slate-800 shadow-xl shadow-slate-200/50 dark:shadow-none">
                    <div class="flex flex-col sm:flex-row items-start sm:items-center justify-between mb-8 gap-4">
                        <div>
                            <h2 class="text-slate-900 dark:text-white text-xl font-black tracking-tight leading-tight">Revenue Trends</h2>
                            <p class="text-slate-500 dark:text-slate-400 text-[10px] font-bold uppercase tracking-widest mt-1">Growth analysis over the last 7 days</p>
                        </div>
                        <div class="flex gap-2">
                            <span class="px-3 py-1 bg-primary/10 text-primary text-[10px] font-bold rounded-full uppercase tracking-widest">Weekly</span>
                        </div>
                    </div>
                    <div class="h-[300px] w-full relative">
                        <canvas id="revenueChart"></canvas>
                    </div>
                </div>

                <!-- Fleet Status -->
                <div class="bg-white dark:bg-surface-dark rounded-[2.5rem] p-8 border border-slate-200 dark:border-slate-800 shadow-xl shadow-slate-200/50 dark:shadow-none">
                    <h2 class="text-slate-900 dark:text-white text-xl font-black tracking-tight mb-2">Fleet Status</h2>
                    <p class="text-slate-500 dark:text-slate-400 text-[10px] font-bold uppercase tracking-widest mb-8">Vehicle utilization overview</p>
                    <div class="h-[250px] w-full relative">
                        <canvas id="fleetChart"></canvas>
                    </div>
                </div>
            </div>

            <!-- Recent Activity Row -->
            <div class="grid grid-cols-1 xl:grid-cols-2 gap-8 px-4 py-8 lg:px-0">
                <!-- Recent Bookings -->
                <div class="bg-white dark:bg-surface-dark rounded-[2.5rem] shadow-xl shadow-slate-200/50 dark:shadow-none border border-slate-200 dark:border-slate-800 overflow-hidden">
                    <div class="px-8 py-6 border-b border-slate-100 dark:border-slate-800 flex justify-between items-center bg-slate-50/50 dark:bg-slate-800/20">
                        <div>
                            <h2 class="text-lg font-black tracking-tight">Recent Bookings</h2>
                            <p class="text-[10px] font-bold text-slate-400 uppercase tracking-widest mt-0.5">Latest 10 transactions</p>
                        </div>
                        <a href="bookings.php" class="px-4 py-2 bg-primary/10 text-primary text-[10px] font-black rounded-xl hover:bg-primary hover:text-white transition-all duration-300 uppercase tracking-widest">View All</a>
                    </div>
                    <div class="divide-y divide-slate-100 dark:divide-slate-800">
                        <?php if(empty($recent_bookings)): ?>
                            <div class="p-12 text-center">
                                <span class="material-symbols-outlined text-4xl text-slate-200 mb-2">event_busy</span>
                                <p class="text-sm font-bold text-slate-400">No recent bookings found.</p>
                            </div>
                        <?php else: ?>
                            <?php foreach ($recent_bookings as $booking): ?>
                                <div class="px-8 py-5 flex items-center justify-between hover:bg-slate-50 dark:hover:bg-slate-900/30 transition-all duration-300 group">
                                    <div class="flex items-center gap-5">
                                        <div class="size-12 rounded-2xl <?= $booking['booking_type'] === 'delivery' ? 'bg-amber-500/10 text-amber-600' : 'bg-slate-100 dark:bg-slate-800 text-slate-400 group-hover:bg-primary/10 group-hover:text-primary' ?> flex items-center justify-center transition-all duration-300">
                                            <span class="material-symbols-outlined text-xl"><?= $booking['booking_type'] === 'delivery' ? 'local_shipping' : 'directions_car' ?></span>
                                        </div>
                                        <div>
                                            <p class="font-black text-sm tracking-tight"><?= htmlspecialchars($booking['first_name'] . ' ' . $booking['last_name']) ?></p>
                                            <p class="text-[10px] font-bold text-slate-500 uppercase tracking-widest mt-0.5">
                                                <?php if ($booking['booking_type'] === 'delivery'): ?>
                                                    <?= htmlspecialchars($booking['delivery_service_name'] ?: 'Delivery Service') ?>
                                                <?php else: ?>
                                                    <?= htmlspecialchars($booking['make'] . ' ' . $booking['model']) ?>
                                                <?php endif; ?>
                                                • <span class="text-primary"><?= $booking['reference_number'] ?></span>
                                            </p>
                                        </div>
                                    </div>
                                    <div class="flex items-center gap-6">
                                        <div class="text-right hidden sm:block">
                                            <p class="font-black text-sm"><?= formatCurrency(convertCurrency($booking['total_amount'], 'PHP', $selected_currency), $selected_currency) ?></p>
                                            <div class="flex items-center justify-end gap-2 mt-1">
                                                <p class="text-[8px] font-black text-emerald-500 uppercase">DP: <?= formatCurrency(convertCurrency($booking['downpayment_amount'], 'PHP', $selected_currency), $selected_currency) ?></p>
                                                <span class="text-[8px] text-slate-300">•</span>
                                                <p class="text-[8px] font-black text-orange-500 uppercase">Bal: <?= formatCurrency(convertCurrency($booking['balance_amount'], 'PHP', $selected_currency), $selected_currency) ?></p>
                                            </div>
                                        </div>
                                        <div class="flex flex-col items-end gap-2">
                                            <?php
                                            $status_classes = [
                                                'completed' => 'bg-emerald-500/10 text-emerald-500',
                                                'active' => 'bg-primary/10 text-primary',
                                                'pending' => 'bg-orange-500/10 text-orange-500',
                                                'cancelled' => 'bg-rose-500/10 text-rose-500',
                                            ];
                                            $cls = $status_classes[strtolower($booking['booking_status'])] ?? 'bg-slate-100 text-slate-500';
                                            ?>
                                            <span class="px-3 py-1 text-[8px] font-black rounded-full uppercase tracking-widest <?= $cls ?>">
                                                <?= $booking['booking_status'] ?>
                                            </span>
                                            <a href="booking_details.php?id=<?= $booking['id'] ?>" class="text-[9px] font-black text-slate-400 group-hover:text-primary flex items-center gap-1 uppercase tracking-widest hover:underline transition-colors">
                                                Details <span class="material-symbols-outlined text-[14px]">chevron_right</span>
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Pending Payments -->
                <div class="bg-white dark:bg-surface-dark rounded-[2.5rem] shadow-xl shadow-slate-200/50 dark:shadow-none border border-slate-200 dark:border-slate-800 overflow-hidden">
                    <div class="px-8 py-6 border-b border-slate-100 dark:border-slate-800 flex justify-between items-center bg-slate-50/50 dark:bg-slate-800/20">
                        <div>
                            <h2 class="text-lg font-black tracking-tight">Pending Approvals</h2>
                            <p class="text-[10px] font-bold text-slate-400 uppercase tracking-widest mt-0.5">Verification queue</p>
                        </div>
                        <a href="payments.php?status=pending" class="px-4 py-2 bg-orange-500/10 text-orange-500 text-[10px] font-black rounded-xl hover:bg-orange-500 hover:text-white transition-all duration-300 uppercase tracking-widest">View Queue</a>
                    </div>
                    <div class="divide-y divide-slate-100 dark:divide-slate-800">
                        <?php if(empty($recent_payments)): ?>
                            <div class="p-12 text-center">
                                <span class="material-symbols-outlined text-4xl text-slate-200 mb-2">check_circle</span>
                                <p class="text-sm font-bold text-slate-400">All caught up! No pending approvals.</p>
                            </div>
                        <?php else: ?>
                            <?php foreach ($recent_payments as $payment): ?>
                                <div class="px-8 py-6 flex items-center justify-between hover:bg-slate-50 dark:hover:bg-slate-900/30 transition-all duration-300">
                                    <div class="flex items-center gap-5">
                                        <div class="size-12 rounded-2xl bg-orange-500/10 text-orange-600 flex items-center justify-center">
                                            <span class="material-symbols-outlined text-xl">receipt_long</span>
                                        </div>
                                        <div>
                                            <p class="font-black text-sm tracking-tight"><?= htmlspecialchars($payment['booking_ref']) ?></p>
                                            <p class="text-[10px] font-bold text-slate-500 uppercase tracking-widest mt-0.5"><?= htmlspecialchars($payment['payment_method']) ?> • <span class="text-orange-500">Processing</span></p>
                                        </div>
                                    </div>
                                    <div class="flex items-center gap-6">
                                        <div class="text-right">
                                            <p class="font-black text-sm"><?= formatCurrency(convertCurrency($payment['amount'], 'PHP', $selected_currency), $selected_currency) ?></p>
                                            <p class="text-[8px] font-bold text-slate-400 uppercase mt-1"><?= date('h:i A', strtotime($payment['created_at'])) ?></p>
                                        </div>
                                        <div class="flex gap-2">
                                            <form method="POST">
                                                <input type="hidden" name="payment_id" value="<?= $payment['id'] ?>">
                                                <button type="submit" name="verify_payment" class="bg-primary text-white text-[9px] font-black px-4 py-2 rounded-xl hover:shadow-lg hover:shadow-primary/30 transition-all active:scale-95 uppercase tracking-widest">Approve</button>
                                            </form>
                                            <form method="POST">
                                                <input type="hidden" name="payment_id" value="<?= $payment['id'] ?>">
                                                <button type="submit" name="reject_payment" class="bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400 text-[9px] font-black px-4 py-2 rounded-xl hover:bg-rose-500 hover:text-white transition-all active:scale-95 uppercase tracking-widest">Reject</button>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </main>
    </div>
</div>

<script>
    // Charts initialization
    document.addEventListener('DOMContentLoaded', function() {
        const isDark = document.documentElement.classList.contains('dark');
        const textColor = isDark ? '#94a3b8' : '#64748b';
        const gridColor = isDark ? 'rgba(255, 255, 255, 0.05)' : 'rgba(0, 0, 0, 0.05)';

        // Revenue Chart
        const revenueCtx = document.getElementById('revenueChart').getContext('2d');
        const revenueGradient = revenueCtx.createLinearGradient(0, 0, 0, 300);
        revenueGradient.addColorStop(0, 'rgba(19, 127, 236, 0.3)');
        revenueGradient.addColorStop(1, 'rgba(19, 127, 236, 0)');

        window.revenueChart = new Chart(revenueCtx, {
            type: 'line',
            data: {
                labels: <?= json_encode($revenue_chart_labels) ?>,
                datasets: [{
                    label: 'Revenue',
                    data: <?= json_encode(array_map(function($val) use ($selected_currency) {
                        return round(convertCurrency($val, 'PHP', $selected_currency), 2);
                    }, $revenue_chart_data)) ?>,
                    borderColor: '#137fec',
                    borderWidth: 4,
                    pointBackgroundColor: '#137fec',
                    pointBorderColor: isDark ? '#1c2632' : '#ffffff',
                    pointBorderWidth: 3,
                    pointRadius: 6,
                    pointHoverRadius: 8,
                    backgroundColor: revenueGradient,
                    fill: true,
                    tension: 0.4
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: { display: false },
                    tooltip: {
                        backgroundColor: isDark ? '#1e293b' : '#ffffff',
                        titleColor: isDark ? '#ffffff' : '#1e293b',
                        bodyColor: isDark ? '#ffffff' : '#1e293b',
                        borderColor: isDark ? 'rgba(255,255,255,0.1)' : 'rgba(0,0,0,0.1)',
                        borderWidth: 1,
                        padding: 12,
                        cornerRadius: 12,
                        displayColors: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        grid: { color: gridColor, drawBorder: false },
                        ticks: { color: textColor, font: { weight: '600', size: 10 } }
                    },
                    x: {
                        grid: { display: false },
                        ticks: { color: textColor, font: { weight: '600', size: 10 } }
                    }
                }
            }
        });

        // Fleet Status Chart
        const fleetCtx = document.getElementById('fleetChart').getContext('2d');
        new Chart(fleetCtx, {
            type: 'doughnut',
            data: {
                labels: <?= json_encode(array_column($vehicle_status, 'status') ?: ['Available', 'Rented', 'Maintenance']) ?>,
                datasets: [{
                    data: <?= json_encode(array_column($vehicle_status, 'count') ?: [45, 124, 12]) ?>,
                    backgroundColor: ['#10b981', '#137fec', '#f59e0b', '#ef4444'],
                    borderWidth: isDark ? 8 : 4,
                    borderColor: isDark ? '#1c2632' : '#ffffff',
                    hoverOffset: 20
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'bottom',
                        labels: {
                            usePointStyle: true,
                            padding: 30,
                            color: textColor,
                            font: { weight: 'bold', size: 11 }
                        }
                    }
                },
                cutout: '75%',
                animation: {
                    animateScale: true,
                    animateRotate: true
                }
            }
        });
    });
</script>

<script>
// Real-time dashboard updates
document.addEventListener('DOMContentLoaded', function() {
    // Auto-refresh dashboard stats every 30 seconds
    setInterval(function() {
        fetch('ajax_refresh_stats.php')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Update dashboard stats
                    const stats = data.data;
                    
                    // Update stats cards if elements exist
                    const monthlyRevenueEl = document.querySelector('[data-stat="monthly-revenue"]');
                    const activeRentalsEl = document.querySelector('[data-stat="active-rentals"]');
                    const pendingPaymentsEl = document.querySelector('[data-stat="pending-payments"]');
                    const availableVehiclesEl = document.querySelector('[data-stat="available-vehicles"]');
                    
                    if (monthlyRevenueEl) {
                        const currentCurrency = '<?php echo $selected_currency; ?>';
                        const exchangeRate = <?php echo floatval(EXCHANGE_RATES[$selected_currency] ?? 1); ?>;
                        const convertedRevenue = stats.monthly_revenue * exchangeRate;
                        monthlyRevenueEl.textContent = formatCurrencyJS(convertedRevenue, currentCurrency);
                    }

                    // Update growth labels
                    const revenueGrowthEl = document.querySelector('[data-stat="revenue-growth"]');
                    const revenueIconEl = document.querySelector('[data-stat="revenue-icon"]');
                    if (revenueGrowthEl && revenueIconEl) {
                        const growth = stats.revenue_growth;
                        revenueGrowthEl.innerHTML = `${growth >= 0 ? '+' : ''}${growth.toFixed(1)}% <span class="text-slate-400 dark:text-slate-500 font-normal">vs last month</span>`;
                        revenueGrowthEl.className = `${growth >= 0 ? 'text-emerald-500' : 'text-rose-500'} text-sm font-bold`;
                        revenueIconEl.textContent = growth >= 0 ? 'trending_up' : 'trending_down';
                        revenueIconEl.className = `material-symbols-outlined ${growth >= 0 ? 'text-emerald-500' : 'text-rose-500'} text-sm`;
                    }

                    if (activeRentalsEl) {
                        activeRentalsEl.textContent = stats.active_rentals;
                    }

                    const bookingTrendEl = document.querySelector('[data-stat="booking-trend"]');
                    const trendIconEl = document.querySelector('[data-stat="trend-icon"]');
                    if (bookingTrendEl && trendIconEl) {
                        const trend = stats.booking_trend;
                        bookingTrendEl.innerHTML = `${trend >= 0 ? '+' : ''}${trend.toFixed(1)}% <span class="text-slate-400 dark:text-slate-500 font-normal">this week</span>`;
                        bookingTrendEl.className = `${trend >= 0 ? 'text-emerald-500' : 'text-rose-500'} text-sm font-bold`;
                        trendIconEl.textContent = trend >= 0 ? 'trending_up' : 'trending_down';
                        trendIconEl.className = `material-symbols-outlined ${trend >= 0 ? 'text-emerald-500' : 'text-rose-500'} text-sm`;
                    }

                    if (pendingPaymentsEl) {
                        pendingPaymentsEl.textContent = stats.pending_payments;
                    }
                    if (availableVehiclesEl) {
                        availableVehiclesEl.textContent = stats.available_vehicles;
                    }
                    
                    // Update charts if they exist
                    if (window.revenueChart && stats.revenue_chart) {
                        const exchangeRate = <?php echo floatval(EXCHANGE_RATES[$selected_currency] ?? 1); ?>;
                        window.revenueChart.data.labels = stats.revenue_chart.labels;
                        window.revenueChart.data.datasets[0].data = stats.revenue_chart.data.map(val => (val * exchangeRate).toFixed(2));
                        window.revenueChart.update();
                    }
                    if (window.fleetChart && stats.fleet_distribution) {
                        // Refresh fleet chart with new data
                        window.fleetChart.data.labels = stats.fleet_distribution.map(item => item.status);
                        window.fleetChart.data.datasets[0].data = stats.fleet_distribution.map(item => item.count);
                        window.fleetChart.update();
                    }
                }
            })
            .catch(error => console.log('Dashboard refresh failed:', error));
    }, 30000);
    
    // Helper function to format currency
    function formatCurrencyJS(amount, currencyCode) {
        const symbols = <?php echo json_encode($CURRENCY_SYMBOLS); ?>;
        const symbol = symbols[currencyCode] || currencyCode + ' ';
        return symbol + parseFloat(amount).toLocaleString('en-PH', {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2
        });
    }
    
});
</script>

<?php include 'includes/footer.php'; ?>
