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

$pageTitle = 'Front Office Shift Summary';

if (!function_exists('h')) {
    function h($value): string
    {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('money_fmt')) {
    function money_fmt($amount): string
    {
        return number_format((float)$amount, 2);
    }
}

if (!function_exists('fo_table_exists')) {
    function fo_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 = :table_name
            ");
            $stmt->execute([':table_name' => $table]);
            $cache[$table] = ((int)$stmt->fetchColumn() > 0);
        } catch (Throwable $e) {
            $cache[$table] = false;
        }

        return $cache[$table];
    }
}

if (!function_exists('fo_column_exists')) {
    function fo_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 = :table_name
                  AND column_name = :column_name
            ");
            $stmt->execute([
                ':table_name' => $table,
                ':column_name' => $column,
            ]);
            $cache[$key] = ((int)$stmt->fetchColumn() > 0);
        } catch (Throwable $e) {
            $cache[$key] = false;
        }

        return $cache[$key];
    }
}

if (!function_exists('fo_current_user_id')) {
    function fo_current_user_id(): int
    {
        foreach (['user_id', 'ss_user_id', 'id', 'uid', 'staffid'] as $key) {
            if (!empty($_SESSION[$key]) && (int)$_SESSION[$key] > 0) {
                return (int)$_SESSION[$key];
            }
        }
        return 0;
    }
}

if (!function_exists('fo_current_user_name')) {
    function fo_current_user_name(): string
    {
        foreach (['currentUserName', 'current_user_name', 'user_name', 'username', 'full_name', 'name'] as $key) {
            if (!empty($_SESSION[$key]) && trim((string)$_SESSION[$key]) !== '') {
                return trim((string)$_SESSION[$key]);
            }
        }
        return 'Logged Cashier';
    }
}

if (!function_exists('fo_is_card_method')) {
    function fo_is_card_method(string $method): bool
    {
        $method = strtolower(trim($method));
        return in_array($method, ['pos', 'card', 'credit card', 'debit card', 'visa', 'mastercard', 'pos/card', 'card payment'], true);
    }
}

$errors = [];

$today = date('Y-m-d');
$dateFrom = trim((string)($_GET['date_from'] ?? $today));
$dateTo   = trim((string)($_GET['date_to'] ?? $today));
$cashierId = (int)($_GET['cashier_id'] ?? 0);
$paymentMethod = trim((string)($_GET['payment_method'] ?? ''));
$saleType = trim((string)($_GET['sale_type'] ?? ''));

if ($dateFrom === '') {
    $dateFrom = $today;
}
if ($dateTo === '') {
    $dateTo = $today;
}

if (strtotime($dateFrom) === false || strtotime($dateTo) === false) {
    $errors[] = 'Invalid date range selected.';
} elseif (strtotime($dateFrom) > strtotime($dateTo)) {
    $errors[] = 'Date from cannot be after date to.';
}

$ordersTable = 'restaurant_orders';
$itemsTable = 'restaurant_order_items';
$paymentsTable = 'restaurant_payments';

foreach ([$ordersTable, $itemsTable, $paymentsTable] as $requiredTable) {
    if (!fo_table_exists($pdo, $requiredTable)) {
        $errors[] = 'Required table missing: ' . $requiredTable;
    }
}

$hasCashierName = !$errors && fo_column_exists($pdo, $ordersTable, 'cashier_name');
$hasOpenedBy = !$errors && fo_column_exists($pdo, $ordersTable, 'opened_by');
$hasClosedBy = !$errors && fo_column_exists($pdo, $ordersTable, 'closed_by');
$hasOrderType = !$errors && fo_column_exists($pdo, $ordersTable, 'order_type');
$hasNotes = !$errors && fo_column_exists($pdo, $ordersTable, 'notes');
$hasCreatedByPayments = !$errors && fo_column_exists($pdo, $paymentsTable, 'created_by');
$hasStatusPayments = !$errors && fo_column_exists($pdo, $paymentsTable, 'status');
$hasPaymentDate = !$errors && fo_column_exists($pdo, $paymentsTable, 'payment_date');
$hasItemStatus = !$errors && fo_column_exists($pdo, $itemsTable, 'status');
$hasItemName = !$errors && fo_column_exists($pdo, $itemsTable, 'item_name');
$hasItemLineTotal = !$errors && fo_column_exists($pdo, $itemsTable, 'line_total');
$hasTaxAmount = !$errors && fo_column_exists($pdo, $itemsTable, 'tax_amount');
$hasPrinterRole = !$errors && fo_column_exists($pdo, $itemsTable, 'printer_role');

