<?php
require_once __DIR__ . '/../../includes/bootstrap.php';
require_login();

$pageTitle = 'Restaurant Cashup';

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('ro_table_exists')) {
    function ro_table_exists(PDO $pdo, string $table): bool {
        static $cache = [];
        if (array_key_exists($table, $cache)) return $cache[$table];
        try {
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = :t");
            $stmt->execute([':t' => $table]);
            return $cache[$table] = ((int)$stmt->fetchColumn() > 0);
        } catch (Throwable $e) {
            return $cache[$table] = false;
        }
    }
}
if (!function_exists('ro_column_exists')) {
    function ro_column_exists(PDO $pdo, string $table, string $column): bool {
        static $cache = [];
        $key = $table . '.' . $column;
        if (array_key_exists($key, $cache)) return $cache[$key];
        try {
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = :t AND column_name = :c");
            $stmt->execute([':t' => $table, ':c' => $column]);
            return $cache[$key] = ((int)$stmt->fetchColumn() > 0);
        } catch (Throwable $e) {
            return $cache[$key] = false;
        }
    }
}
if (!function_exists('ro_format_dt')) {
    function ro_format_dt($dt, string $fallback = '-'): string {
        $dt = trim((string)$dt);
        if ($dt === '' || strtotime($dt) === false) return $fallback;
        return date('d-M-Y H:i', strtotime($dt));
    }
}
if (!function_exists('ro_status_badge_class')) {
    function ro_status_badge_class(string $status): string {
        $status = strtolower(trim($status));
        switch ($status) {
            case 'open': return 'success';
            case 'sent': return 'warning text-dark';
            case 'preparing': return 'info text-dark';
            case 'served': return 'primary';
            case 'bill_requested': return 'dark';
            case 'closed': return 'secondary';
            case 'void': return 'danger';
            default: return 'light text-dark border';
        }
    }
}

