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

require_once __DIR__ . '/pos_recipe_deduction.php';

$pageTitle = 'POS Orders';

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('poso_flash')) {
    function poso_flash(string $type, string $message): void {
        $_SESSION['pos_orders_flash'][] = ['type' => $type, 'message' => $message];
    }
}
if (!function_exists('poso_get_flash')) {
    function poso_get_flash(): array {
        $items = $_SESSION['pos_orders_flash'] ?? [];
        unset($_SESSION['pos_orders_flash']);
        return $items;
    }
}
if (!function_exists('poso_table_exists')) {
    function poso_table_exists(PDO $pdo, string $table): bool {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name=:t");
        $stmt->execute([':t' => $table]);
        return (int)$stmt->fetchColumn() > 0;
    }
}
if (!function_exists('poso_column_exists')) {
    function poso_column_exists(PDO $pdo, string $table, string $column): bool {
        $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 (int)$stmt->fetchColumn() > 0;
    }
}
if (!function_exists('poso_add_column')) {
    function poso_add_column(PDO $pdo, string $table, string $column, string $sql): void {
        if (!poso_column_exists($pdo, $table, $column)) {
            $pdo->exec($sql);
        }
    }
}

$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_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 stock_movements (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        item_id INT UNSIGNED NOT NULL,
        store_id INT UNSIGNED NOT NULL,
        movement_type ENUM('OPENING','GRN','ISSUE','SALE','TRANSFER_IN','TRANSFER_OUT','ADJUSTMENT_IN','ADJUSTMENT_OUT','WASTAGE','RETURN') NOT NULL,
        qty_in DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        qty_out DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        unit_cost DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        total_cost DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        reference_type VARCHAR(60) NULL,
        reference_id BIGINT UNSIGNED NULL,
        notes TEXT NULL,
        movement_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        INDEX idx_stock_reference (reference_type, reference_id)
    ) 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");

    poso_add_column($pdo, 'pos_orders', 'void_reason', "ALTER TABLE pos_orders ADD COLUMN void_reason TEXT NULL AFTER notes");
    poso_add_column($pdo, 'pos_orders', 'voided_at', "ALTER TABLE pos_orders ADD COLUMN voided_at DATETIME NULL AFTER void_reason");
    poso_add_column($pdo, 'pos_orders', 'voided_by', "ALTER TABLE pos_orders ADD COLUMN voided_by INT UNSIGNED NULL AFTER voided_at");

    $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)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    pos_recipe_prepare_tables($pdo);

} catch (Throwable $e) {
    $errors[] = 'Could not prepare POS orders tables: ' . $e->getMessage();
}

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    try {
        if (function_exists('verify_csrf')) verify_csrf();

        $action = (string)($_POST['action'] ?? '');

        if ($action === 'void_order') {
            $posOrderId = (int)($_POST['pos_order_id'] ?? 0);
            $reason = trim((string)($_POST['void_reason'] ?? ''));

            if ($posOrderId <= 0) throw new RuntimeException('Invalid POS receipt selected.');
            if ($reason === '') throw new RuntimeException('Void reason is required.');

            $stmt = $pdo->prepare("SELECT * FROM pos_orders WHERE id = :id LIMIT 1");
            $stmt->execute([':id' => $posOrderId]);
            $order = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$order) throw new RuntimeException('POS receipt not found.');
            if (($order['status'] ?? '') === 'void') throw new RuntimeException('This receipt is already voided.');

            $pdo->beginTransaction();

            $reversal = pos_reverse_stock_deduction_for_order($pdo, $posOrderId, $reason);
            $reversalCount = count($reversal['reversals'] ?? []);

            $stmt = $pdo->prepare("
                UPDATE pos_orders
                SET status='void',
                    sale_type='void',
                    void_reason=:void_reason,
                    voided_at=NOW(),
                    voided_by=:voided_by,
                    updated_at=NOW()
                WHERE id=:id
            ");
            $stmt->execute([
                ':void_reason' => $reason,
                ':voided_by' => $_SESSION['user_id'] ?? null,
                ':id' => $posOrderId,
            ]);

            if (!empty($order['folio_id']) && poso_table_exists($pdo, 'folio_transactions')) {
                $amount = (float)($order['total_amount'] ?? 0);
                $description = 'VOID POS Receipt ' . ($order['pos_no'] ?? ('#' . $posOrderId)) . ' - ' . $reason;

                $data = [
                    'folio_id' => (int)$order['folio_id'],
                    'order_id' => !empty($order['order_id']) ? (int)$order['order_id'] : null,
                    'transaction_date' => date('Y-m-d'),
                    'date' => date('Y-m-d'),
                    'type' => 'reversal',
                    'transaction_type' => 'reversal',
                    'source' => 'pos_void',
                    'source_id' => $posOrderId,
                    'description' => $description,
                    'amount' => -$amount,
                    'debit' => 0,
                    'credit' => $amount,
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s'),
                ];

                $cols = [];
                $marks = [];
                $params = [];

                foreach ($data as $col => $val) {
                    if (poso_column_exists($pdo, 'folio_transactions', $col)) {
                        $cols[] = "`$col`";
                        $marks[] = ':' . $col;
                        $params[':' . $col] = $val;
                    }
                }

                if ($cols) {
                    $stmt = $pdo->prepare("INSERT INTO folio_transactions (" . implode(',', $cols) . ") VALUES (" . implode(',', $marks) . ")");
                    $stmt->execute($params);
                }

                if (poso_table_exists($pdo, 'folios')) {
                    $updates = [];
                    if (poso_column_exists($pdo, 'folios', 'total_charges')) $updates[] = "total_charges = GREATEST(0, COALESCE(total_charges,0) - :amount)";
                    if (poso_column_exists($pdo, 'folios', 'balance')) $updates[] = "balance = COALESCE(balance,0) - :amount";
                    if (poso_column_exists($pdo, 'folios', 'updated_at')) $updates[] = "updated_at = NOW()";

                    if ($updates) {
                        $stmt = $pdo->prepare("UPDATE folios SET " . implode(',', $updates) . " WHERE id=:folio_id");
                        $stmt->execute([':amount' => $amount, ':folio_id' => (int)$order['folio_id']]);
                    }
                }
            }

            $pdo->commit();

            poso_flash('success', 'Receipt voided and stock reversed. Reversal lines: ' . $reversalCount . '.');
            header('Location: pos_orders.php?view_id=' . $posOrderId);
            exit;
        }

    } catch (Throwable $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        poso_flash('danger', $e->getMessage());
        header('Location: pos_orders.php');
        exit;
    }
}