$cashiers = [];
$paymentMethods = [];
/*
   IMPORTANT: This report now uses the same sale base as sales_list.php:
   DATE(ro.opened_at), no physical table, and order_type frontoffice/spa/curio/walkin/room.
   This keeps Shift Summary and Sales List aligned.
*/
$summary = [
    'sales_count' => 0,
    'closed_sales_count' => 0,
    'gross_sales' => 0.00,
    'payments_total' => 0.00,
    'cash_total' => 0.00,
    'card_pos_total' => 0.00,
    'folio_total' => 0.00,
    'other_total' => 0.00,
    'surcharge_total' => 0.00,
    'spa_total' => 0.00,
    'curio_total' => 0.00,
    'tax_total' => 0.00,
];
$paymentRows = [];
$itemRows = [];
$saleRows = [];
$cashierRows = [];

if (!$errors) {
    try {
        if ($hasOpenedBy || $hasClosedBy || $hasCashierName) {
            $sqlCashiers = "
                SELECT DISTINCT
                    COALESCE(NULLIF(TRIM(cashier_name), ''), CONCAT('User #', COALESCE(opened_by, closed_by, 0))) AS cashier_name,
                    COALESCE(opened_by, closed_by, 0) AS cashier_id
                FROM {$ordersTable}
                WHERE DATE(opened_at) BETWEEN :date_from AND :date_to
                  AND (order_type IN ('front_office','frontoffice','spa','curio','walkin','room') OR order_type IS NULL)
                  AND (table_id IS NULL OR table_id = 0)
                ORDER BY cashier_name ASC
            ";
            $stmt = $pdo->prepare($sqlCashiers);
            $stmt->execute([
                ':date_from' => $dateFrom,
                ':date_to' => $dateTo,
            ]);
            $cashiers = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
        }
    } catch (Throwable $e) {
        $cashiers = [];
    }

    try {
        $stmt = $pdo->query("
            SELECT DISTINCT payment_method
            FROM {$paymentsTable}
            WHERE payment_method IS NOT NULL
              AND TRIM(payment_method) <> ''
            ORDER BY payment_method ASC
        ");
        $paymentMethods = $stmt->fetchAll(PDO::FETCH_COLUMN) ?: [];
    } catch (Throwable $e) {
        $paymentMethods = [];
    }
}

if (!$errors) {
    try {
        $baseWhere = "
            DATE(ro.opened_at) BETWEEN :date_from AND :date_to
            AND (
                ro.order_type IN ('front_office','frontoffice','spa','curio','walkin','room')
                OR ro.order_type IS NULL
            )
            AND (ro.table_id IS NULL OR ro.table_id = 0)
        ";

        $params = [
            ':date_from' => $dateFrom,
            ':date_to' => $dateTo,
        ];

        if ($cashierId > 0) {
            $baseWhere .= " AND (COALESCE(ro.opened_by,0) = :cashier_id OR COALESCE(ro.closed_by,0) = :cashier_id OR COALESCE(rp.created_by,0) = :cashier_id) ";
            $params[':cashier_id'] = $cashierId;
        }

        if ($paymentMethod !== '') {
            $baseWhere .= " AND rp.payment_method = :payment_method ";
            $params[':payment_method'] = $paymentMethod;
        }

        $paymentStatusWhere = $hasStatusPayments ? " AND COALESCE(rp.status,'posted') = 'posted' " : "";

        $stmt = $pdo->prepare("
            SELECT
                rp.payment_method,
                COUNT(*) AS payment_count,
                COALESCE(SUM(rp.amount),0) AS amount_total
            FROM {$paymentsTable} rp
            INNER JOIN {$ordersTable} ro ON ro.id = rp.restaurant_order_id
            WHERE {$baseWhere}
              {$paymentStatusWhere}
            GROUP BY rp.payment_method
            ORDER BY amount_total DESC, rp.payment_method ASC
        ");
        $stmt->execute($params);
        $paymentRows = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];

        foreach ($paymentRows as $pr) {
            $method = (string)($pr['payment_method'] ?? '');
            $amount = (float)($pr['amount_total'] ?? 0);
            $summary['payments_total'] += $amount;

            $lower = strtolower($method);
            if ($lower === 'cash') {
                $summary['cash_total'] += $amount;
            } elseif (fo_is_card_method($method)) {
                $summary['card_pos_total'] += $amount;
            } elseif (strpos($lower, 'folio') !== false || strpos($lower, 'room') !== false || strpos($lower, 'guest') !== false || strpos($lower, 'master') !== false) {
                $summary['folio_total'] += $amount;
            } else {
                $summary['other_total'] += $amount;
            }
        }

        $itemWhere = "
            DATE(ro.opened_at) BETWEEN :date_from AND :date_to
            AND (
                ro.order_type IN ('front_office','frontoffice','spa','curio','walkin','room')
                OR ro.order_type IS NULL
            )
            AND (ro.table_id IS NULL OR ro.table_id = 0)
        ";

        $itemParams = [
            ':date_from' => $dateFrom,
            ':date_to' => $dateTo,
        ];

        if ($cashierId > 0) {
            $itemWhere .= " AND (COALESCE(ro.opened_by,0) = :cashier_id OR COALESCE(ro.closed_by,0) = :cashier_id) ";
            $itemParams[':cashier_id'] = $cashierId;
        }

        if ($saleType === 'spa') {
            $itemWhere .= " AND (LOWER(COALESCE(roi.printer_role,'')) = 'spa' OR LOWER(COALESCE(roi.item_name,'')) LIKE '%spa%' OR LOWER(COALESCE(roi.item_name,'')) LIKE '%massage%' OR LOWER(COALESCE(roi.item_name,'')) LIKE '%treatment%') ";
        } elseif ($saleType === 'curio') {
            $itemWhere .= " AND (LOWER(COALESCE(roi.printer_role,'')) = 'curio' OR LOWER(COALESCE(roi.item_name,'')) LIKE '%curio%' OR LOWER(COALESCE(roi.item_name,'')) LIKE '%gift%' OR LOWER(COALESCE(roi.item_name,'')) LIKE '%shop%') ";
        }

        $itemStatusWhere = $hasItemStatus ? " AND COALESCE(roi.status,'active') = 'active' " : "";

        $stmt = $pdo->prepare("
            SELECT
                CASE
                    WHEN LOWER(COALESCE(roi.item_name,'')) LIKE '%surcharge%' THEN 'Surcharge'
                    WHEN LOWER(COALESCE(roi.printer_role,'')) = 'spa'
                         OR LOWER(COALESCE(roi.item_name,'')) LIKE '%spa%'
                         OR LOWER(COALESCE(roi.item_name,'')) LIKE '%massage%'
                         OR LOWER(COALESCE(roi.item_name,'')) LIKE '%treatment%' THEN 'Spa'
                    WHEN LOWER(COALESCE(roi.printer_role,'')) = 'curio'
                         OR LOWER(COALESCE(roi.item_name,'')) LIKE '%curio%'
                         OR LOWER(COALESCE(roi.item_name,'')) LIKE '%gift%'
                         OR LOWER(COALESCE(roi.item_name,'')) LIKE '%shop%' THEN 'Curio'
                    ELSE 'Other'
                END AS sale_group,
                COUNT(*) AS line_count,
                COALESCE(SUM(roi.qty),0) AS qty_total,
                COALESCE(SUM(roi.line_total),0) AS line_total,
                COALESCE(SUM(COALESCE(roi.tax_amount,0)),0) AS tax_total
            FROM {$itemsTable} roi
            INNER JOIN {$ordersTable} ro ON ro.id = roi.restaurant_order_id
            WHERE {$itemWhere}
              {$itemStatusWhere}
            GROUP BY sale_group
            ORDER BY FIELD(sale_group,'Spa','Curio','Surcharge','Other'), sale_group
        ");
        $stmt->execute($itemParams);
        $itemRows = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];

        foreach ($itemRows as $ir) {
            $group = strtolower((string)($ir['sale_group'] ?? ''));
            $lineTotal = (float)($ir['line_total'] ?? 0);
            $taxTotal = (float)($ir['tax_total'] ?? 0);

            if ($group === 'spa') {
                $summary['spa_total'] += $lineTotal + $taxTotal;
            } elseif ($group === 'curio') {
                $summary['curio_total'] += $lineTotal + $taxTotal;
            } elseif ($group === 'surcharge') {
                $summary['surcharge_total'] += $lineTotal + $taxTotal;
            }

            $summary['gross_sales'] += $lineTotal + $taxTotal;
            $summary['tax_total'] += $taxTotal;
        }

        $saleWhere = "
            DATE(ro.opened_at) BETWEEN :date_from AND :date_to
            AND (
                ro.order_type IN ('front_office','frontoffice','spa','curio','walkin','room')
                OR ro.order_type IS NULL
            )
            AND (ro.table_id IS NULL OR ro.table_id = 0)
        ";

        $saleParams = [
            ':date_from' => $dateFrom,
            ':date_to' => $dateTo,
        ];

        if ($cashierId > 0) {
            $saleWhere .= " AND (COALESCE(ro.opened_by,0) = :cashier_id OR COALESCE(ro.closed_by,0) = :cashier_id) ";
            $saleParams[':cashier_id'] = $cashierId;
        }

        $stmt = $pdo->prepare("
            SELECT
                ro.id,
                ro.order_no,
                ro.guest_name,
                ro.room_no,
                ro.order_type,
                ro.status,
                ro.payment_status,
                ro.subtotal,
                ro.tax_total,
                ro.total_amount,
                ro.opened_at,
                ro.closed_at,
                COALESCE(NULLIF(TRIM(ro.cashier_name), ''), CONCAT('User #', COALESCE(ro.opened_by, ro.closed_by, 0))) AS cashier_name,
                COALESCE(pay.paid_amount,0) AS paid_amount,
                COALESCE(pay.payment_methods,'') AS payment_methods
            FROM {$ordersTable} ro
            LEFT JOIN (
                SELECT
                    restaurant_order_id,
                    SUM(amount) AS paid_amount,
                    GROUP_CONCAT(DISTINCT payment_method ORDER BY payment_method SEPARATOR ', ') AS payment_methods
                FROM {$paymentsTable}
                " . ($hasStatusPayments ? "WHERE COALESCE(status,'posted')='posted'" : "") . "
                GROUP BY restaurant_order_id
            ) pay ON pay.restaurant_order_id = ro.id
            WHERE {$saleWhere}
            ORDER BY COALESCE(ro.closed_at, ro.opened_at, ro.created_at) DESC, ro.id DESC
            LIMIT 500
        ");
        $stmt->execute($saleParams);
        $saleRows = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];

        foreach ($saleRows as $sr) {
            $summary['sales_count']++;
            if (strtolower((string)($sr['status'] ?? '')) === 'closed') {
                $summary['closed_sales_count']++;
            }
        }

        $stmt = $pdo->prepare("
            SELECT
                COALESCE(NULLIF(TRIM(ro.cashier_name), ''), CONCAT('User #', COALESCE(ro.opened_by, ro.closed_by, 0))) AS cashier_name,
                COALESCE(ro.opened_by, ro.closed_by, 0) AS cashier_id,
                COUNT(DISTINCT ro.id) AS sales_count,
                COALESCE(SUM(ro.total_amount),0) AS sales_total,
                COALESCE(SUM(pay.paid_amount),0) AS paid_total
            FROM {$ordersTable} ro
            LEFT JOIN (
                SELECT restaurant_order_id, SUM(amount) AS paid_amount
                FROM {$paymentsTable}
                " . ($hasStatusPayments ? "WHERE COALESCE(status,'posted')='posted'" : "") . "
                GROUP BY restaurant_order_id
            ) pay ON pay.restaurant_order_id = ro.id
            WHERE {$saleWhere}
            GROUP BY cashier_name, cashier_id
            ORDER BY sales_total DESC, cashier_name ASC
        ");
        $stmt->execute($saleParams);
        $cashierRows = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];

    } catch (Throwable $e) {
        $errors[] = 'Could not load shift summary: ' . $e->getMessage();
    }
}

if (isset($_GET['export']) && $_GET['export'] === 'csv' && !$errors) {
    $filename = 'front_office_shift_summary_' . date('Ymd_His') . '.csv';
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $filename . '"');

    $out = fopen('php://output', 'w');

    fputcsv($out, ['Front Office Shift Summary']);
    fputcsv($out, ['Date From', $dateFrom, 'Date To', $dateTo]);
    fputcsv($out, []);
    fputcsv($out, ['Metric', 'Value']);
    foreach ($summary as $key => $value) {
        fputcsv($out, [ucwords(str_replace('_', ' ', $key)), $value]);
    }

    fputcsv($out, []);
    fputcsv($out, ['Payment Method Breakdown']);
    fputcsv($out, ['Payment Method', 'Count', 'Amount']);
    foreach ($paymentRows as $row) {
        fputcsv($out, [$row['payment_method'], $row['payment_count'], $row['amount_total']]);
    }

    fputcsv($out, []);
    fputcsv($out, ['Sale Group Breakdown']);
    fputcsv($out, ['Group', 'Lines', 'Qty', 'Line Total', 'Tax']);
    foreach ($itemRows as $row) {
        fputcsv($out, [$row['sale_group'], $row['line_count'], $row['qty_total'], $row['line_total'], $row['tax_total']]);
    }

    fputcsv($out, []);
    fputcsv($out, ['Sales Detail']);
    fputcsv($out, ['Order No', 'Guest', 'Room', 'Cashier', 'Status', 'Payment Status', 'Total', 'Paid', 'Methods', 'Opened', 'Closed']);
    foreach ($saleRows as $row) {
        fputcsv($out, [
            $row['order_no'],
            $row['guest_name'],
            $row['room_no'],
            $row['cashier_name'],
            $row['status'],
            $row['payment_status'],
            $row['total_amount'],
            $row['paid_amount'],
            $row['payment_methods'],
            $row['opened_at'],
            $row['closed_at'],
        ]);
    }

    fclose($out);
    exit;
}

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