function ro_export_cashup_pdf(
    string $dateFrom, string $dateTo, bool $allCashiersMode, array $selectedCashiers,
    array $summary, array $methodTotals, float $totalCollected, float $gratuityTotal,
    array $cashierRows, array $allMethods, array $voidSummary, array $detailOrders
): void {
    $fpdfCandidates = [
        __DIR__ . '/../payments/fpdf.php',
        __DIR__ . '/fpdf.php',
        __DIR__ . '/../../payments/fpdf.php',
    ];
    $fpdfFound = false;
    foreach ($fpdfCandidates as $fpdfPath) {
        if (is_file($fpdfPath)) {
            require_once $fpdfPath;
            $fpdfFound = true;
            break;
        }
    }
    if (!$fpdfFound) {
        http_response_code(500);
        echo 'Could not generate PDF: fpdf.php was not found. Expected it in the payments module folder (' . h($fpdfCandidates[0]) . ').';
        exit;
    }

    class RestaurantCashupPDF extends FPDF
    {
        public $scopeLabel = '';

        function RoundedRect($x, $y, $w, $h, $r, $style = '')
        {
            $k = $this->k;
            $hp = $this->h;
            $op = ($style === 'F') ? 'f' : (($style === 'FD' || $style === 'DF') ? 'B' : 'S');
            $arc = 4 / 3 * (sqrt(2) - 1);
            $this->_out(sprintf('%.2F %.2F m', ($x + $r) * $k, ($hp - $y) * $k));
            $xc = $x + $w - $r; $yc = $y + $r;
            $this->_out(sprintf('%.2F %.2F l', $xc * $k, ($hp - $y) * $k));
            $this->_Arc($xc + $r * $arc, $yc - $r, $xc + $r, $yc - $r * $arc, $xc + $r, $yc);
            $xc = $x + $w - $r; $yc = $y + $h - $r;
            $this->_out(sprintf('%.2F %.2F l', ($x + $w) * $k, ($hp - $yc) * $k));
            $this->_Arc($xc + $r, $yc + $r * $arc, $xc + $r * $arc, $yc + $r, $xc, $yc + $r);
            $xc = $x + $r; $yc = $y + $h - $r;
            $this->_out(sprintf('%.2F %.2F l', $xc * $k, ($hp - ($y + $h)) * $k));
            $this->_Arc($xc - $r * $arc, $yc + $r, $xc - $r, $yc + $r * $arc, $xc - $r, $yc);
            $xc = $x + $r; $yc = $y + $r;
            $this->_out(sprintf('%.2F %.2F l', $x * $k, ($hp - $yc) * $k));
            $this->_Arc($xc - $r, $yc - $r * $arc, $xc - $r * $arc, $yc - $r, $xc, $yc - $r);
            $this->_out($op);
        }

        function _Arc($x1, $y1, $x2, $y2, $x3, $y3)
        {
            $h = $this->h;
            $this->_out(sprintf('%.2F %.2F %.2F %.2F %.2F %.2F c ', $x1 * $this->k, ($h - $y1) * $this->k, $x2 * $this->k, ($h - $y2) * $this->k, $x3 * $this->k, ($h - $y3) * $this->k));
        }

        function Header()
        {
            $this->SetFillColor(15, 23, 42);
            $this->Rect(0, 0, $this->w, 24, 'F');
            $this->SetTextColor(255, 255, 255);
            $this->SetFont('Arial', 'B', 16);
            $this->SetXY(10, 6);
            $this->Cell(150, 8, 'RESTAURANT CASHUP', 0, 0, 'L');
            $this->SetFont('Arial', '', 9);
            $this->SetXY(10, 15);
            $this->Cell(150, 5, 'Sales, payments and gratuity breakdown', 0, 0, 'L');
            $this->SetFont('Arial', 'B', 10);
            $this->SetXY($this->w - 110, 6);
            $this->Cell(100, 6, $this->scopeLabel, 0, 0, 'R');
            $this->SetFont('Arial', '', 8);
            $this->SetXY($this->w - 110, 14);
            $this->Cell(100, 5, 'Generated ' . date('d-M-Y H:i'), 0, 0, 'R');
            $this->SetY(30);
            $this->SetTextColor(15, 23, 42);
        }

        function Footer()
        {
            $this->SetY(-14);
            $this->SetDrawColor(203, 213, 225);
            $this->Line(10, $this->GetY(), $this->w - 10, $this->GetY());
            $this->SetY(-11);
            $this->SetFont('Arial', '', 7.5);
            $this->SetTextColor(100, 116, 139);
            $this->Cell($this->w - 30, 5, 'Restaurant Cashup', 0, 0, 'L');
            $this->Cell($this->w - 30, 5, 'Page ' . $this->PageNo() . ' of {nb}', 0, 0, 'R');
        }

        function sectionTitle($title, $subtitle = '')
        {
            $this->SetFillColor(241, 245, 249);
            $this->Rect(10, $this->GetY(), $this->w - 20, 8, 'F');
            $this->SetFont('Arial', 'B', 10.5);
            $this->SetTextColor(15, 23, 42);
            $this->SetXY(13, $this->GetY() + 1);
            $this->Cell(120, 6, $title, 0, 0, 'L');
            if ($subtitle !== '') {
                $this->SetFont('Arial', '', 8);
                $this->SetTextColor(100, 116, 139);
                $this->Cell($this->w - 133, 6, $subtitle, 0, 0, 'R');
            }
            $this->Ln(11);
        }

        function tableHeaderRow(array $cols)
        {
            $this->SetFillColor(30, 41, 59);
            $this->SetTextColor(255, 255, 255);
            $this->SetFont('Arial', 'B', 8);
            foreach ($cols as $c) {
                $this->Cell($c[1], 7, $c[0], 0, 0, $c[2] ?? 'L', true);
            }
            $this->Ln();
            $this->SetTextColor(15, 23, 42);
        }

        function checkSpace($needed)
        {
            if ($this->GetY() + $needed > $this->h - 20) {
                $this->AddPage();
            }
        }
    }

    $money = function ($v) { return number_format((float)$v, 2); };

    $pdf = new RestaurantCashupPDF('L', 'mm', 'A4');
    $pdf->scopeLabel = date('d M Y', strtotime($dateFrom)) . ($dateFrom !== $dateTo ? ' to ' . date('d M Y', strtotime($dateTo)) : '')
        . '  |  ' . ($allCashiersMode ? 'All Cashiers' : ('Cashier(s): ' . implode(', ', $selectedCashiers)));
    $pdf->AliasNbPages();
    $pdf->AddPage();
    $pdf->SetAutoPageBreak(true, 20);

    /* KPI summary tiles */
    $tileW = ($pdf->GetPageWidth() - 20 - 15) / 4;
    $tiles = [
        ['Closed Orders', number_format($summary['order_count']), [37, 99, 235]],
        ['Gross Sales', $money($summary['gross_sales']), [22, 163, 74]],
        ['Room / Folio Charges', $money($summary['room_charged_total']), [124, 58, 237]],
        ['Gratuity Collected', $money($gratuityTotal), [217, 119, 6]],
    ];
    $tx = 10;
    foreach ($tiles as $t) {
        $pdf->SetFillColor($t[2][0], $t[2][1], $t[2][2]);
        $pdf->RoundedRect($tx, $pdf->GetY(), $tileW, 20, 3, 'F');
        $pdf->SetTextColor(255, 255, 255);
        $pdf->SetFont('Arial', '', 7.5);
        $pdf->SetXY($tx + 4, $pdf->GetY() + 3);
        $pdf->Cell($tileW - 8, 5, strtoupper($t[0]), 0, 0, 'L');
        $pdf->SetFont('Arial', 'B', 13);
        $pdf->SetXY($tx + 4, $pdf->GetY() + 5.5);
        $pdf->Cell($tileW - 8, 7, $t[1], 0, 0, 'L');
        $tx += $tileW + 5;
    }
    $pdf->SetTextColor(15, 23, 42);
    $pdf->SetY($pdf->GetY() + 26);

    $variance = round($summary['gross_sales'] - $totalCollected, 2);
    if (abs($variance) > 0.01) {
        $pdf->SetFillColor(254, 243, 199);
        $pdf->SetDrawColor(217, 119, 6);
        $pdf->RoundedRect(10, $pdf->GetY(), $pdf->GetPageWidth() - 20, 10, 2, 'DF');
        $pdf->SetFont('Arial', '', 8.3);
        $pdf->SetTextColor(120, 53, 15);
        $pdf->SetXY(14, $pdf->GetY() + 2.5);
        $pdf->Cell($pdf->GetPageWidth() - 28, 5, 'Variance: Gross sales ' . $money($summary['gross_sales']) . ' vs accounted payments ' . $money($totalCollected) . ' differ by ' . $money(abs($variance)) . '. See detail list for orders missing a posted payment.', 0, 0, 'L');
        $pdf->SetTextColor(15, 23, 42);
        $pdf->Ln(15);
    }

    /* Payment Method Breakdown */
    $pdf->sectionTitle('Payment Method Breakdown');
    $pdf->tableHeaderRow([['Method', 90, 'L'], ['Transactions', 55, 'R'], ['Amount', 55, 'R'], ['% of Total', 55, 'R']]);
    $fill = false;
    if (!$methodTotals) {
        $pdf->SetFont('Arial', 'I', 8.5);
        $pdf->SetTextColor(100, 116, 139);
        $pdf->Cell($pdf->GetPageWidth() - 20, 8, 'No payments recorded for this filter.', 0, 1, 'C');
        $pdf->SetTextColor(15, 23, 42);
    } else {
        $pdf->SetFont('Arial', '', 8.3);
        foreach ($methodTotals as $method => $m) {
            $pdf->checkSpace(8);
            $pdf->SetFillColor($fill ? 248 : 255, $fill ? 250 : 255, $fill ? 252 : 255);
            $pct = $totalCollected > 0 ? number_format(($m['amount'] / $totalCollected) * 100, 1) : '0.0';
            $pdf->Cell(90, 7, $method, 0, 0, 'L', true);
            $pdf->Cell(55, 7, number_format($m['count']), 0, 0, 'R', true);
            $pdf->Cell(55, 7, $money($m['amount']), 0, 0, 'R', true);
            $pdf->Cell(55, 7, $pct . '%', 0, 0, 'R', true);
            $pdf->Ln();
            $fill = !$fill;
        }
        $pdf->SetFillColor(226, 232, 240);
        $pdf->SetFont('Arial', 'B', 8.3);
        $pdf->Cell(90, 7.5, 'Total', 0, 0, 'L', true);
        $pdf->Cell(55, 7.5, number_format(array_sum(array_column($methodTotals, 'count'))), 0, 0, 'R', true);
        $pdf->Cell(55, 7.5, $money($totalCollected), 0, 0, 'R', true);
        $pdf->Cell(55, 7.5, '100.0%', 0, 0, 'R', true);
        $pdf->Ln(12);
    }

    /* Cashier Pivot */
    $pdf->checkSpace(20);
    $pdf->sectionTitle('Breakdown by Cashier');
    $fixedW = 60 + 30; // cashier + orders
    $methodColW = $allMethods ? max(22, (($pdf->GetPageWidth() - 20 - $fixedW - 35) / max(1, count($allMethods)))) : 0;
    $cols = [['Cashier', 60, 'L'], ['Orders', 30, 'R']];
    foreach ($allMethods as $m) $cols[] = [$m, $methodColW, 'R'];
    $cols[] = ['Gross Sales', 35, 'R'];
    $pdf->SetFont('Arial', 'B', 7.2);
    $pdf->tableHeaderRow($cols);
    if (!$cashierRows) {
        $pdf->SetFont('Arial', 'I', 8.5);
        $pdf->SetTextColor(100, 116, 139);
        $pdf->Cell($pdf->GetPageWidth() - 20, 8, 'No closed orders for this filter.', 0, 1, 'C');
        $pdf->SetTextColor(15, 23, 42);
    } else {
        $fill = false;
        $pdf->SetFont('Arial', '', 7.6);
        foreach ($cashierRows as $cName => $row) {
            $pdf->checkSpace(8);
            $pdf->SetFillColor($fill ? 248 : 255, $fill ? 250 : 255, $fill ? 252 : 255);
            $pdf->Cell(60, 7, $cName, 0, 0, 'L', true);
            $pdf->Cell(30, 7, number_format($row['order_count']), 0, 0, 'R', true);
            foreach ($allMethods as $m) {
                $val = isset($row['methods'][$m]) && $row['methods'][$m] > 0 ? $money($row['methods'][$m]) : '-';
                $pdf->Cell($methodColW, 7, $val, 0, 0, 'R', true);
            }
            $pdf->SetFont('Arial', 'B', 7.6);
            $pdf->Cell(35, 7, $money($row['gross_sales']), 0, 0, 'R', true);
            $pdf->SetFont('Arial', '', 7.6);
            $pdf->Ln();
            $fill = !$fill;
        }
    }
    $pdf->Ln(6);

    if ($voidSummary['order_count'] > 0) {
        $pdf->checkSpace(16);
        $pdf->SetFillColor(254, 226, 226);
        $pdf->SetDrawColor(220, 38, 38);
        $pdf->RoundedRect(10, $pdf->GetY(), $pdf->GetPageWidth() - 20, 12, 2, 'DF');
        $pdf->SetFont('Arial', 'B', 8.5);
        $pdf->SetTextColor(153, 27, 27);
        $pdf->SetXY(14, $pdf->GetY() + 2.2);
        $pdf->Cell(30, 5, 'Voided:', 0, 0, 'L');
        $pdf->SetFont('Arial', '', 8.3);
        $pdf->Cell($pdf->GetPageWidth() - 60, 5, number_format($voidSummary['order_count']) . ' order(s) voided in this period, would-be total ' . $money($voidSummary['would_be_total']) . '. Excluded from Gross Sales above.', 0, 0, 'L');
        $pdf->SetTextColor(15, 23, 42);
        $pdf->Ln(17);
    }

    /* Detail Closed Orders */
    $pdf->checkSpace(20);
    $pdf->sectionTitle('Closed Orders (Detail)', number_format(count($detailOrders)) . ' orders');
    $detailCols = [
        ['Order', 28, 'L'], ['Guest / Client', 55, 'L'], ['Cashier', 40, 'L'], ['Type', 28, 'L'],
        ['Payment', 30, 'L'], ['Close Method', 40, 'L'], ['Total', 25, 'R'], ['Closed', 34, 'L'],
    ];
    $pdf->tableHeaderRow($detailCols);
    if (!$detailOrders) {
        $pdf->SetFont('Arial', 'I', 8.5);
        $pdf->SetTextColor(100, 116, 139);
        $pdf->Cell($pdf->GetPageWidth() - 20, 8, 'No closed orders found for this filter.', 0, 1, 'C');
        $pdf->SetTextColor(15, 23, 42);
    } else {
        $fill = false;
        $pdf->SetFont('Arial', '', 7.3);
        foreach ($detailOrders as $o) {
            $pdf->checkSpace(7);
            if ($pdf->GetY() < 33) { $pdf->tableHeaderRow($detailCols); $pdf->SetFont('Arial', '', 7.3); }
            $pdf->SetFillColor($fill ? 248 : 255, $fill ? 250 : 255, $fill ? 252 : 255);
            $pdf->Cell(28, 6.5, (string)($o['order_no'] ?: ('#' . $o['id'])), 0, 0, 'L', true);
            $pdf->Cell(55, 6.5, substr((string)($o['guest_name'] ?: '-'), 0, 32), 0, 0, 'L', true);
            $pdf->Cell(40, 6.5, substr((string)$o['cashier_name'], 0, 22), 0, 0, 'L', true);
            $pdf->Cell(28, 6.5, ucwords(str_replace('_', ' ', (string)$o['order_type'])), 0, 0, 'L', true);
            $pdf->Cell(30, 6.5, ucwords(str_replace('_', ' ', (string)($o['payment_status'] ?: 'unpaid'))), 0, 0, 'L', true);
            $pdf->Cell(40, 6.5, substr((string)($o['close_method'] ?: '-'), 0, 22), 0, 0, 'L', true);
            $pdf->Cell(25, 6.5, $money($o['total_amount']), 0, 0, 'R', true);
            $pdf->Cell(34, 6.5, ro_format_dt($o['closed_when']), 0, 0, 'L', true);
            $pdf->Ln();
            $fill = !$fill;
        }
    }

    $filename = 'Restaurant_Cashup_' . $dateFrom . '_to_' . $dateTo . '.pdf';
    $pdf->Output('I', $filename);
}

