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

$pageTitle = 'POS Sales Report';

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); }
}

$errors = [];

try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS store_locations (
        id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        location_code VARCHAR(50) NULL,
        location_name VARCHAR(150) NOT NULL,
        location_type ENUM('main_store','bar','restaurant','curio','kitchen','housekeeping','maintenance','other') NOT NULL DEFAULT 'main_store',
        is_pos_location TINYINT(1) NOT NULL DEFAULT 0,
        allow_room_charge TINYINT(1) NOT NULL DEFAULT 1,
        is_active TINYINT(1) NOT NULL DEFAULT 1,
        notes TEXT NULL,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY uq_store_location_code (location_code)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $pdo->exec("CREATE TABLE IF NOT EXISTS inventory_item_categories (
        id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        category_name VARCHAR(120) NOT NULL,
        category_type ENUM('stock','food','bar','curio','consumable','service','other') NOT NULL DEFAULT 'stock',
        is_active TINYINT(1) NOT NULL DEFAULT 1,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY uq_inventory_category_name (category_name)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $pdo->exec("CREATE TABLE IF NOT EXISTS inventory_items (
        id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        item_code VARCHAR(60) NULL,
        item_name VARCHAR(180) NOT NULL,
        category_id INT UNSIGNED NULL,
        unit_id INT UNSIGNED NULL,
        item_type ENUM('stock','food','bar','curio','consumable','service','recipe','other') NOT NULL DEFAULT 'stock',
        barcode VARCHAR(100) NULL,
        description TEXT NULL,
        cost_price DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        avg_cost DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        selling_price DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        tax_rate DECIMAL(7,4) NOT NULL DEFAULT 0.0000,
        reorder_level DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        reorder_qty DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        is_stock_item TINYINT(1) NOT NULL DEFAULT 1,
        is_pos_item TINYINT(1) NOT NULL DEFAULT 0,
        allow_room_charge TINYINT(1) NOT NULL DEFAULT 1,
        track_expiry TINYINT(1) NOT NULL DEFAULT 0,
        is_active TINYINT(1) NOT NULL DEFAULT 1,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY uq_inventory_item_code (item_code)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $pdo->exec("CREATE TABLE IF NOT EXISTS pos_orders (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        pos_no VARCHAR(60) NOT NULL,
        store_id INT UNSIGNED NOT NULL,
        order_id INT UNSIGNED NULL,
        folio_id INT UNSIGNED NULL,
        guest_name VARCHAR(180) NULL,
        room_label VARCHAR(80) NULL,
        sale_type ENUM('cash','card','transfer','room_charge','complimentary','void') NOT NULL DEFAULT 'cash',
        payment_method VARCHAR(40) NULL,
        subtotal DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        tax_amount DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        discount_amount DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        total_amount DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        status ENUM('open','paid','charged_to_room','void') NOT NULL DEFAULT 'open',
        notes TEXT NULL,
        void_reason TEXT NULL,
        voided_at DATETIME NULL,
        voided_by INT UNSIGNED NULL,
        created_by INT UNSIGNED NULL,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY uq_pos_no (pos_no),
        INDEX idx_pos_store (store_id),
        INDEX idx_pos_status (status),
        INDEX idx_pos_created (created_at)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $pdo->exec("CREATE TABLE IF NOT EXISTS pos_order_items (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        pos_order_id BIGINT UNSIGNED NOT NULL,
        item_id INT UNSIGNED NOT NULL,
        item_name VARCHAR(180) NOT NULL,
        qty DECIMAL(14,4) NOT NULL DEFAULT 1.0000,
        unit_price DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        unit_cost DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        tax_rate DECIMAL(7,4) NOT NULL DEFAULT 0.0000,
        line_total DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        INDEX idx_pos_item_order (pos_order_id),
        INDEX idx_pos_item_item (item_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
} catch (Throwable $e) {
    $errors[] = 'Could not prepare POS report tables: ' . $e->getMessage();
}

$stores = [];
$categories = [];

try {
    $stores = $pdo->query("SELECT * FROM store_locations WHERE is_active=1 ORDER BY is_pos_location DESC, location_name ASC")->fetchAll(PDO::FETCH_ASSOC);
    $categories = $pdo->query("SELECT * FROM inventory_item_categories WHERE is_active=1 ORDER BY category_name ASC")->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $errors[] = 'Could not load report filters: ' . $e->getMessage();
}

$dateFrom = trim((string)($_GET['date_from'] ?? date('Y-m-01')));
$dateTo = trim((string)($_GET['date_to'] ?? date('Y-m-d')));
$storeId = (int)($_GET['store_id'] ?? 0);
$categoryId = (int)($_GET['category_id'] ?? 0);
$paymentMethod = trim((string)($_GET['payment_method'] ?? ''));
$status = trim((string)($_GET['status'] ?? ''));
$search = trim((string)($_GET['q'] ?? ''));

if (strtotime($dateFrom) === false) $dateFrom = date('Y-m-01');
if (strtotime($dateTo) === false) $dateTo = date('Y-m-d');
if (strtotime($dateFrom) > strtotime($dateTo)) {
    $tmp = $dateFrom; $dateFrom = $dateTo; $dateTo = $tmp;
}

$summary = [
    'orders' => 0,
    'lines' => 0,
    'qty' => 0,
    'sales' => 0,
    'tax' => 0,
    'discount' => 0,
    'cost' => 0,
    'gross_profit' => 0,
    'void_sales' => 0,
    'room_charges' => 0,
];

$orderWhere = "DATE(po.created_at) BETWEEN :date_from AND :date_to";
$orderParams = [':date_from' => $dateFrom, ':date_to' => $dateTo];

if ($storeId > 0) { $orderWhere .= " AND po.store_id = :store_id"; $orderParams[':store_id'] = $storeId; }
if ($paymentMethod !== '') { $orderWhere .= " AND po.payment_method = :payment_method"; $orderParams[':payment_method'] = $paymentMethod; }
if ($status !== '') { $orderWhere .= " AND po.status = :status"; $orderParams[':status'] = $status; }
if ($search !== '') {
    $orderWhere .= " AND (po.pos_no LIKE :q OR po.guest_name LIKE :q OR sl.location_name LIKE :q)";
    $orderParams[':q'] = '%' . $search . '%';
}

$orders = [];
$itemRows = [];
$storeRows = [];
$paymentRows = [];
$categoryRows = [];
$dailyRows = [];

try {
    $stmt = $pdo->prepare("
        SELECT
            po.*,
            sl.location_name,
            COUNT(poi.id) AS line_count,
            COALESCE(SUM(poi.qty),0) AS item_qty,
            COALESCE(SUM(poi.qty * poi.unit_cost),0) AS cost_total
        FROM pos_orders po
        LEFT JOIN store_locations sl ON sl.id = po.store_id
        LEFT JOIN pos_order_items poi ON poi.pos_order_id = po.id
        WHERE $orderWhere
        GROUP BY po.id
        ORDER BY po.created_at DESC, po.id DESC
        LIMIT 700
    ");
    $stmt->execute($orderParams);
    $orders = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($orders as $o) {
        $summary['orders']++;
        $summary['lines'] += (int)$o['line_count'];
        $summary['qty'] += (float)$o['item_qty'];

        if ($o['status'] === 'void') {
            $summary['void_sales'] += (float)$o['total_amount'];
        } else {
            $summary['sales'] += (float)$o['total_amount'];
            $summary['tax'] += (float)$o['tax_amount'];
            $summary['discount'] += (float)$o['discount_amount'];
            $summary['cost'] += (float)$o['cost_total'];
            if (($o['payment_method'] ?? '') === 'room_charge') $summary['room_charges'] += (float)$o['total_amount'];
        }
    }
    $summary['gross_profit'] = $summary['sales'] - $summary['cost'];

    $itemWhere = "DATE(po.created_at) BETWEEN :date_from AND :date_to AND po.status <> 'void'";
    $itemParams = [':date_from' => $dateFrom, ':date_to' => $dateTo];
    if ($storeId > 0) { $itemWhere .= " AND po.store_id = :store_id"; $itemParams[':store_id'] = $storeId; }
    if ($paymentMethod !== '') { $itemWhere .= " AND po.payment_method = :payment_method"; $itemParams[':payment_method'] = $paymentMethod; }
    if ($categoryId > 0) { $itemWhere .= " AND ii.category_id = :category_id"; $itemParams[':category_id'] = $categoryId; }
    if ($search !== '') { $itemWhere .= " AND (poi.item_name LIKE :q OR ii.item_code LIKE :q OR c.category_name LIKE :q)"; $itemParams[':q'] = '%' . $search . '%'; }

    $stmt = $pdo->prepare("
        SELECT
            poi.item_id,
            poi.item_name,
            ii.item_code,
            c.category_name,
            COALESCE(SUM(poi.qty),0) AS qty_sold,
            COALESCE(SUM(poi.line_total),0) AS sales_total,
            COALESCE(SUM(poi.qty * poi.unit_cost),0) AS cost_total,
            COALESCE(SUM(poi.line_total) - SUM(poi.qty * poi.unit_cost),0) AS gross_profit,
            COUNT(DISTINCT po.id) AS order_count
        FROM pos_order_items poi
        INNER JOIN pos_orders po ON po.id = poi.pos_order_id
        LEFT JOIN inventory_items ii ON ii.id = poi.item_id
        LEFT JOIN inventory_item_categories c ON c.id = ii.category_id
        WHERE $itemWhere
        GROUP BY poi.item_id, poi.item_name, ii.item_code, c.category_name
        ORDER BY sales_total DESC
        LIMIT 500
    ");
    $stmt->execute($itemParams);
    $itemRows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $stmt = $pdo->prepare("
        SELECT
            sl.location_name,
            COUNT(DISTINCT po.id) AS order_count,
            COALESCE(SUM(CASE WHEN po.status <> 'void' THEN po.total_amount ELSE 0 END),0) AS sales_total,
            COALESCE(SUM(CASE WHEN po.status = 'void' THEN po.total_amount ELSE 0 END),0) AS void_total,
            COALESCE(SUM(CASE WHEN po.status <> 'void' THEN poi.qty * poi.unit_cost ELSE 0 END),0) AS cost_total
        FROM pos_orders po
        LEFT JOIN store_locations sl ON sl.id = po.store_id
        LEFT JOIN pos_order_items poi ON poi.pos_order_id = po.id
        WHERE DATE(po.created_at) BETWEEN :date_from AND :date_to
        " . ($storeId > 0 ? " AND po.store_id = :store_id" : "") . "
        GROUP BY po.store_id, sl.location_name
        ORDER BY sales_total DESC
    ");
    $storeParams = [':date_from' => $dateFrom, ':date_to' => $dateTo];
    if ($storeId > 0) $storeParams[':store_id'] = $storeId;
    $stmt->execute($storeParams);
    $storeRows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $stmt = $pdo->prepare("
        SELECT
            COALESCE(payment_method, 'unknown') AS payment_method,
            COUNT(*) AS order_count,
            COALESCE(SUM(CASE WHEN status <> 'void' THEN total_amount ELSE 0 END),0) AS sales_total,
            COALESCE(SUM(CASE WHEN status = 'void' THEN total_amount ELSE 0 END),0) AS void_total
        FROM pos_orders
        WHERE DATE(created_at) BETWEEN :date_from AND :date_to
        " . ($storeId > 0 ? " AND store_id = :store_id" : "") . "
        GROUP BY payment_method
        ORDER BY sales_total DESC
    ");
    $payParams = [':date_from' => $dateFrom, ':date_to' => $dateTo];
    if ($storeId > 0) $payParams[':store_id'] = $storeId;
    $stmt->execute($payParams);
    $paymentRows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $stmt = $pdo->prepare("
        SELECT
            COALESCE(c.category_name, 'Uncategorised') AS category_name,
            COALESCE(SUM(poi.qty),0) AS qty_sold,
            COALESCE(SUM(poi.line_total),0) AS sales_total,
            COALESCE(SUM(poi.qty * poi.unit_cost),0) AS cost_total,
            COALESCE(SUM(poi.line_total) - SUM(poi.qty * poi.unit_cost),0) AS gross_profit
        FROM pos_order_items poi
        INNER JOIN pos_orders po ON po.id = poi.pos_order_id
        LEFT JOIN inventory_items ii ON ii.id = poi.item_id
        LEFT JOIN inventory_item_categories c ON c.id = ii.category_id
        WHERE DATE(po.created_at) BETWEEN :date_from AND :date_to
          AND po.status <> 'void'
        " . ($storeId > 0 ? " AND po.store_id = :store_id" : "") . "
        GROUP BY c.category_name
        ORDER BY sales_total DESC
    ");
    $catParams = [':date_from' => $dateFrom, ':date_to' => $dateTo];
    if ($storeId > 0) $catParams[':store_id'] = $storeId;
    $stmt->execute($catParams);
    $categoryRows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $stmt = $pdo->prepare("
        SELECT
            DATE(created_at) AS sale_date,
            COUNT(*) AS order_count,
            COALESCE(SUM(CASE WHEN status <> 'void' THEN total_amount ELSE 0 END),0) AS sales_total,
            COALESCE(SUM(CASE WHEN status = 'void' THEN total_amount ELSE 0 END),0) AS void_total,
            COALESCE(SUM(CASE WHEN status <> 'void' AND payment_method='room_charge' THEN total_amount ELSE 0 END),0) AS room_charges
        FROM pos_orders
        WHERE DATE(created_at) BETWEEN :date_from AND :date_to
        " . ($storeId > 0 ? " AND store_id = :store_id" : "") . "
        GROUP BY DATE(created_at)
        ORDER BY sale_date ASC
    ");
    $dailyParams = [':date_from' => $dateFrom, ':date_to' => $dateTo];
    if ($storeId > 0) $dailyParams[':store_id'] = $storeId;
    $stmt->execute($dailyParams);
    $dailyRows = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

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

<div class="hero-band no-print">
    <div class="row g-4 align-items-center">
        <div class="col-lg-8">
            <div class="page-eyebrow text-white-50"><i class="bi bi-bar-chart"></i> POS Reports</div>
            <div class="hero-title mt-2">POS Sales Report</div>
            <div class="hero-subtitle mt-2">Bar, restaurant and curio sales by item, payment method, room charge, store and gross profit.</div>
        </div>
        <div class="col-lg-4 text-lg-end">
            <button onclick="window.print()" class="btn btn-light me-2"><i class="bi bi-printer me-2"></i>Print</button>
            <a href="inventory_dashboard.php" class="btn btn-outline-light"><i class="bi bi-speedometer2 me-2"></i>Dashboard</a>
        </div>
    </div>
</div>

<?php if ($errors): ?>
    <div class="alert alert-danger no-print">
        <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="print-title">
    <h3 class="mb-1">POS Sales Report</h3>
    <div class="text-muted"><?php echo h(date('d M Y', strtotime($dateFrom))); ?> to <?php echo h(date('d M Y', strtotime($dateTo))); ?></div>
</div>

<div class="card panel-card mb-4 no-print">
    <div class="card-body">
        <form method="get" class="row g-3 align-items-end">
            <div class="col-md-2"><label class="form-label">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">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">Store</label><select name="store_id" class="form-select"><option value="0">All stores</option><?php foreach ($stores as $store): ?><option value="<?php echo (int)$store['id']; ?>" <?php echo $storeId === (int)$store['id'] ? 'selected' : ''; ?>><?php echo h($store['location_name']); ?></option><?php endforeach; ?></select></div>
            <div class="col-md-2"><label class="form-label">Category</label><select name="category_id" class="form-select"><option value="0">All categories</option><?php foreach ($categories as $cat): ?><option value="<?php echo (int)$cat['id']; ?>" <?php echo $categoryId === (int)$cat['id'] ? 'selected' : ''; ?>><?php echo h($cat['category_name']); ?></option><?php endforeach; ?></select></div>
            <div class="col-md-1"><label class="form-label">Payment</label><select name="payment_method" class="form-select"><option value="">All</option><?php foreach (['cash'=>'Cash','card'=>'Card','transfer'=>'Transfer','room_charge'=>'Room','complimentary'=>'Comp'] as $v => $l): ?><option value="<?php echo h($v); ?>" <?php echo $paymentMethod === $v ? 'selected' : ''; ?>><?php echo h($l); ?></option><?php endforeach; ?></select></div>
            <div class="col-md-1"><label class="form-label">Status</label><select name="status" class="form-select"><option value="">All</option><option value="paid" <?php echo $status === 'paid' ? 'selected' : ''; ?>>Paid</option><option value="charged_to_room" <?php echo $status === 'charged_to_room' ? 'selected' : ''; ?>>Room</option><option value="void" <?php echo $status === 'void' ? 'selected' : ''; ?>>Void</option></select></div>
            <div class="col-md-1"><label class="form-label">Search</label><input type="text" name="q" class="form-control" value="<?php echo h($search); ?>"></div>
            <div class="col-md-1 d-grid"><button class="btn btn-primary"><i class="bi bi-funnel"></i></button></div>
        </form>
    </div>
</div>

<div class="row g-4 mb-4">
    <div class="col-md-6 col-xl-3"><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">Orders</div><div class="metric-value"><?php echo (int)$summary['orders']; ?></div></div></div></div>
    <div class="col-md-6 col-xl-3"><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">Sales</div><div class="metric-value small-value"><?php echo money_fmt($summary['sales']); ?></div></div></div></div>
    <div class="col-md-6 col-xl-3"><div class="metric-card"><div class="metric-icon bg-warning-subtle text-warning"><i class="bi bi-graph-up"></i></div><div><div class="metric-label">Gross Profit</div><div class="metric-value small-value"><?php echo money_fmt($summary['gross_profit']); ?></div></div></div></div>
    <div class="col-md-6 col-xl-3"><div class="metric-card"><div class="metric-icon bg-info-subtle text-info"><i class="bi bi-door-open"></i></div><div><div class="metric-label">Room Charges</div><div class="metric-value small-value"><?php echo money_fmt($summary['room_charges']); ?></div></div></div></div>
</div>

<div class="row g-4 mb-4">
    <div class="col-md-6 col-xl-3"><div class="metric-card"><div class="metric-icon bg-secondary-subtle text-secondary"><i class="bi bi-box"></i></div><div><div class="metric-label">Qty Sold</div><div class="metric-value small-value"><?php echo money_fmt($summary['qty']); ?></div></div></div></div>
    <div class="col-md-6 col-xl-3"><div class="metric-card"><div class="metric-icon bg-danger-subtle text-danger"><i class="bi bi-x-octagon"></i></div><div><div class="metric-label">Voids</div><div class="metric-value small-value"><?php echo money_fmt($summary['void_sales']); ?></div></div></div></div>
    <div class="col-md-6 col-xl-3"><div class="metric-card"><div class="metric-icon bg-dark-subtle text-dark"><i class="bi bi-percent"></i></div><div><div class="metric-label">Tax</div><div class="metric-value small-value"><?php echo money_fmt($summary['tax']); ?></div></div></div></div>
    <div class="col-md-6 col-xl-3"><div class="metric-card"><div class="metric-icon bg-light text-dark"><i class="bi bi-arrow-down-circle"></i></div><div><div class="metric-label">Cost</div><div class="metric-value small-value"><?php echo money_fmt($summary['cost']); ?></div></div></div></div>
</div>

<div class="row g-4 mb-4 no-print">
    <div class="col-xl-4"><div class="card panel-card h-100"><div class="card-header"><h5 class="mb-0">Sales by Store</h5></div><div class="card-body p-0"><table class="table table-modern mb-0"><thead><tr><th>Store</th><th class="text-end">Orders</th><th class="text-end">Sales</th><th class="text-end">Profit</th></tr></thead><tbody>
    <?php if (!$storeRows): ?><tr><td colspan="4" class="text-center text-muted py-4">No store sales.</td></tr><?php else: foreach ($storeRows as $row): $profit=(float)$row['sales_total']-(float)$row['cost_total']; ?><tr><td><strong><?php echo h($row['location_name'] ?: 'Store'); ?></strong></td><td class="text-end"><?php echo (int)$row['order_count']; ?></td><td class="text-end"><?php echo money_fmt($row['sales_total']); ?></td><td class="text-end fw-bold"><?php echo money_fmt($profit); ?></td></tr><?php endforeach; endif; ?>
    </tbody></table></div></div></div>

    <div class="col-xl-4"><div class="card panel-card h-100"><div class="card-header"><h5 class="mb-0">Sales by Payment</h5></div><div class="card-body p-0"><table class="table table-modern mb-0"><thead><tr><th>Payment</th><th class="text-end">Orders</th><th class="text-end">Sales</th><th class="text-end">Voids</th></tr></thead><tbody>
    <?php if (!$paymentRows): ?><tr><td colspan="4" class="text-center text-muted py-4">No payment sales.</td></tr><?php else: foreach ($paymentRows as $row): ?><tr><td><strong><?php echo h(ucwords(str_replace('_',' ', $row['payment_method']))); ?></strong></td><td class="text-end"><?php echo (int)$row['order_count']; ?></td><td class="text-end fw-bold"><?php echo money_fmt($row['sales_total']); ?></td><td class="text-end text-danger"><?php echo money_fmt($row['void_total']); ?></td></tr><?php endforeach; endif; ?>
    </tbody></table></div></div></div>

    <div class="col-xl-4"><div class="card panel-card h-100"><div class="card-header"><h5 class="mb-0">Sales by Category</h5></div><div class="card-body p-0"><table class="table table-modern mb-0"><thead><tr><th>Category</th><th class="text-end">Qty</th><th class="text-end">Sales</th><th class="text-end">Profit</th></tr></thead><tbody>
    <?php if (!$categoryRows): ?><tr><td colspan="4" class="text-center text-muted py-4">No category sales.</td></tr><?php else: foreach ($categoryRows as $row): ?><tr><td><strong><?php echo h($row['category_name']); ?></strong></td><td class="text-end"><?php echo money_fmt($row['qty_sold']); ?></td><td class="text-end"><?php echo money_fmt($row['sales_total']); ?></td><td class="text-end fw-bold"><?php echo money_fmt($row['gross_profit']); ?></td></tr><?php endforeach; endif; ?>
    </tbody></table></div></div></div>
</div>

<div class="card panel-card mb-4">
    <div class="card-header d-flex justify-content-between align-items-center"><h5 class="mb-0">Item Sales Performance</h5><span class="text-muted small">Top 500 items</span></div>
    <div class="card-body p-0"><div class="table-responsive"><table class="table table-modern align-middle mb-0">
        <thead><tr><th>Item</th><th>Category</th><th class="text-end">Orders</th><th class="text-end">Qty</th><th class="text-end">Sales</th><th class="text-end">Cost</th><th class="text-end">Gross Profit</th><th class="text-end">Margin %</th></tr></thead>
        <tbody>
        <?php if (!$itemRows): ?><tr><td colspan="8" class="text-center text-muted py-4">No item sales found.</td></tr><?php else: foreach ($itemRows as $row): $sales=(float)$row['sales_total']; $profit=(float)$row['gross_profit']; $margin=$sales>0?($profit/$sales)*100:0; ?>
            <tr>
                <td><strong><?php echo h($row['item_name']); ?></strong><div class="small text-muted"><?php echo h($row['item_code'] ?: ''); ?></div></td>
                <td><?php echo h($row['category_name'] ?: 'Uncategorised'); ?></td>
                <td class="text-end"><?php echo (int)$row['order_count']; ?></td>
                <td class="text-end"><?php echo money_fmt($row['qty_sold']); ?></td>
                <td class="text-end fw-bold"><?php echo money_fmt($sales); ?></td>
                <td class="text-end"><?php echo money_fmt($row['cost_total']); ?></td>
                <td class="text-end fw-bold <?php echo $profit < 0 ? 'text-danger' : 'text-success'; ?>"><?php echo money_fmt($profit); ?></td>
                <td class="text-end"><?php echo money_fmt($margin); ?>%</td>
            </tr>
        <?php endforeach; endif; ?>
        </tbody>
    </table></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">Daily Sales Summary</h5></div><div class="card-body p-0"><table class="table table-modern mb-0"><thead><tr><th>Date</th><th class="text-end">Orders</th><th class="text-end">Sales</th><th class="text-end">Room</th><th class="text-end">Voids</th></tr></thead><tbody>
    <?php if (!$dailyRows): ?><tr><td colspan="5" class="text-center text-muted py-4">No daily sales.</td></tr><?php else: foreach ($dailyRows as $row): ?><tr><td><strong><?php echo h($row['sale_date']); ?></strong></td><td class="text-end"><?php echo (int)$row['order_count']; ?></td><td class="text-end fw-bold"><?php echo money_fmt($row['sales_total']); ?></td><td class="text-end"><?php echo money_fmt($row['room_charges']); ?></td><td class="text-end text-danger"><?php echo money_fmt($row['void_total']); ?></td></tr><?php endforeach; endif; ?>
    </tbody></table></div></div></div>

    <div class="col-xl-7"><div class="card panel-card h-100"><div class="card-header d-flex justify-content-between align-items-center"><h5 class="mb-0">Receipt Detail</h5><a href="/rooms/modules/pos/pos_orders.php?date_from=<?php echo h($dateFrom); ?>&date_to=<?php echo h($dateTo); ?>" class="btn btn-sm btn-outline-primary no-print">Open POS Orders</a></div><div class="card-body p-0"><div class="table-responsive"><table class="table table-modern align-middle mb-0"><thead><tr><th>Date</th><th>Receipt</th><th>Store</th><th>Guest</th><th>Payment</th><th>Status</th><th class="text-end">Total</th></tr></thead><tbody>
    <?php if (!$orders): ?><tr><td colspan="7" class="text-center text-muted py-4">No receipts found.</td></tr><?php else: foreach ($orders as $o): ?><tr class="<?php echo $o['status'] === 'void' ? 'table-danger' : ''; ?>"><td><?php echo h(date('Y-m-d H:i', strtotime($o['created_at']))); ?></td><td><strong><?php echo h($o['pos_no']); ?></strong></td><td><?php echo h($o['location_name'] ?: 'Store'); ?></td><td><?php echo h($o['guest_name'] ?: 'Walk-in'); ?></td><td><?php echo h(ucwords(str_replace('_',' ', $o['payment_method'] ?: '—'))); ?></td><td><span class="badge <?php echo $o['status'] === 'void' ? 'text-bg-danger' : ($o['status'] === 'charged_to_room' ? 'text-bg-info' : 'text-bg-success'); ?>"><?php echo h(ucwords(str_replace('_',' ', $o['status']))); ?></span></td><td class="text-end fw-bold"><?php echo money_fmt($o['total_amount']); ?></td></tr><?php endforeach; endif; ?>
    </tbody></table></div></div></div></div>
</div>

<style>
.small-value{font-size:1rem!important;letter-spacing:0!important}
.print-title{display:none}
@media print{
    .no-print,.sidebar,.enterprise-sidebar,.app-sidebar,.topbar,.navbar,.header,.footer{display:none!important}
    .print-title{display:block;margin-bottom:16px}
    .panel-card,.card{box-shadow:none!important;border:1px solid #ddd!important}
    body{background:#fff!important}
    .table{font-size:10.5px}
    .metric-card{box-shadow:none!important;border:1px solid #ddd!important}
}
</style>

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