<div class="hero-band fo-compact-hero">
    <div class="row g-4 align-items-center">
        <div class="col-lg-8">
            <div class="page-eyebrow text-white-50">
                <i class="bi bi-person-badge"></i> Front Office POS
            </div>
            <div class="hero-title mt-2">Shift Summary</div>
            <div class="hero-subtitle mt-2">
                Review Spa and Curio POS sales, cashier takings, POS/Card surcharge, and folio postings.
            </div>
        </div>
        <div class="col-lg-4 text-lg-end">
            <a href="front_office_pos.php" class="btn btn-outline-light me-2">
                <i class="bi bi-cash-register me-2"></i>POS
            </a>
            <a href="shift_summary.php?<?php echo h(http_build_query(array_merge($_GET, ['export' => 'csv']))); ?>" class="btn btn-light">
                <i class="bi bi-download me-2"></i>Export CSV
            </a>
        </div>
    </div>
</div>

<?php if ($errors): ?>
    <div class="alert alert-danger">
        <div class="fw-bold mb-2">Please fix the following:</div>
        <ul class="mb-0">
            <?php foreach ($errors as $err): ?>
                <li><?php echo h($err); ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

<div class="card panel-card mb-4">
    <div class="card-body">
        <form method="get" class="row g-3 align-items-end">
            <div class="col-md-2">
                <label class="form-label">Date From</label>
                <input type="date" name="date_from" class="form-control" value="<?php echo h($dateFrom); ?>">
            </div>

            <div class="col-md-2">
                <label class="form-label">Date To</label>
                <input type="date" name="date_to" class="form-control" value="<?php echo h($dateTo); ?>">
            </div>

            <div class="col-md-2">
                <label class="form-label">Cashier</label>
                <select name="cashier_id" class="form-select">
                    <option value="0">All cashiers</option>
                    <?php foreach ($cashiers as $cashier): ?>
                        <?php $cid = (int)($cashier['cashier_id'] ?? 0); ?>
                        <option value="<?php echo $cid; ?>" <?php echo $cashierId === $cid ? 'selected' : ''; ?>>
                            <?php echo h($cashier['cashier_name'] ?? ('User #' . $cid)); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="col-md-2">
                <label class="form-label">Payment</label>
                <select name="payment_method" class="form-select">
                    <option value="">All methods</option>
                    <?php foreach ($paymentMethods as $pm): ?>
                        <option value="<?php echo h($pm); ?>" <?php echo $paymentMethod === $pm ? 'selected' : ''; ?>>
                            <?php echo h($pm); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="col-md-2">
                <label class="form-label">Sale Type</label>
                <select name="sale_type" class="form-select">
                    <option value="">All</option>
                    <option value="spa" <?php echo $saleType === 'spa' ? 'selected' : ''; ?>>Spa</option>
                    <option value="curio" <?php echo $saleType === 'curio' ? 'selected' : ''; ?>>Curio</option>
                </select>
            </div>

            <div class="col-md-2 d-grid">
                <button class="btn btn-primary">
                    <i class="bi bi-funnel me-2"></i>Apply
                </button>
            </div>
        </form>
    </div>
