<?php
/**
 * @var int $todayAppointments
 * @var float $todayRevenue
 * @var int $activeCustomers
 * @var int $lowStockCount
 * @var array $appointments
 */
?>
<div class="page-title mb-4">
    <h5><i class="fas fa-th-large me-2 text-gold"></i>Dashboard</h5>
</div>

<?php \core\View::partial('Dashboard/partials/stats_row', [
    'todayRevenue' => $todayRevenue,
    'todayAppointments' => $todayAppointments,
    'activeCustomers' => $activeCustomers,
    'lowStockCount' => $lowStockCount,
]); ?>

<div class="row g-4">
    <div class="col-lg-8">
        <div class="glass-card p-0">
            <div class="card-header">
                <div class="card-header-left">
                    <i class="fas fa-chart-area card-icon"></i>
                    <h6 class="card-title">Revenue Overview (Last 7 Days)</h6>
                </div>
                <div>
                    <button type="button" class="btn btn-sm btn-outline-gold" id="refreshChartBtn">
                        <i class="fas fa-sync-alt"></i>
                    </button>
                </div>
            </div>
            <div class="card-body">
                <canvas id="revenueChart" height="280"></canvas>
            </div>
        </div>

        <div class="glass-card p-0 mt-4">
            <div class="card-header">
                <div class="card-header-left">
                    <i class="fas fa-crown card-icon"></i>
                    <h6 class="card-title">Top Services</h6>
                </div>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-dark table-hover mb-0">
                        <thead>
                            <tr>
                                <th>Service</th>
                                <th class="text-center">Bookings</th>
                                <th class="text-end">Revenue</th>
                            </tr>
                        </thead>
                        <tbody id="topServicesBody">
                            <tr>
                                <td colspan="3" class="text-center text-muted py-3">
                                    <i class="fas fa-spinner fa-spin me-2"></i>Loading...
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <div class="col-lg-4">
        <div class="glass-card p-0">
            <div class="card-header">
                <div class="card-header-left">
                    <i class="fas fa-calendar-check card-icon"></i>
                    <h6 class="card-title">Today's Appointments</h6>
                </div>
                <span class="badge bg-gold"><?= count($appointments) ?> today</span>
            </div>
            <div class="card-body p-0">
                <?php if (empty($appointments)): ?>
                    <div class="text-center text-muted py-4">
                        <i class="fas fa-calendar-day fa-2x mb-2"></i>
                        <p class="mb-0">No appointments today</p>
                    </div>
                <?php else: ?>
                    <ul class="list-group list-group-flush">
                        <?php foreach ($appointments as $apt): ?>
                            <li class="list-group-item bg-transparent px-3 py-3">
                                <div class="d-flex justify-content-between align-items-start">
                                    <div>
                                        <strong><?= e($apt->start_time ? date('h:i A', strtotime($apt->start_time)) : '--:--') ?></strong>
                                        <div class="mt-1">
                                            <?php if ($apt->customer_first_name): ?>
                                                <span class="text-muted small">
                                                    <i class="fas fa-user me-1"></i><?= e($apt->customer_first_name . ' ' . $apt->customer_last_name) ?>
                                                </span>
                                            <?php endif; ?>
                                        </div>
                                        <div class="small text-muted">
                                            <i class="fas fa-cut me-1"></i>Appointment
                                        </div>
                                    </div>
                                    <span class="badge bg-<?= statusBadge($apt->status ?? 'pending') ?>">
                                        <?= e(ucwords(str_replace('_', ' ', $apt->status ?? 'pending'))) ?>
                                    </span>
                                </div>
                                <?php if (!empty($apt->customer_phone)): ?>
                                    <div class="small text-muted mt-1">
                                        <i class="fas fa-phone me-1"></i><?= e($apt->customer_phone) ?>
                                    </div>
                                <?php endif; ?>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                <?php endif; ?>
            </div>
            <div class="card-footer text-center">
                <a href="<?= url('appointments') ?>" class="btn btn-sm btn-outline-gold">
                    <i class="fas fa-arrow-right me-1"></i>View All
                </a>
            </div>
        </div>

        <div class="glass-card p-0 mt-4">
            <div class="card-header">
                <div class="card-header-left">
                    <i class="fas fa-exclamation-triangle card-icon"></i>
                    <h6 class="card-title">Low Stock Alerts</h6>
                </div>
                <span class="badge bg-danger"><?= $lowStockCount ?> items</span>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-dark table-hover mb-0">
                        <thead>
                            <tr>
                                <th>Product</th>
                                <th class="text-center">Qty</th>
                            </tr>
                        </thead>
                        <tbody id="lowStockBody">
                            <tr>
                                <td colspan="2" class="text-center text-muted py-3">
                                    <i class="fas fa-spinner fa-spin me-2"></i>Loading...
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="card-footer text-center">
                <a href="<?= url('inventory/low-stock') ?>" class="btn btn-sm btn-outline-gold">
                    <i class="fas fa-arrow-right me-1"></i>Manage Stock
                </a>
            </div>
        </div>

        <div class="glass-card p-0 mt-4">
            <div class="card-header">
                <div class="card-header-left">
                    <i class="fas fa-star card-icon"></i>
                    <h6 class="card-title">Top Employees</h6>
                </div>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-dark table-hover mb-0">
                        <thead>
                            <tr>
                                <th>Employee</th>
                                <th class="text-end">Revenue</th>
                            </tr>
                        </thead>
                        <tbody id="topEmployeesBody">
                            <tr>
                                <td colspan="2" class="text-center text-muted py-3">
                                    <i class="fas fa-spinner fa-spin me-2"></i>Loading...
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<?php 
$revenueChartUrl = url('dashboard/revenue-chart');
$topServicesUrl = url('dashboard/top-services');
$lowStockUrl = url('dashboard/low-stock-data');
$topEmployeesUrl = url('dashboard/top-employees');
$inlineScripts = <<<EOS
    function loadChart() {
        $.get("{$revenueChartUrl}", function(res) {
            if (res.success) {
                const ctx = document.getElementById("revenueChart").getContext("2d");
                if (window.revenueChartInstance) {
                    window.revenueChartInstance.destroy();
                }
                window.revenueChartInstance = new Chart(ctx, {
                    type: "line",
                    data: res.data,
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: { display: false },
                            tooltip: {
                                callbacks: {
                                    label: function(context) {
                                        return APP_CURRENCY_SYMBOL + " " + Number(context.raw).toFixed(2);
                                    }
                                }
                            }
                        },
                        scales: {
                            y: {
                                beginAtZero: true,
                                ticks: {
                                    callback: function(value) {
                                        return APP_CURRENCY_SYMBOL + " " + Number(value).toFixed(0);
                                    }
                                },
                                grid: { color: "rgba(255,255,255,0.05)" }
                            },
                            x: {
                                grid: { display: false }
                            }
                        }
                    }
                });
            }
        });
    }

    function loadTopServices() {
        $.get("{$topServicesUrl}", function(res) {
            if (res.success) {
                let html = "";
                res.data.forEach(function(s) {
                    html += `<tr>
                        <td>` + s.name + `</td>
                        <td class="text-center">` + s.total_count + `</td>
                        <td class="text-end">` + APP_CURRENCY_SYMBOL + " " + Number(s.total_revenue).toFixed(2) + `</td>
                    </tr>`;
                });
                if (!res.data.length) {
                    html = `<tr><td colspan="3" class="text-center text-muted py-3">No data</td></tr>`;
                }
                $("#topServicesBody").html(html);
            }
        });
    }

    function loadLowStock() {
        $.get("{$lowStockUrl}", function(res) {
            if (res.success) {
                let html = "";
                res.data.forEach(function(item) {
                    html += `<tr>
                        <td>` + item.name + `</td>
                        <td class="text-center"><span class="badge bg-danger">` + item.quantity + `</span></td>
                    </tr>`;
                });
                if (!res.data.length) {
                    html = `<tr><td colspan="2" class="text-center text-muted py-3">No low stock items</td></tr>`;
                }
                $("#lowStockBody").html(html);
            }
        });
    }

    function loadTopEmployees() {
        $.get("{$topEmployeesUrl}", function(res) {
            if (res.success) {
                let html = "";
                res.data.forEach(function(e) {
                    html += `<tr>
                        <td>` + e.first_name + " " + e.last_name + `</td>
                        <td class="text-end">` + APP_CURRENCY_SYMBOL + " " + Number(e.total_revenue).toFixed(2) + `</td>
                    </tr>`;
                });
                if (!res.data.length) {
                    html = `<tr><td colspan="2" class="text-center text-muted py-3">No data</td></tr>`;
                }
                $("#topEmployeesBody").html(html);
            }
        });
    }

    loadChart();
    loadTopServices();
    loadLowStock();
    loadTopEmployees();

    $("#refreshChartBtn").click(function() {
        loadChart();
    });
EOS;
?>