function ro_export_cashup_xlsx(
    string $dateFrom, string $dateTo, bool $allCashiersMode, array $selectedCashiers,
    array $summary, array $methodTotals, float $totalCollected, float $gratuityTotal,
    array $cashierRows, array $allMethods, array $voidSummary, array $detailOrders
): void {
    $money = function ($v) { return number_format((float)$v, 2); };
    $esc = function ($v) { return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); };

    $scopeLabel = date('d M Y', strtotime($dateFrom)) . ($dateFrom !== $dateTo ? ' to ' . date('d M Y', strtotime($dateTo)) : '')
        . '  |  ' . ($allCashiersMode ? 'All Cashiers' : ('Cashier(s): ' . implode(', ', $selectedCashiers)));

    $filename = 'Restaurant_Cashup_' . $dateFrom . '_to_' . $dateTo . '.xls';
    header('Content-Type: application/vnd.ms-excel; charset=UTF-8');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Cache-Control: max-age=0');

    echo "\xEF\xBB\xBF"; // UTF-8 BOM so Excel renders correctly

    $navy = '#0f172a';
    $slate = '#1e293b';
    $lightBg = '#f1f5f9';
    $totalBg = '#e2e8f0';
    $border = '1px solid #cbd5e1';

    echo "<html xmlns:x='urn:schemas-microsoft-com:office:excel'>";
    echo "<head><meta charset='UTF-8'>";
    echo "<!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>";
    echo "<x:Name>Cashup</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions>";
    echo "</x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->";
    echo "<style>
        body{font-family:Calibri,Arial,sans-serif;}
        table{border-collapse:collapse;}
        td,th{padding:5px 8px;font-size:11pt;}
        .title{font-size:18pt;font-weight:bold;color:#ffffff;background:$navy;}
        .subtitle{font-size:10pt;color:#e2e8f0;background:$navy;}
        .scope{font-size:10.5pt;color:$slate;font-weight:bold;background:#ffffff;}
        .kpi-label{font-size:8.5pt;color:#ffffff;text-transform:uppercase;font-weight:bold;}
        .kpi-value{font-size:14pt;color:#ffffff;font-weight:bold;}
        .section{font-size:12pt;font-weight:bold;color:#ffffff;background:$slate;}
        .thead{font-size:9.5pt;font-weight:bold;color:#ffffff;background:$navy;border:$border;text-transform:uppercase;}
        .cell{border:$border;}
        .cell-num{border:$border;mso-number-format:'0.00';text-align:right;}
        .cell-int{border:$border;mso-number-format:'0';text-align:right;}
        .total-row{font-weight:bold;background:$totalBg;border:$border;}
        .total-row-num{font-weight:bold;background:$totalBg;border:$border;mso-number-format:'0.00';text-align:right;}
        .banner{background:#fef3c7;border:1px solid #d97706;color:#78350f;font-size:10pt;padding:8px;}
        .void-banner{background:#fee2e2;border:1px solid #dc2626;color:#991b1b;font-size:10pt;padding:8px;}
        .muted{color:#64748b;font-style:italic;}
    </style></head><body>";

    $colCount = 4 + count($allMethods);
    $detailColCount = 8;
    $maxCols = max($colCount, $detailColCount, 4);

    echo "<table>";

    // Title band
    echo "<tr><td class='title' colspan='$maxCols'>RESTAURANT CASHUP</td></tr>";
    echo "<tr><td class='subtitle' colspan='$maxCols'>Sales, payments and gratuity breakdown</td></tr>";
    echo "<tr><td class='scope' colspan='$maxCols'>" . $esc($scopeLabel) . " &nbsp;|&nbsp; Generated " . date('d-M-Y H:i') . "</td></tr>";
    echo "<tr><td colspan='$maxCols'>&nbsp;</td></tr>";

    // KPI row
    echo "<tr>";
    echo "<td class='kpi-label' style='background:#2563eb;'>CLOSED ORDERS<br><span class='kpi-value'>" . number_format($summary['order_count']) . "</span></td>";
    echo "<td class='kpi-label' style='background:#16a34a;'>GROSS SALES<br><span class='kpi-value'>" . $money($summary['gross_sales']) . "</span></td>";
    echo "<td class='kpi-label' style='background:#7c3aed;'>ROOM / FOLIO CHARGES<br><span class='kpi-value'>" . $money($summary['room_charged_total']) . "</span></td>";
    echo "<td class='kpi-label' style='background:#d97706;'>GRATUITY COLLECTED<br><span class='kpi-value'>" . $money($gratuityTotal) . "</span></td>";
    if ($maxCols > 4) echo "<td colspan='" . ($maxCols - 4) . "'></td>";
    echo "</tr>";
    echo "<tr><td colspan='$maxCols'>&nbsp;</td></tr>";

    $variance = round($summary['gross_sales'] - $totalCollected, 2);
    if (abs($variance) > 0.01) {
        echo "<tr><td class='banner' colspan='$maxCols'>Variance: Gross sales " . $money($summary['gross_sales']) . " vs accounted payments " . $money($totalCollected) . " differ by " . $money(abs($variance)) . ". Check the detail list for orders missing a posted payment.</td></tr>";
        echo "<tr><td colspan='$maxCols'>&nbsp;</td></tr>";
    }

    // Payment Method Breakdown
    echo "<tr><td class='section' colspan='$maxCols'>PAYMENT METHOD BREAKDOWN</td></tr>";
    echo "<tr><td class='thead'>Method</td><td class='thead'>Transactions</td><td class='thead'>Amount</td><td class='thead'>% of Total</td>";
    if ($maxCols > 4) echo "<td colspan='" . ($maxCols - 4) . "'></td>";
    echo "</tr>";
    if (!$methodTotals) {
        echo "<tr><td class='muted cell' colspan='$maxCols'>No payments recorded for this filter.</td></tr>";
    } else {
        foreach ($methodTotals as $method => $m) {
            $pct = $totalCollected > 0 ? number_format(($m['amount'] / $totalCollected) * 100, 1) : '0.0';
            echo "<tr>";
            echo "<td class='cell'>" . $esc($method) . "</td>";
            echo "<td class='cell-int'>" . (int)$m['count'] . "</td>";
            echo "<td class='cell-num'>" . $money($m['amount']) . "</td>";
            echo "<td class='cell'>" . $pct . "%</td>";
            if ($maxCols > 4) echo "<td colspan='" . ($maxCols - 4) . "'></td>";
            echo "</tr>";
        }
        echo "<tr><td class='total-row'>Total</td><td class='total-row' style='text-align:right;'>" . number_format(array_sum(array_column($methodTotals, 'count'))) . "</td><td class='total-row-num'>" . $money($totalCollected) . "</td><td class='total-row'>100.0%</td>";
        if ($maxCols > 4) echo "<td colspan='" . ($maxCols - 4) . "'></td>";
        echo "</tr>";
    }
    echo "<tr><td colspan='$maxCols'>&nbsp;</td></tr>";

    // Cashier Pivot
    echo "<tr><td class='section' colspan='$maxCols'>BREAKDOWN BY CASHIER</td></tr>";
    echo "<tr><td class='thead'>Cashier</td><td class='thead'>Orders</td>";
    foreach ($allMethods as $m) echo "<td class='thead'>" . $esc($m) . "</td>";
    echo "<td class='thead'>Gross Sales</td>";
    if ($maxCols > (2 + count($allMethods) + 1)) echo "<td colspan='" . ($maxCols - (2 + count($allMethods) + 1)) . "'></td>";
    echo "</tr>";
    if (!$cashierRows) {
        echo "<tr><td class='muted cell' colspan='$maxCols'>No closed orders for this filter.</td></tr>";
    } else {
        foreach ($cashierRows as $cName => $row) {
            echo "<tr><td class='cell'>" . $esc($cName) . "</td><td class='cell-int'>" . (int)$row['order_count'] . "</td>";
            foreach ($allMethods as $m) {
                $val = isset($row['methods'][$m]) && $row['methods'][$m] > 0 ? $money($row['methods'][$m]) : '-';
                echo "<td class='cell-num'>" . $val . "</td>";
            }
            echo "<td class='cell-num' style='font-weight:bold;'>" . $money($row['gross_sales']) . "</td>";
            if ($maxCols > (2 + count($allMethods) + 1)) echo "<td colspan='" . ($maxCols - (2 + count($allMethods) + 1)) . "'></td>";
            echo "</tr>";
        }
    }
    echo "<tr><td colspan='$maxCols'>&nbsp;</td></tr>";

    if ($voidSummary['order_count'] > 0) {
        echo "<tr><td class='void-banner' colspan='$maxCols'>" . number_format($voidSummary['order_count']) . " order(s) voided in this period, would-be total " . $money($voidSummary['would_be_total']) . ". Excluded from Gross Sales above.</td></tr>";
        echo "<tr><td colspan='$maxCols'>&nbsp;</td></tr>";
    }

    // Detail Closed Orders
    echo "<tr><td class='section' colspan='$maxCols'>CLOSED ORDERS (DETAIL) - " . number_format(count($detailOrders)) . " orders</td></tr>";
    echo "<tr><td class='thead'>Order</td><td class='thead'>Guest / Client</td><td class='thead'>Cashier</td><td class='thead'>Type</td><td class='thead'>Payment</td><td class='thead'>Close Method</td><td class='thead'>Total</td><td class='thead'>Closed</td>";
    if ($maxCols > 8) echo "<td colspan='" . ($maxCols - 8) . "'></td>";
    echo "</tr>";
    if (!$detailOrders) {
        echo "<tr><td class='muted cell' colspan='$maxCols'>No closed orders found for this filter.</td></tr>";
    } else {
        foreach ($detailOrders as $o) {
            echo "<tr>";
            echo "<td class='cell'>" . $esc($o['order_no'] ?: ('#' . $o['id'])) . "</td>";
            echo "<td class='cell'>" . $esc($o['guest_name'] ?: '-') . "</td>";
            echo "<td class='cell'>" . $esc($o['cashier_name']) . "</td>";
            echo "<td class='cell'>" . $esc(ucwords(str_replace('_', ' ', (string)$o['order_type']))) . "</td>";
            echo "<td class='cell'>" . $esc(ucwords(str_replace('_', ' ', (string)($o['payment_status'] ?: 'unpaid')))) . "</td>";
            echo "<td class='cell'>" . $esc($o['close_method'] ?: '-') . "</td>";
            echo "<td class='cell-num'>" . $money($o['total_amount']) . "</td>";
            echo "<td class='cell'>" . $esc(ro_format_dt($o['closed_when'])) . "</td>";
            if ($maxCols > 8) echo "<td colspan='" . ($maxCols - 8) . "'></td>";
            echo "</tr>";
        }
    }

    echo "</table></body></html>";
}

/* ---------------------------------------------------------------------
   Filters
--------------------------------------------------------------------- */
$dateFrom = trim((string)($_GET['from'] ?? date('Y-m-d')));
$dateTo   = trim((string)($_GET['to'] ?? date('Y-m-d')));
if (strtotime($dateFrom) === false) $dateFrom = date('Y-m-d');
if (strtotime($dateTo) === false)   $dateTo   = date('Y-m-d');
if (strtotime($dateTo) < strtotime($dateFrom)) { $tmp = $dateFrom; $dateFrom = $dateTo; $dateTo = $tmp; }

$selectedCashiers = array_values(array_filter(array_map('trim', (array)($_GET['cashiers'] ?? []))));
$allCashiersMode  = empty($selectedCashiers);

$hasPayments    = ro_table_exists($pdo, 'restaurant_payments');
$hasOrderItems  = ro_table_exists($pdo, 'restaurant_order_items');
$hasCashierCol  = ro_column_exists($pdo, 'restaurant_orders', 'cashier_name');
$cashierExpr    = $hasCashierCol ? "COALESCE(NULLIF(TRIM(ro.cashier_name),''),'Unassigned')" : "'Unassigned'";

$error = '';
$availableCashiers = [];
$summary = ['order_count' => 0, 'gross_sales' => 0.0, 'room_charged_total' => 0.0];
$methodTotals = [];   // method => ['count'=>n,'amount'=>x]
$gratuityTotal = 0.0;
$cashierRows = [];    // cashier => ['order_count'=>n,'gross_sales'=>x,'room_charged'=>x,'methods'=>[method=>amount]]
$voidSummary = ['order_count' => 0, 'would_be_total' => 0.0];
$detailOrders = [];

try {
    /* Cashier picker options: everyone who has closed a restaurant order in the last 120 days */
    if ($hasCashierCol) {
        $stmt = $pdo->prepare("
            SELECT DISTINCT $cashierExpr AS cashier_name
            FROM restaurant_orders ro
            WHERE ro.status = 'closed'
              AND COALESCE(ro.closed_at, ro.updated_at, ro.opened_at) >= DATE_SUB(:today, INTERVAL 120 DAY)
            ORDER BY cashier_name ASC
        ");
        $stmt->execute([':today' => date('Y-m-d')]);
        $availableCashiers = array_column($stmt->fetchAll(PDO::FETCH_ASSOC), 'cashier_name');
    }

    $params = [
        ':from' => $dateFrom . ' 00:00:00',
        ':to'   => $dateTo . ' 23:59:59',
    ];
    $cashierFilterSql = '';
    if (!$allCashiersMode) {
        $ph = [];
        foreach ($selectedCashiers as $i => $c) {
            $key = ':c' . $i;
            $ph[] = $key;
            $params[$key] = $c;
        }
        $cashierFilterSql = " AND $cashierExpr IN (" . implode(',', $ph) . ")";
    }

    $closedWhere = "ro.status = 'closed' AND UPPER(COALESCE(ro.order_no,'')) NOT LIKE 'FO-%' AND COALESCE(ro.closed_at, ro.updated_at, ro.opened_at) BETWEEN :from AND :to" . $cashierFilterSql;

    /* Overall summary: order count, gross sales, room/folio charged total */
    $stmt = $pdo->prepare("
        SELECT
            COUNT(*) AS order_count,
            COALESCE(SUM(ro.total_amount),0) AS gross_sales,
            COALESCE(SUM(CASE WHEN LOWER(COALESCE(ro.payment_status,''))='room_charged' THEN ro.total_amount ELSE 0 END),0) AS room_charged_total
        FROM restaurant_orders ro
        WHERE $closedWhere
    ");
    $stmt->execute($params);
    $row = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];
    $summary['order_count']        = (int)($row['order_count'] ?? 0);
    $summary['gross_sales']        = (float)($row['gross_sales'] ?? 0);
    $summary['room_charged_total'] = (float)($row['room_charged_total'] ?? 0);

    /* Payment method breakdown (posted payments only), scoped to closed orders in range */
    if ($hasPayments) {
        $stmt = $pdo->prepare("
            SELECT rp.payment_method AS method, COUNT(*) AS cnt, COALESCE(SUM(rp.amount),0) AS total
            FROM restaurant_payments rp
            INNER JOIN restaurant_orders ro ON ro.id = rp.restaurant_order_id
            WHERE rp.status = 'posted' AND $closedWhere
            GROUP BY rp.payment_method
            ORDER BY total DESC
        ");
        $stmt->execute($params);
        foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $r) {
            $method = trim((string)$r['method']) ?: 'Other';
            $methodTotals[$method] = ['count' => (int)$r['cnt'], 'amount' => (float)$r['total']];
        }
    }
    if ($summary['room_charged_total'] > 0) {
        $roomCount = 0;
        $stmtRc = $pdo->prepare("SELECT COUNT(*) FROM restaurant_orders ro WHERE $closedWhere AND LOWER(COALESCE(ro.payment_status,''))='room_charged'");
        $stmtRc->execute($params);
        $roomCount = (int)$stmtRc->fetchColumn();
        $methodTotals['Room / Folio Charge'] = ['count' => $roomCount, 'amount' => $summary['room_charged_total']];
    }

    /* Gratuity collected (posted as its own line item on orders) */
    if ($hasOrderItems && ro_column_exists($pdo, 'restaurant_order_items', 'item_name')) {
        $stmt = $pdo->prepare("
            SELECT COALESCE(SUM(roi.line_total),0)
            FROM restaurant_order_items roi
            INNER JOIN restaurant_orders ro ON ro.id = roi.restaurant_order_id
            WHERE $closedWhere AND LOWER(TRIM(roi.item_name)) = 'gratuity'
        ");
        $stmt->execute($params);
        $gratuityTotal = (float)$stmt->fetchColumn();
    }

    /* Per-cashier order totals */
    $stmt = $pdo->prepare("
        SELECT
            $cashierExpr AS cashier_name,
            COUNT(*) AS order_count,
            COALESCE(SUM(ro.total_amount),0) AS gross_sales,
            COALESCE(SUM(CASE WHEN LOWER(COALESCE(ro.payment_status,''))='room_charged' THEN ro.total_amount ELSE 0 END),0) AS room_charged
        FROM restaurant_orders ro
        WHERE $closedWhere
        GROUP BY cashier_name
        ORDER BY gross_sales DESC
    ");
    $stmt->execute($params);
    foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $r) {
        $cashierRows[$r['cashier_name']] = [
            'order_count'  => (int)$r['order_count'],
            'gross_sales'  => (float)$r['gross_sales'],
            'room_charged' => (float)$r['room_charged'],
            'methods'      => [],
        ];
    }

    /* Per-cashier per-method payment totals, folded into the same rows */
    if ($hasPayments) {
        $stmt = $pdo->prepare("
            SELECT $cashierExpr AS cashier_name, rp.payment_method AS method, COALESCE(SUM(rp.amount),0) AS total
            FROM restaurant_payments rp
            INNER JOIN restaurant_orders ro ON ro.id = rp.restaurant_order_id
            WHERE rp.status = 'posted' AND $closedWhere
            GROUP BY cashier_name, rp.payment_method
        ");
        $stmt->execute($params);
        foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $r) {
            $cName  = $r['cashier_name'];
            $method = trim((string)$r['method']) ?: 'Other';
            if (!isset($cashierRows[$cName])) {
                $cashierRows[$cName] = ['order_count' => 0, 'gross_sales' => 0.0, 'room_charged' => 0.0, 'methods' => []];
            }
            $cashierRows[$cName]['methods'][$method] = (float)$r['total'];
        }
    }
    foreach ($cashierRows as $cName => $row) {
        if ($row['room_charged'] > 0) {
            $cashierRows[$cName]['methods']['Room / Folio Charge'] = $row['room_charged'];
        }
    }

    /* Void reconciliation: what was cancelled during the same window/cashier filter */
    $voidWhere = "ro.status = 'void' AND UPPER(COALESCE(ro.order_no,'')) NOT LIKE 'FO-%' AND COALESCE(ro.closed_at, ro.updated_at, ro.opened_at) BETWEEN :from AND :to" . $cashierFilterSql;
    $stmt = $pdo->prepare("
        SELECT COUNT(*) AS cnt, COALESCE(SUM(ro.total_amount),0) AS total
        FROM restaurant_orders ro
        WHERE $voidWhere
    ");
    $stmt->execute($params);
    $vr = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];
    $voidSummary['order_count']     = (int)($vr['cnt'] ?? 0);
    $voidSummary['would_be_total']  = (float)($vr['total'] ?? 0);

    /* Detail list of closed orders in range for drill-down */
    $stmt = $pdo->prepare("
        SELECT ro.id, ro.order_no, ro.guest_name, ro.order_type, ro.total_amount, ro.payment_status, ro.close_method,
               $cashierExpr AS cashier_name, COALESCE(ro.closed_at, ro.updated_at, ro.opened_at) AS closed_when
        FROM restaurant_orders ro
        WHERE $closedWhere
        ORDER BY closed_when DESC
        LIMIT 500
    ");
    $stmt->execute($params);
    $detailOrders = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
} catch (Throwable $e) {
    $error = $e->getMessage();
}

/* Build the ordered list of payment-method columns for the cashier pivot table */
$allMethods = array_keys($methodTotals);
foreach ($cashierRows as $row) {
    foreach (array_keys($row['methods']) as $m) {
        if (!in_array($m, $allMethods, true)) $allMethods[] = $m;
    }
}
usort($allMethods, function ($a, $b) {
    if ($a === 'Room / Folio Charge') return 1;
    if ($b === 'Room / Folio Charge') return -1;
    return strcmp($a, $b);
});

$totalCollected = 0.0;
foreach ($methodTotals as $m) $totalCollected += $m['amount'];

$exportMode = trim((string)($_GET['export'] ?? ''));
if ($exportMode === 'pdf') {
    while (ob_get_level() > 0) { @ob_end_clean(); }
    try {
        ro_export_cashup_pdf($dateFrom, $dateTo, $allCashiersMode, $selectedCashiers, $summary, $methodTotals, $totalCollected, $gratuityTotal, $cashierRows, $allMethods, $voidSummary, $detailOrders);
    } catch (Throwable $e) {
        http_response_code(500);
        header('Content-Type: text/plain; charset=UTF-8');
        echo "Could not generate PDF.\n\n";
        echo "Error: " . $e->getMessage() . "\n";
        echo "File: " . $e->getFile() . " (line " . $e->getLine() . ")\n";
    }
    exit;
}
if ($exportMode === 'xlsx') {
    while (ob_get_level() > 0) { @ob_end_clean(); }
    try {
        ro_export_cashup_xlsx($dateFrom, $dateTo, $allCashiersMode, $selectedCashiers, $summary, $methodTotals, $totalCollected, $gratuityTotal, $cashierRows, $allMethods, $voidSummary, $detailOrders);
    } catch (Throwable $e) {
        http_response_code(500);
        header('Content-Type: text/plain; charset=UTF-8');
        echo "Could not generate Excel export.\n\n";
        echo "Error: " . $e->getMessage() . "\n";
        echo "File: " . $e->getFile() . " (line " . $e->getLine() . ")\n";
    }
    exit;
}

require_once __DIR__ . '/../../includes/header.php';
?>

<div class="hero-band compact-restaurant-hero cashup-print-hide">
    <div class="d-flex justify-content-between align-items-center flex-wrap gap-2">
        <div>
            <div class="page-eyebrow text-white-50"><i class="bi bi-cash-stack"></i> Restaurant</div>
            <div class="hero-title mt-1">Restaurant Cashup</div>
            <div class="hero-subtitle mt-1">Sales, payments and gratuity breakdown for all or selected cashiers.</div>
        </div>
        <div class="d-flex gap-2 flex-wrap">
            <a class="btn btn-light btn-sm" href="?<?php echo h(http_build_query(array_merge($_GET, ['export' => 'pdf']))); ?>" target="_blank"><i class="bi bi-file-earmark-pdf me-1"></i>Export PDF</a>
            <a class="btn btn-light btn-sm" href="?<?php echo h(http_build_query(array_merge($_GET, ['export' => 'xlsx']))); ?>"><i class="bi bi-file-earmark-excel me-1"></i>Export Excel</a>
            <button type="button" class="btn btn-light btn-sm" onclick="window.print()"><i class="bi bi-printer me-1"></i>Print Cashup</button>
            <a class="btn btn-outline-light btn-sm" href="restaurant_orders.php"><i class="bi bi-receipt me-1"></i>Orders</a>
            <a class="btn btn-outline-light btn-sm" href="planner.php"><i class="bi bi-grid-3x3-gap me-1"></i>Planner</a>
        </div>
    </div>
</div>

<?php if ($error): ?>
    <div class="alert alert-danger">Could not load cashup: <?php echo h($error); ?></div>
<?php endif; ?>

<div class="card panel-card mb-3 cashup-print-hide">
    <div class="card-body">
        <form method="get" class="row g-3 align-items-end">
            <div class="col-auto">
                <label class="form-label small mb-1">From</label>
                <input type="date" name="from" value="<?php echo h($dateFrom); ?>" class="form-control form-control-sm">
            </div>
            <div class="col-auto">
                <label class="form-label small mb-1">To</label>
                <input type="date" name="to" value="<?php echo h($dateTo); ?>" class="form-control form-control-sm">
            </div>
            <div class="col-12 col-md-auto flex-grow-1">
                <label class="form-label small mb-1 d-flex justify-content-between align-items-center">
                    <span>Cashiers</span>
                    <span class="cashier-toggle-links">
                        <a href="#" id="cashupSelectAll">All</a> ·
                        <a href="#" id="cashupSelectNone">None</a>
                    </span>
                </label>
                <div class="cashier-picker">
                    <?php if (!$availableCashiers): ?>
                        <span class="text-muted small">No cashiers found in the last 120 days.</span>
                    <?php else: foreach ($availableCashiers as $c): ?>
                        <label class="cashier-chip">
                            <input type="checkbox" name="cashiers[]" value="<?php echo h($c); ?>" <?php echo in_array($c, $selectedCashiers, true) ? 'checked' : ''; ?>>
                            <?php echo h($c); ?>
                        </label>
                    <?php endforeach; endif; ?>
                </div>
                <div class="form-text small">Leave everything unchecked to include <strong>all cashiers</strong>.</div>
            </div>
            <div class="col-auto">
                <button class="btn btn-primary btn-sm"><i class="bi bi-funnel me-1"></i>Run Cashup</button>
            </div>
        </form>
    </div>
</div>

<div class="cashup-scope mb-3">
    <strong><?php echo h(date('d M Y', strtotime($dateFrom))); ?><?php echo $dateFrom !== $dateTo ? ' – ' . h(date('d M Y', strtotime($dateTo))) : ''; ?></strong>
    &nbsp;|&nbsp;
    <?php if ($allCashiersMode): ?>
        <span>All Cashiers</span>
    <?php else: ?>
        <span>Cashier<?php echo count($selectedCashiers) > 1 ? 's' : ''; ?>: <?php echo h(implode(', ', $selectedCashiers)); ?></span>
    <?php endif; ?>
</div>

<div class="row g-3 mb-3 cashup-summary-cards">
    <div class="col-6 col-md-3">
        <div class="summary-card">
            <div class="summary-label">Closed Orders</div>
            <div class="summary-value"><?php echo number_format($summary['order_count']); ?></div>
        </div>
    </div>
    <div class="col-6 col-md-3">
        <div class="summary-card">
            <div class="summary-label">Gross Sales</div>
            <div class="summary-value"><?php echo money_fmt($summary['gross_sales']); ?></div>
        </div>
    </div>
    <div class="col-6 col-md-3">
        <div class="summary-card">
            <div class="summary-label">Room / Folio Charges</div>
            <div class="summary-value"><?php echo money_fmt($summary['room_charged_total']); ?></div>
        </div>
    </div>
    <div class="col-6 col-md-3">
        <div class="summary-card">
            <div class="summary-label">Gratuity Collected</div>
            <div class="summary-value"><?php echo money_fmt($gratuityTotal); ?></div>
        </div>
    </div>
</div>

<?php
    $variance = round($summary['gross_sales'] - $totalCollected, 2);
?>
<?php if (abs($variance) > 0.01): ?>
    <div class="alert alert-warning cashup-print-hide">
        <i class="bi bi-exclamation-triangle-fill me-1"></i>
        Gross sales (<?php echo money_fmt($summary['gross_sales']); ?>) and total accounted payments (<?php echo money_fmt($totalCollected); ?>) differ by <?php echo money_fmt(abs($variance)); ?>.
        This can happen if a closed order has no posted payment on file &mdash; check the detail list below.
    </div>
<?php endif; ?>

<div class="card panel-card mb-3">
    <div class="card-header"><h5 class="mb-0">Payment Method Breakdown</h5></div>
    <div class="card-body p-0">
        <table class="table table-modern align-middle mb-0">
            <thead><tr><th>Method</th><th class="text-end">Transactions</th><th class="text-end">Amount</th><th class="text-end">% of Total</th></tr></thead>
            <tbody>
            <?php if (!$methodTotals): ?>
                <tr><td colspan="4" class="text-center text-muted py-4">No payments recorded for this filter.</td></tr>
            <?php else: foreach ($methodTotals as $method => $m): ?>
                <tr>
                    <td><?php echo h($method); ?></td>
                    <td class="text-end"><?php echo number_format($m['count']); ?></td>
                    <td class="text-end fw-bold"><?php echo money_fmt($m['amount']); ?></td>
                    <td class="text-end text-muted"><?php echo $totalCollected > 0 ? number_format(($m['amount'] / $totalCollected) * 100, 1) : '0.0'; ?>%</td>
                </tr>
            <?php endforeach; endif; ?>
            </tbody>
            <?php if ($methodTotals): ?>
            <tfoot>
                <tr class="table-light fw-bold">
                    <td>Total</td>
                    <td class="text-end"><?php echo number_format(array_sum(array_column($methodTotals, 'count'))); ?></td>
                    <td class="text-end"><?php echo money_fmt($totalCollected); ?></td>
                    <td class="text-end">100.0%</td>
                </tr>
            </tfoot>
            <?php endif; ?>
        </table>
    </div>
</div>

<div class="card panel-card mb-3">
    <div class="card-header"><h5 class="mb-0">Breakdown by Cashier</h5></div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-modern align-middle mb-0">
                <thead>
                <tr>
                    <th>Cashier</th>
                    <th class="text-end">Orders</th>
                    <?php foreach ($allMethods as $m): ?><th class="text-end"><?php echo h($m); ?></th><?php endforeach; ?>
                    <th class="text-end">Gross Sales</th>
                </tr>
                </thead>
                <tbody>
                <?php if (!$cashierRows): ?>
                    <tr><td colspan="<?php echo 3 + count($allMethods); ?>" class="text-center text-muted py-4">No closed orders for this filter.</td></tr>
                <?php else: foreach ($cashierRows as $cName => $row): ?>
                    <tr>
                        <td class="fw-bold"><?php echo h($cName); ?></td>
                        <td class="text-end"><?php echo number_format($row['order_count']); ?></td>
                        <?php foreach ($allMethods as $m): ?>
                            <td class="text-end"><?php echo isset($row['methods'][$m]) && $row['methods'][$m] > 0 ? money_fmt($row['methods'][$m]) : '-'; ?></td>
                        <?php endforeach; ?>
                        <td class="text-end fw-bold"><?php echo money_fmt($row['gross_sales']); ?></td>
                    </tr>
                <?php endforeach; endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<?php if ($voidSummary['order_count'] > 0): ?>
<div class="card panel-card mb-3">
    <div class="card-header"><h5 class="mb-0">Voided Orders (Reconciliation)</h5></div>
    <div class="card-body">
        <p class="mb-0">
            <strong><?php echo number_format($voidSummary['order_count']); ?></strong> order<?php echo $voidSummary['order_count'] === 1 ? '' : 's'; ?> voided in this period,
            with a would-be total of <strong><?php echo money_fmt($voidSummary['would_be_total']); ?></strong>. These are excluded from Gross Sales above.
        </p>
    </div>
</div>
<?php endif; ?>

<div class="card panel-card">
    <div class="card-header d-flex justify-content-between align-items-center flex-wrap gap-2">
        <h5 class="mb-0">Closed Orders (Detail)</h5>
        <small class="text-muted"><?php echo number_format(count($detailOrders)); ?> orders</small>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive cashup-detail-wrap">
            <table class="table table-modern align-middle mb-0">
                <thead>
                <tr>
                    <th>Order</th>
                    <th>Guest / Client</th>
                    <th>Cashier</th>
                    <th>Type</th>
                    <th>Payment</th>
                    <th>Close Method</th>
                    <th class="text-end">Total</th>
                    <th>Closed</th>
                </tr>
                </thead>
                <tbody>
                <?php if (!$detailOrders): ?>
                    <tr><td colspan="8" class="text-center text-muted py-4">No closed orders found for this filter.</td></tr>
                <?php else: foreach ($detailOrders as $o): ?>
                    <tr>
                        <td><a href="order_view.php?id=<?php echo (int)$o['id']; ?>"><?php echo h($o['order_no'] ?: ('#' . (int)$o['id'])); ?></a></td>
                        <td><?php echo h($o['guest_name'] ?: '-'); ?></td>
                        <td><?php echo h($o['cashier_name']); ?></td>
                        <td><?php echo h(ucwords(str_replace('_', ' ', (string)$o['order_type']))); ?></td>
                        <td><span class="badge text-bg-<?php echo h(ro_status_badge_class((string)$o['payment_status'])); ?>"><?php echo h(ucwords(str_replace('_', ' ', (string)$o['payment_status'] ?: 'unpaid'))); ?></span></td>
                        <td><?php echo h($o['close_method'] ?: '-'); ?></td>
                        <td class="text-end fw-bold"><?php echo money_fmt($o['total_amount']); ?></td>
                        <td><?php echo h(ro_format_dt($o['closed_when'])); ?></td>
                    </tr>
                <?php endforeach; endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<style>
.compact-restaurant-hero{padding:12px 16px!important;margin-bottom:10px!important}
.panel-card{border-radius:16px;box-shadow:0 12px 30px rgba(15,23,42,.07);border:1px solid #e5e7eb}
.table-modern thead th{font-size:.70rem;text-transform:uppercase;letter-spacing:.05em;color:#64748b;background:#f8fafc;white-space:nowrap}
.table-modern td,.table-modern th{padding:.55rem .7rem;border-bottom:1px solid #eef2f7;font-size:.83rem;vertical-align:middle}
.cashup-detail-wrap{max-height:480px;overflow:auto}

.cashier-picker{display:flex;flex-wrap:wrap;gap:6px;border:1px solid #e5e7eb;border-radius:10px;padding:8px;max-height:120px;overflow:auto}
.cashier-chip{display:inline-flex;align-items:center;gap:5px;background:#f8fafc;border:1px solid #e5e7eb;border-radius:999px;padding:4px 10px;font-size:.78rem;cursor:pointer}
.cashier-chip input{margin:0}
.cashier-toggle-links a{font-size:.75rem;text-decoration:none}

.cashup-scope{font-size:.85rem;color:#334155}

.summary-card{background:#fff;border:1px solid #e5e7eb;border-radius:14px;padding:14px 16px;height:100%}
.summary-label{font-size:.7rem;text-transform:uppercase;letter-spacing:.06em;color:#64748b}
.summary-value{font-size:1.35rem;font-weight:800;color:#111827;margin-top:2px}

@media print{
    .cashup-print-hide{display:none!important}
    .cashier-picker{border:none}
    .cashup-detail-wrap{max-height:none;overflow:visible}
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function () {
    var selectAll = document.getElementById('cashupSelectAll');
    var selectNone = document.getElementById('cashupSelectNone');
    var boxes = document.querySelectorAll('.cashier-picker input[type="checkbox"]');

    if (selectAll) {
        selectAll.addEventListener('click', function (e) {
            e.preventDefault();
            boxes.forEach(function (b) { b.checked = true; });
        });
    }
    if (selectNone) {
        selectNone.addEventListener('click', function (e) {
            e.preventDefault();
            boxes.forEach(function (b) { b.checked = false; });
        });
    }
});
</script>

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