<?php
require_once __DIR__ . '/../../includes/bootstrap.php';
require_login();
$pageTitle = 'Restaurant Dashboard';

if (!function_exists('h')) { function h($v): string { return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); } }
if (!function_exists('money_fmt')) { function money_fmt($v): string { return number_format((float)$v, 2); } }
if (!function_exists('rest_table_exists')) {
    function rest_table_exists(PDO $pdo, string $table): bool {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name=:t");
        $stmt->execute([':t'=>$table]); return (int)$stmt->fetchColumn() > 0;
    }
}
function rest_scalar(PDO $pdo, string $sql, array $params = [], $default = 0) {
    try { $stmt = $pdo->prepare($sql); $stmt->execute($params); $v = $stmt->fetchColumn(); return $v === false ? $default : $v; }
    catch (Throwable $e) { return $default; }
}

$hasOrders = rest_table_exists($pdo, 'restaurant_orders');
$hasTables = rest_table_exists($pdo, 'restaurant_tables');
$hasItems  = rest_table_exists($pdo, 'restaurant_order_items');
$hasJobs   = rest_table_exists($pdo, 'restaurant_print_jobs');

$todaySales = $hasOrders ? (float)rest_scalar($pdo, "SELECT COALESCE(SUM(total_amount),0) FROM restaurant_orders WHERE DATE(created_at)=CURDATE() AND status='closed'") : 0;
$openOrders = $hasOrders ? (int)rest_scalar($pdo, "SELECT COUNT(*) FROM restaurant_orders WHERE status IN ('open','preparing','served','bill_requested')") : 0;
$openTables = $hasTables ? (int)rest_scalar($pdo, "SELECT COUNT(*) FROM restaurant_tables WHERE status IN ('occupied','ordered','bill_requested')") : 0;
$availableTables = $hasTables ? (int)rest_scalar($pdo, "SELECT COUNT(*) FROM restaurant_tables WHERE status='available'") : 0;
$kitchenPending = $hasJobs ? (int)rest_scalar($pdo, "SELECT COUNT(*) FROM restaurant_print_jobs WHERE status IN ('pending','printing') AND LOWER(job_type) IN ('kitchen','food')") : 0;
$barPending = $hasJobs ? (int)rest_scalar($pdo, "SELECT COUNT(*) FROM restaurant_print_jobs WHERE status IN ('pending','printing') AND LOWER(job_type) IN ('bar','drinks')") : 0;
$walkinsToday = $hasOrders ? (int)rest_scalar($pdo, "SELECT COUNT(*) FROM restaurant_orders WHERE DATE(created_at)=CURDATE() AND order_type='walkin'") : 0;
$roomChargesToday = $hasOrders ? (float)rest_scalar($pdo, "SELECT COALESCE(SUM(total_amount),0) FROM restaurant_orders WHERE DATE(closed_at)=CURDATE() AND close_method IN ('room','master','guest_folio')") : 0;