$stores = [];
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);
} catch (Throwable $e) {
    $errors[] = 'Could not load stores: ' . $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);
$status = trim((string)($_GET['status'] ?? ''));
$paymentMethod = trim((string)($_GET['payment_method'] ?? ''));
$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;
}

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

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

$orders = [];
$summary = ['count'=>0, 'sales'=>0, 'voids'=>0, 'room_charges'=>0, 'deducted_lines'=>0, 'reversal_lines'=>0];

try {
    $stmt = $pdo->prepare("
        SELECT
            po.*,
            sl.location_name,
            COALESCE(pi.line_count,0) AS line_count,
            COALESCE(pi.qty_total,0) AS qty_total,
            COALESCE(d.deduction_count,0) AS deduction_count,
            COALESCE(r.reversal_count,0) AS reversal_count
        FROM pos_orders po
        LEFT JOIN store_locations sl ON sl.id = po.store_id
        LEFT JOIN (
            SELECT pos_order_id, COUNT(*) AS line_count, SUM(qty) AS qty_total
            FROM pos_order_items
            GROUP BY pos_order_id
        ) pi ON pi.pos_order_id = po.id
        LEFT JOIN (
            SELECT pos_order_id, COUNT(*) AS deduction_count
            FROM pos_stock_deductions
            GROUP BY pos_order_id
        ) d ON d.pos_order_id = po.id
        LEFT JOIN (
            SELECT reference_id AS pos_order_id, COUNT(*) AS reversal_count
            FROM stock_movements
            WHERE reference_type = 'POS_ORDER_REVERSAL'
            GROUP BY reference_id
        ) r ON r.pos_order_id = po.id
        WHERE $where
        ORDER BY po.created_at DESC, po.id DESC
        LIMIT 700
    ");
    $stmt->execute($params);
    $orders = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($orders as $o) {
        $summary['count']++;
        $summary['deducted_lines'] += (int)$o['deduction_count'];
        $summary['reversal_lines'] += (int)$o['reversal_count'];

        if (($o['status'] ?? '') === 'void') {
            $summary['voids'] += (float)$o['total_amount'];
        } else {
            $summary['sales'] += (float)$o['total_amount'];
            if (($o['payment_method'] ?? '') === 'room_charge') $summary['room_charges'] += (float)$o['total_amount'];
        }
    }
} catch (Throwable $e) {
    $errors[] = 'Could not load POS orders: ' . $e->getMessage();
}

$viewId = (int)($_GET['view_id'] ?? 0);
$viewOrder = null;
$viewItems = [];
$viewDeductions = [];
$viewReversals = [];

if ($viewId > 0) {
    try {
        $stmt = $pdo->prepare("
            SELECT po.*, sl.location_name
            FROM pos_orders po
            LEFT JOIN store_locations sl ON sl.id = po.store_id
            WHERE po.id = :id
            LIMIT 1
        ");
        $stmt->execute([':id' => $viewId]);
        $viewOrder = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;

        if ($viewOrder) {
            $stmt = $pdo->prepare("SELECT * FROM pos_order_items WHERE pos_order_id=:id ORDER BY id ASC");
            $stmt->execute([':id' => $viewId]);
            $viewItems = $stmt->fetchAll(PDO::FETCH_ASSOC);

            $stmt = $pdo->prepare("
                SELECT d.*, sold.item_name AS sold_item_name, deducted.item_name AS deducted_item_name, sl.location_name
                FROM pos_stock_deductions d
                LEFT JOIN inventory_items sold ON sold.id = d.sold_item_id
                LEFT JOIN inventory_items deducted ON deducted.id = d.deducted_item_id
                LEFT JOIN store_locations sl ON sl.id = d.store_id
                WHERE d.pos_order_id = :id
                ORDER BY d.id ASC
            ");
            $stmt->execute([':id' => $viewId]);
            $viewDeductions = $stmt->fetchAll(PDO::FETCH_ASSOC);

            $stmt = $pdo->prepare("
                SELECT sm.*, ii.item_name, sl.location_name
                FROM stock_movements sm
                LEFT JOIN inventory_items ii ON ii.id = sm.item_id
                LEFT JOIN store_locations sl ON sl.id = sm.store_id
                WHERE sm.reference_type='POS_ORDER_REVERSAL'
                  AND sm.reference_id=:id
                ORDER BY sm.id ASC
            ");
            $stmt->execute([':id' => $viewId]);
            $viewReversals = $stmt->fetchAll(PDO::FETCH_ASSOC);
        }
    } catch (Throwable $e) {
        $errors[] = 'Could not load receipt details: ' . $e->getMessage();
    }
}

$flashes = poso_get_flash();

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-receipt"></i> Stores &amp; POS</div>
            <div class="hero-title mt-2">POS Orders</div>
            <div class="hero-subtitle mt-2">View receipts and void safely with stock/recipe reversal.</div>
        </div>
        <div class="col-lg-4 text-lg-end">
            <a href="pos.php" class="btn btn-light me-2"><i class="bi bi-cash-register me-2"></i>Open POS</a>
            <a href="/rooms/modules/inventory/pos_sales_report.php" class="btn btn-outline-light"><i class="bi bi-bar-chart me-2"></i>Sales Report</a>
        </div>
    </div>
</div>

<?php foreach ($flashes as $flash): ?>
    <div class="alert alert-<?php echo h($flash['type']); ?> no-print"><?php echo h($flash['message']); ?></div>
<?php endforeach; ?>

<?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; ?>

<?php if ($viewOrder): ?>
<div class="card panel-card mb-4 receipt-view" id="receiptPrint">
    <div class="card-header d-flex justify-content-between align-items-center">
        <div>
            <h5 class="mb-0">Receipt <?php echo h($viewOrder['pos_no']); ?></h5>
            <div class="small text-muted"><?php echo h(date('Y-m-d H:i', strtotime($viewOrder['created_at']))); ?> • <?php echo h($viewOrder['location_name'] ?: 'Store'); ?></div>
        </div>
        <div class="d-flex gap-2 no-print">
            <button type="button" class="btn btn-sm btn-outline-primary" onclick="window.print()"><i class="bi bi-printer me-1"></i>Print</button>
            <a href="pos_orders.php" class="btn btn-sm btn-outline-secondary">Close</a>
        </div>
    </div>
    <div class="card-body">
        <div class="row g-3 mb-3">
            <div class="col-md-3"><strong>Status:</strong><br>
                <span class="badge <?php echo $viewOrder['status'] === 'void' ? 'text-bg-danger' : ($viewOrder['status'] === 'charged_to_room' ? 'text-bg-info' : 'text-bg-success'); ?>">
                    <?php echo h(ucwords(str_replace('_',' ', $viewOrder['status']))); ?>
                </span>
            </div>
            <div class="col-md-3"><strong>Payment:</strong><br><?php echo h(ucwords(str_replace('_',' ', $viewOrder['payment_method'] ?: '—'))); ?></div>
            <div class="col-md-3"><strong>Guest:</strong><br><?php echo h($viewOrder['guest_name'] ?: 'Walk-in'); ?></div>
            <div class="col-md-3 text-md-end"><strong>Total:</strong><br><span class="fs-5 fw-bold"><?php echo money_fmt($viewOrder['total_amount']); ?></span></div>
        </div>

        <?php if ($viewOrder['status'] === 'void'): ?>
            <div class="alert alert-danger">
                <strong>Voided:</strong> <?php echo h($viewOrder['void_reason'] ?: 'No reason captured'); ?>
                <?php if (!empty($viewOrder['voided_at'])): ?> • <?php echo h($viewOrder['voided_at']); ?><?php endif; ?>
            </div>
        <?php endif; ?>

        <h6 class="fw-bold">Receipt Items</h6>
        <div class="table-responsive mb-4">
            <table class="table table-sm align-middle">
                <thead><tr><th>Item</th><th class="text-end">Qty</th><th class="text-end">Price</th><th class="text-end">Cost</th><th class="text-end">Total</th></tr></thead>
                <tbody>
                <?php foreach ($viewItems as $item): ?>
                    <tr>
                        <td><strong><?php echo h($item['item_name']); ?></strong></td>
                        <td class="text-end"><?php echo money_fmt($item['qty']); ?></td>
                        <td class="text-end"><?php echo money_fmt($item['unit_price']); ?></td>
                        <td class="text-end"><?php echo money_fmt($item['unit_cost']); ?></td>
                        <td class="text-end fw-bold"><?php echo money_fmt($item['line_total']); ?></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
                <tfoot>
                    <tr><th colspan="4" class="text-end">Subtotal</th><th class="text-end"><?php echo money_fmt($viewOrder['subtotal']); ?></th></tr>
                    <tr><th colspan="4" class="text-end">Tax</th><th class="text-end"><?php echo money_fmt($viewOrder['tax_amount']); ?></th></tr>
                    <tr><th colspan="4" class="text-end fs-5">Total</th><th class="text-end fs-5"><?php echo money_fmt($viewOrder['total_amount']); ?></th></tr>
                </tfoot>
            </table>
        </div>

        <h6 class="fw-bold">Stock Deducted</h6>
        <div class="table-responsive mb-4">
            <table class="table table-sm align-middle">
                <thead><tr><th>Sold Item</th><th>Deducted Stock</th><th>Type</th><th>Store</th><th class="text-end">Qty</th><th class="text-end">Cost</th></tr></thead>
                <tbody>
                <?php if (!$viewDeductions): ?>
                    <tr><td colspan="6" class="text-center text-muted py-3">No stock deduction recorded.</td></tr>
                <?php else: foreach ($viewDeductions as $d): ?>
                    <tr>
                        <td><?php echo h($d['sold_item_name'] ?: 'Item'); ?></td>
                        <td><strong><?php echo h($d['deducted_item_name'] ?: 'Stock'); ?></strong></td>
                        <td><span class="badge text-bg-light border"><?php echo h(ucwords(str_replace('_',' ', $d['deduction_type']))); ?></span></td>
                        <td><?php echo h($d['location_name'] ?: 'Store'); ?></td>
                        <td class="text-end"><?php echo money_fmt($d['qty_deducted']); ?></td>
                        <td class="text-end"><?php echo money_fmt($d['total_cost']); ?></td>
                    </tr>
                <?php endforeach; endif; ?>
                </tbody>
            </table>
        </div>

        <h6 class="fw-bold">Stock Reversal</h6>
        <div class="table-responsive mb-4">
            <table class="table table-sm align-middle">
                <thead><tr><th>Date</th><th>Item</th><th>Store</th><th class="text-end">Qty Returned</th><th class="text-end">Cost</th><th>Notes</th></tr></thead>
                <tbody>
                <?php if (!$viewReversals): ?>
                    <tr><td colspan="6" class="text-center text-muted py-3">No stock reversal recorded.</td></tr>
                <?php else: foreach ($viewReversals as $r): ?>
                    <tr class="table-success">
                        <td><?php echo h($r['movement_date']); ?></td>
                        <td><strong><?php echo h($r['item_name'] ?: 'Item'); ?></strong></td>
                        <td><?php echo h($r['location_name'] ?: 'Store'); ?></td>
                        <td class="text-end"><?php echo money_fmt($r['qty_in']); ?></td>
                        <td class="text-end"><?php echo money_fmt($r['total_cost']); ?></td>
                        <td><?php echo h($r['notes'] ?: ''); ?></td>
                    </tr>
                <?php endforeach; endif; ?>
                </tbody>
            </table>
        </div>

        <?php if ($viewOrder['status'] !== 'void'): ?>
            <div class="void-box no-print">
                <form method="post" onsubmit="return confirm('Void this receipt? This will restore deducted stock and recipe ingredients.');">
                    <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                    <input type="hidden" name="action" value="void_order">
                    <input type="hidden" name="pos_order_id" value="<?php echo (int)$viewOrder['id']; ?>">
                    <label class="form-label fw-bold">Void Receipt</label>
                    <div class="input-group">
                        <input type="text" name="void_reason" class="form-control" placeholder="Reason required" required>
                        <button class="btn btn-outline-danger"><i class="bi bi-x-octagon me-1"></i>Void & Reverse Stock</button>
                    </div>
                </form>
            </div>
        <?php endif; ?>
    </div>
</div>
<?php endif; ?>

<div class="row g-4 mb-4 no-print">
    <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">Receipts</div><div class="metric-value"><?php echo (int)$summary['count']; ?></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-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['voids']); ?></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-arrow-counterclockwise"></i></div><div><div class="metric-label">Reversal Lines</div><div class="metric-value"><?php echo (int)$summary['reversal_lines']; ?></div></div></div></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 $s): ?><option value="<?php echo (int)$s['id']; ?>" <?php echo $storeId === (int)$s['id'] ? 'selected' : ''; ?>><?php echo h($s['location_name']); ?></option><?php endforeach; ?></select></div>
            <div class="col-md-2"><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' : ''; ?>>Charged to Room</option><option value="void" <?php echo $status === 'void' ? 'selected' : ''; ?>>Void</option><option value="open" <?php echo $status === 'open' ? 'selected' : ''; ?>>Open</option></select></div>
            <div class="col-md-2"><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 Charge','complimentary'=>'Complimentary'] 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">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="card panel-card no-print">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0">Receipt History</h5>
        <span class="text-muted small">Showing latest 700 matching receipts</span>
    </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 / Room</th><th>Payment</th><th>Status</th>
                    <th class="text-end">Lines</th><th class="text-end">Deducted</th><th class="text-end">Reversed</th><th class="text-end">Total</th><th class="text-end">Action</th>
                </tr>
                </thead>
                <tbody>
                <?php if (!$orders): ?>
                    <tr><td colspan="11" class="text-center text-muted py-4">No POS 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'); ?><div class="small text-muted"><?php echo h($o['room_label'] ?: ''); ?></div></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"><?php echo (int)$o['line_count']; ?></td>
                        <td class="text-end"><?php echo (int)$o['deduction_count']; ?></td>
                        <td class="text-end"><?php echo (int)$o['reversal_count']; ?></td>
                        <td class="text-end fw-bold"><?php echo money_fmt($o['total_amount']); ?></td>
                        <td class="text-end"><a href="pos_orders.php?view_id=<?php echo (int)$o['id']; ?>" class="btn btn-sm btn-outline-primary"><i class="bi bi-eye"></i></a></td>
                    </tr>
                    <?php if ($o['status'] === 'void' && !empty($o['void_reason'])): ?>
                        <tr class="table-danger"><td colspan="11" class="small pt-0"><strong>Void reason:</strong> <?php echo h($o['void_reason']); ?></td></tr>
                    <?php endif; ?>
                <?php endforeach; endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<style>
.small-value{font-size:1rem!important;letter-spacing:0!important}
.receipt-view{border:2px solid rgba(37,99,235,.18)}
.void-box{background:#fff7ed;border:1px solid #fed7aa;border-radius:16px;padding:14px}
@media print{
    .no-print,.sidebar,.enterprise-sidebar,.app-sidebar,.topbar,.navbar,.header,.footer{display:none!important}
    body{background:#fff!important}
    #receiptPrint{box-shadow:none!important;border:0!important}
    .panel-card,.card{box-shadow:none!important}
}
</style>

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