</div>

<div class="row g-4 mb-4">
    <div class="col-md-6 col-xl-2">
        <div class="metric-card">
            <div class="metric-icon bg-primary-subtle text-primary"><i class="bi bi-receipt"></i></div>
            <div>
                <div class="metric-label">Sales</div>
                <div class="metric-value"><?php echo (int)$summary['sales_count']; ?></div>
            </div>
        </div>
    </div>

    <div class="col-md-6 col-xl-2">
        <div class="metric-card">
            <div class="metric-icon bg-success-subtle text-success"><i class="bi bi-cash-stack"></i></div>
            <div>
                <div class="metric-label">Payments</div>
                <div class="metric-value"><?php echo money_fmt($summary['payments_total']); ?></div>
            </div>
        </div>
    </div>

    <div class="col-md-6 col-xl-2">
        <div class="metric-card">
            <div class="metric-icon bg-info-subtle text-info"><i class="bi bi-droplet"></i></div>
            <div>
                <div class="metric-label">Spa</div>
                <div class="metric-value"><?php echo money_fmt($summary['spa_total']); ?></div>
            </div>
        </div>
    </div>

    <div class="col-md-6 col-xl-2">
        <div class="metric-card">
            <div class="metric-icon bg-warning-subtle text-warning"><i class="bi bi-bag-heart"></i></div>
            <div>
                <div class="metric-label">Curio</div>
                <div class="metric-value"><?php echo money_fmt($summary['curio_total']); ?></div>
            </div>
        </div>
    </div>

    <div class="col-md-6 col-xl-2">
        <div class="metric-card">
            <div class="metric-icon bg-danger-subtle text-danger"><i class="bi bi-credit-card"></i></div>
            <div>
                <div class="metric-label">Card/POS</div>
                <div class="metric-value"><?php echo money_fmt($summary['card_pos_total']); ?></div>
            </div>
        </div>
    </div>

    <div class="col-md-6 col-xl-2">
        <div class="metric-card">
            <div class="metric-icon bg-secondary-subtle text-secondary"><i class="bi bi-plus-circle"></i></div>
            <div>
                <div class="metric-label">Surcharge</div>
                <div class="metric-value"><?php echo money_fmt($summary['surcharge_total']); ?></div>
            </div>
        </div>
    </div>