$recentOrders = [];
if ($hasOrders) {
    try {
        $stmt = $pdo->query("SELECT ro.*, rt.table_no, rt.table_name FROM restaurant_orders ro LEFT JOIN restaurant_tables rt ON rt.id=ro.table_id ORDER BY ro.id DESC LIMIT 12");
        $recentOrders = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (Throwable $e) { $recentOrders = []; }
}

require_once __DIR__ . '/../../includes/header.php';
?>
<div class="hero-band compact-restaurant-hero">
    <div class="row g-3 align-items-center">
        <div class="col-lg-7">
            <div class="page-eyebrow text-white-50"><i class="bi bi-cup-hot"></i> Restaurant Operations</div>
            <div class="hero-title mt-1">Restaurant Dashboard</div>
            <div class="hero-subtitle mt-1">Table service, room charging, walk-ins, kitchen/bar routing and daily sales control.</div>
        </div>
        <div class="col-lg-5 text-lg-end">
            <a href="planner.php" class="btn btn-light btn-sm me-2"><i class="bi bi-grid-3x3-gap me-1"></i>Table Planner</a>
            <a href="orders.php" class="btn btn-outline-light btn-sm me-2"><i class="bi bi-receipt me-1"></i>Orders</a>
            <a href="menu.php" class="btn btn-outline-light btn-sm"><i class="bi bi-card-list me-1"></i>Menu</a>
        </div>
    </div>
</div>

<?php if (!$hasOrders || !$hasTables): ?>
<div class="alert alert-warning">
    <strong>Restaurant tables are not fully installed.</strong> Run <code>restaurant_schema.sql</code> first, then reload this dashboard.
</div>
<?php endif; ?>

<div class="row g-3 mb-3">
    <?php
    $cards = [
        ['Today Sales', money_fmt($todaySales), 'bi-cash-stack', 'success'],
        ['Open Orders', number_format($openOrders), 'bi-receipt-cutoff', 'primary'],
        ['Open Tables', number_format($openTables), 'bi-grid-3x3-gap', 'warning'],
        ['Available Tables', number_format($availableTables), 'bi-check-circle', 'info'],
        ['Kitchen Pending', number_format($kitchenPending), 'bi-fire', 'danger'],
        ['Bar Pending', number_format($barPending), 'bi-cup-straw', 'secondary'],
        ['Walk-ins Today', number_format($walkinsToday), 'bi-person-walking', 'dark'],
        ['Room Charges Today', money_fmt($roomChargesToday), 'bi-door-open', 'success'],
    ];
    foreach ($cards as $c): ?>
    <div class="col-sm-6 col-xl-3">
        <div class="metric-card rest-metric-card">
            <div class="metric-icon bg-<?php echo h($c[3]); ?>-subtle text-<?php echo h($c[3]); ?>"><i class="bi <?php echo h($c[2]); ?>"></i></div>
            <div><div class="metric-label"><?php echo h($c[0]); ?></div><div class="metric-value small-value"><?php echo h($c[1]); ?></div></div>
        </div>
    </div>
    <?php endforeach; ?>
</div>

<div class="row g-3">
    <div class="col-xl-4">
        <div class="card panel-card h-100">
            <div class="card-header"><h5 class="mb-0">Quick Actions</h5></div>
            <div class="card-body d-grid gap-2">
                <a class="btn btn-primary" href="planner.php"><i class="bi bi-grid-3x3-gap me-2"></i>Open Table Planner</a>
                <a class="btn btn-outline-primary" href="orders.php"><i class="bi bi-receipt me-2"></i>Open Orders</a>
                <a class="btn btn-outline-success" href="cashier.php"><i class="bi bi-cash-register me-2"></i>Cashier / Close Tables</a>
                <a class="btn btn-outline-danger" href="kitchen_display.php"><i class="bi bi-display me-2"></i>Kitchen Display</a>
                <a class="btn btn-outline-secondary" href="bar_display.php"><i class="bi bi-cup-straw me-2"></i>Bar Display</a>
                <a class="btn btn-outline-dark" href="reports.php"><i class="bi bi-bar-chart-line me-2"></i>Restaurant Reports</a>
            </div>
        </div>
    </div>
    <div class="col-xl-8">
        <div class="card panel-card h-100">
            <div class="card-header d-flex justify-content-between align-items-center"><h5 class="mb-0">Recent Orders</h5><a class="btn btn-sm btn-light" href="orders.php">View All</a></div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-modern align-middle mb-0">
                        <thead><tr><th>Order</th><th>Table</th><th>Type</th><th>Status</th><th class="text-end">Total</th><th>Created</th></tr></thead>
                        <tbody>
                        <?php if (!$recentOrders): ?>
                            <tr><td colspan="6" class="text-center text-muted py-4">No restaurant orders yet.</td></tr>
                        <?php else: foreach ($recentOrders as $o): ?>
                            <tr>
                                <td><a href="order_view.php?id=<?php echo (int)$o['id']; ?>" class="fw-bold"><?php echo h($o['order_no'] ?: ('#'.$o['id'])); ?></a></td>
                                <td><?php echo h(($o['table_no'] ?? '') . (!empty($o['table_name']) ? ' - '.$o['table_name'] : '')); ?></td>
                                <td><?php echo h(ucfirst((string)$o['order_type'])); ?></td>
                                <td><span class="badge text-bg-light border text-dark"><?php echo h(str_replace('_',' ', (string)$o['status'])); ?></span></td>
                                <td class="text-end fw-bold"><?php echo money_fmt($o['total_amount'] ?? 0); ?></td>
                                <td><?php echo h($o['created_at'] ?? ''); ?></td>
                            </tr>
                        <?php endforeach; endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.compact-restaurant-hero{padding:12px 16px!important;margin-bottom:10px!important}.small-value{font-size:1.05rem!important}.rest-metric-card{min-height:72px}.panel-card .card-header{padding:10px 14px}.table-modern thead th{font-size:.72rem;text-transform:uppercase;letter-spacing:.05em;color:#64748b;background:#f8fafc;white-space:nowrap}.table-modern td,.table-modern th{padding:.62rem .75rem;border-bottom:1px solid #eef2f7}
</style>
<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