</div>

<div class="row g-4">
    <div class="col-xl-5">
        <div class="card panel-card h-100">
            <div class="card-header">
                <h5 class="mb-0">Payment Breakdown</h5>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive table-freeze">
                    <table class="table table-modern align-middle mb-0">
                        <thead>
                            <tr>
                                <th>Payment Method</th>
                                <th class="text-end">Count</th>
                                <th class="text-end">Amount</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!$paymentRows): ?>
                                <tr><td colspan="3" class="text-center text-muted py-4">No payments found.</td></tr>
                            <?php else: ?>
                                <?php foreach ($paymentRows as $row): ?>
                                    <tr>
                                        <td><strong><?php echo h($row['payment_method']); ?></strong></td>
                                        <td class="text-end"><?php echo (int)$row['payment_count']; ?></td>
                                        <td class="text-end fw-bold"><?php echo money_fmt($row['amount_total']); ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                        <tfoot>
                            <tr>
                                <th colspan="2">Total</th>
                                <th class="text-end"><?php echo money_fmt($summary['payments_total']); ?></th>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <div class="col-xl-7">
        <div class="card panel-card h-100">
            <div class="card-header">
                <h5 class="mb-0">Spa / Curio Breakdown</h5>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive table-freeze">
                    <table class="table table-modern align-middle mb-0">
                        <thead>
                            <tr>
                                <th>Group</th>
                                <th class="text-end">Lines</th>
                                <th class="text-end">Qty</th>
                                <th class="text-end">Line Total</th>
                                <th class="text-end">Tax</th>
                                <th class="text-end">Gross</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!$itemRows): ?>
                                <tr><td colspan="6" class="text-center text-muted py-4">No items found.</td></tr>
                            <?php else: ?>
                                <?php foreach ($itemRows as $row): ?>
                                    <?php $gross = (float)$row['line_total'] + (float)$row['tax_total']; ?>
                                    <tr>
                                        <td><strong><?php echo h($row['sale_group']); ?></strong></td>
                                        <td class="text-end"><?php echo (int)$row['line_count']; ?></td>
                                        <td class="text-end"><?php echo money_fmt($row['qty_total']); ?></td>
                                        <td class="text-end"><?php echo money_fmt($row['line_total']); ?></td>
                                        <td class="text-end"><?php echo money_fmt($row['tax_total']); ?></td>
                                        <td class="text-end fw-bold"><?php echo money_fmt($gross); ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <div class="col-xl-5">
        <div class="card panel-card h-100">
            <div class="card-header">
                <h5 class="mb-0">Cashier Summary</h5>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive table-freeze">
                    <table class="table table-modern align-middle mb-0">
                        <thead>
                            <tr>
                                <th>Cashier</th>
                                <th class="text-end">Sales</th>
                                <th class="text-end">Sales Total</th>
                                <th class="text-end">Paid</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!$cashierRows): ?>
                                <tr><td colspan="4" class="text-center text-muted py-4">No cashier summary found.</td></tr>
                            <?php else: ?>
                                <?php foreach ($cashierRows as $row): ?>
                                    <tr>
                                        <td><strong><?php echo h($row['cashier_name']); ?></strong></td>
                                        <td class="text-end"><?php echo (int)$row['sales_count']; ?></td>
                                        <td class="text-end"><?php echo money_fmt($row['sales_total']); ?></td>
                                        <td class="text-end fw-bold"><?php echo money_fmt($row['paid_total']); ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <div class="col-xl-7">
        <div class="card panel-card h-100">
            <div class="card-header">
                <h5 class="mb-0">Shift Cash-Up Totals</h5>
            </div>
            <div class="card-body">
                <div class="shift-cashup-grid">
                    <div class="shift-box"><span>Cash</span><strong><?php echo money_fmt($summary['cash_total']); ?></strong></div>
                    <div class="shift-box"><span>Card / POS</span><strong><?php echo money_fmt($summary['card_pos_total']); ?></strong></div>
                    <div class="shift-box"><span>Room / Guest / Master Folio</span><strong><?php echo money_fmt($summary['folio_total']); ?></strong></div>
                    <div class="shift-box"><span>Other</span><strong><?php echo money_fmt($summary['other_total']); ?></strong></div>
                    <div class="shift-box"><span>Tax</span><strong><?php echo money_fmt($summary['tax_total']); ?></strong></div>
                    <div class="shift-box"><span>Closed Sales</span><strong><?php echo (int)$summary['closed_sales_count']; ?></strong></div>
                </div>

                <div class="alert alert-light border mt-3 mb-0 small">
                    POS/Card payments include the 3% surcharge where the cashier used a card/POS payment method.
                </div>
            </div>
        </div>
    </div>

    <div class="col-12">
        <div class="card panel-card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Sales Detail</h5>
                <span class="text-muted small">Showing latest 500 sales</span>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive table-freeze">
                    <table class="table table-modern align-middle mb-0">
                        <thead>
                            <tr>
                                <th>Sale</th>
                                <th>Guest / Room</th>
                                <th>Cashier</th>
                                <th>Status</th>
                                <th>Payment</th>
                                <th class="text-end">Total</th>
                                <th class="text-end">Paid</th>
                                <th class="text-end">Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!$saleRows): ?>
                                <tr><td colspan="8" class="text-center text-muted py-4">No sales found.</td></tr>
                            <?php else: ?>
                                <?php foreach ($saleRows as $row): ?>
                                    <tr>
                                        <td>
                                            <div class="data-stack">
                                                <strong><?php echo h($row['order_no'] ?: ('#' . $row['id'])); ?></strong>
                                                <small><?php echo h($row['closed_at'] ?: $row['opened_at']); ?></small>
                                            </div>
                                        </td>
                                        <td>
                                            <div class="data-stack">
                                                <strong><?php echo h($row['guest_name'] ?: 'Walk-in'); ?></strong>
                                                <small><?php echo h($row['room_no'] ? ('Room ' . $row['room_no']) : 'Direct / Front Office'); ?></small>
                                            </div>
                                        </td>
                                        <td><?php echo h($row['cashier_name']); ?></td>
                                        <td>
                                            <span class="badge text-bg-<?php echo strtolower((string)$row['status']) === 'closed' ? 'success' : 'warning'; ?>">
                                                <?php echo h(ucwords(str_replace('_', ' ', (string)$row['status']))); ?>
                                            </span>
                                        </td>
                                        <td>
                                            <div class="data-stack">
                                                <strong><?php echo h(ucwords(str_replace('_', ' ', (string)$row['payment_status']))); ?></strong>
                                                <small><?php echo h($row['payment_methods'] ?: '—'); ?></small>
                                            </div>
                                        </td>
                                        <td class="text-end fw-bold"><?php echo money_fmt($row['total_amount']); ?></td>
                                        <td class="text-end"><?php echo money_fmt($row['paid_amount']); ?></td>
                                        <td class="text-end">
                                            <a href="front_office_pos.php?front_order_id=<?php echo (int)$row['id']; ?>" class="btn btn-sm btn-outline-primary">
                                                Open
                                            </a>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>


<style>
.shift-cashup-grid{
    display:grid;
    grid-template-columns:repeat(3,minmax(0,1fr));
    gap:12px;
}
.shift-box{
    border:1px solid #e5e7eb;
    border-radius:16px;
    padding:14px 16px;
    background:#fff;
    box-shadow:0 10px 24px rgba(15,23,42,.04);
}
.shift-box span{
    display:block;
    color:#64748b;
    font-size:.78rem;
    font-weight:700;
    margin-bottom:4px;
}
.shift-box strong{
    color:#111827;
    font-size:1.15rem;
    font-weight:900;
}
@media(max-width:991.98px){
    .shift-cashup-grid{
        grid-template-columns:repeat(2,minmax(0,1fr));
    }
}
@media(max-width:575.98px){
    .shift-cashup-grid{
        grid-template-columns:1fr;
    }
}

.fo-compact-hero{
    padding: 12px 16px !important;
    border-radius: 16px !important;
    margin-bottom: 14px !important;
}
.fo-compact-hero .row{
    --bs-gutter-y: .5rem;
}
.fo-compact-hero .page-eyebrow{
    font-size: .72rem;
    line-height: 1.1;
}
.fo-compact-hero .hero-title{
    font-size: 1.18rem !important;
    line-height: 1.15 !important;
    margin-top: 4px !important;
}
.fo-compact-hero .hero-subtitle{
    font-size: .8rem !important;
    line-height: 1.25 !important;
    margin-top: 4px !important;
    max-width: 780px;
}
.fo-compact-hero .btn{
    padding: .32rem .65rem;
    font-size: .82rem;
}
.table-freeze{
    max-height: 520px;
    overflow: auto;
}
.table-freeze table{
    border-collapse: separate;
    border-spacing: 0;
}
.table-freeze thead th{
    position: sticky;
    top: 0;
    z-index: 5;
    background: #f8fafc;
    box-shadow: 0 1px 0 #e5e7eb;
}
.table-freeze tfoot th{
    position: sticky;
    bottom: 0;
    z-index: 4;
    background: #fff;
    box-shadow: 0 -1px 0 #e5e7eb;
}

</style>

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