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

require_once __DIR__ . '/pos_recipe_deduction.php';

if (file_exists(__DIR__ . '/../../includes/permission_check.php')) {
    require_once __DIR__ . '/../../includes/permission_check.php';
    if (function_exists('require_permission')) {
        require_permission($pdo, 'pos_orders', 'view');
    }
}

$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);
        }
    }
}
if (!function_exists('poso_user_name_expr')) {
    function poso_user_name_expr(PDO $pdo, string $alias = 'u'): string {
        if (!poso_table_exists($pdo, 'users')) return "NULL";
        if (poso_column_exists($pdo, 'users', 'firstname') && poso_column_exists($pdo, 'users', 'lastname')) return "CONCAT({$alias}.firstname, ' ', {$alias}.lastname)";
        if (poso_column_exists($pdo, 'users', 'name')) return "{$alias}.name";
        if (poso_column_exists($pdo, 'users', 'full_name')) return "{$alias}.full_name";
        if (poso_column_exists($pdo, 'users', 'username')) return "{$alias}.username";
        if (poso_column_exists($pdo, 'users', 'email')) return "{$alias}.email";
        return "CONCAT('User #', {$alias}.id)";
    }
}

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

$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),
        INDEX idx_pos_item_item (item_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    pos_recipe_prepare_tables($pdo);

} catch (Throwable $e) {
    $errors[] = 'Could not prepare POS order 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') {
            if (function_exists('require_permission')) {
                require_permission($pdo, 'pos_void', 'approve');
            }

            $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 POS receipt is already voided.');
            }

            /*
             * Manager approval popup posts manager_approved + manager_password.
             * This verifies the password/PIN and logs approval before voiding.
             */
            $managerApprovedBy = null;
            if (file_exists(__DIR__ . '/../../includes/manager_approval_modal.php')) {
                require_once __DIR__ . '/../../includes/manager_approval_modal.php';
                if (function_exists('require_manager_approval')) {
                    $manager = require_manager_approval(
                        $pdo,
                        'pos_void',
                        'Void POS Receipt ' . ($order['pos_no'] ?? ('#' . $posOrderId)),
                        'pos_order',
                        $posOrderId
                    );
                    $managerApprovedBy = (int)($manager['id'] ?? 0);
                }
            }

            $pdo->beginTransaction();

            /*
             * Reverse stock/recipe deductions.
             */
            $reversal = pos_reverse_stock_deduction_for_order($pdo, $posOrderId, $reason);
            $reversalCount = count($reversal['reversals'] ?? []);

            $voidedBy = $managerApprovedBy ?: (int)($_SESSION['user_id'] ?? 0);

            $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' => $voidedBy ?: null,
                ':id' => $posOrderId,
            ]);

            /*
             * Optional folio reversal if this receipt was charged to room.
             */
            if (!empty($order['folio_id']) && poso_table_exists($pdo, 'folio_transactions')) {
                $description = 'VOID POS Receipt ' . ($order['pos_no'] ?? ('#' . $posOrderId)) . ' - ' . $reason;
                $amount = (float)($order['total_amount'] ?? 0);

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

                $insertData = [
                    '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'),
                ];

                foreach ($insertData 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', 'POS receipt voided successfully with manager approval. Stock 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());
        $redirectId = (int)($_POST['pos_order_id'] ?? 0);
        header('Location: pos_orders.php' . ($redirectId > 0 ? '?view_id=' . $redirectId : ''));
        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,
    'cash_card_transfer' => 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'];
            } else {
                $summary['cash_card_transfer'] += (float)$o['total_amount'];
            }
        }
    }
} catch (Throwable $e) {
    $errors[] = 'Could not load POS orders: ' . $e->getMessage();
}


if (isset($_GET['export_excel']) && (string)$_GET['export_excel'] === '1') {
    $filename = 'pos_orders_' . date('Ymd_His') . '.xls';

    header('Content-Type: application/vnd.ms-excel; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Pragma: no-cache');
    header('Expires: 0');

    $filterStore = 'All stores';
    if ($storeId > 0) {
        foreach ($stores as $s) {
            if ((int)$s['id'] === $storeId) {
                $filterStore = (string)$s['location_name'];
                break;
            }
        }
    }

    echo "<!DOCTYPE html><html><head><meta charset=\"utf-8\">";
    echo "<style>

/* ===== Compact top + filter polish ===== */
.hero-band{
    padding:12px 16px!important;
    margin-bottom:10px!important;
}
.hero-title{
    font-size:1.35rem!important;
    line-height:1.15!important;
    margin-top:2px!important;
}
.hero-subtitle{
    font-size:.82rem!important;
    line-height:1.25!important;
    margin-top:2px!important;
}
.page-eyebrow{
    font-size:.72rem!important;
    letter-spacing:.08em!important;
}
.hero-band .btn{
    padding:6px 10px!important;
    font-size:.8rem!important;
    border-radius:10px!important;
}
.row.g-4.mb-4.no-print{
    margin-bottom:10px!important;
    --bs-gutter-x:.75rem!important;
    --bs-gutter-y:.75rem!important;
}
.metric-card{
    padding:9px 10px!important;
    gap:8px!important;
    min-height:58px!important;
}
.metric-icon{
    width:32px!important;
    height:32px!important;
    border-radius:10px!important;
    font-size:13px!important;
}
.metric-label{
    font-size:.72rem!important;
    margin-bottom:1px!important;
}
.metric-value{
    font-size:1rem!important;
    line-height:1.05!important;
}
.panel-card .card-header{padding:10px 12px!important}
.panel-card .card-body{padding:10px!important}
.form-label{font-size:.72rem!important;margin-bottom:2px!important;font-weight:700!important}
.form-control,.form-select{height:32px!important;min-height:32px!important;font-size:.82rem!important;padding:4px 8px!important;border-radius:9px!important}
.row.g-3{--bs-gutter-x:.65rem!important;--bs-gutter-y:.55rem!important}
.alert.no-print{padding:8px 12px!important;margin-bottom:10px!important;border-radius:12px!important}

        body{font-family:Arial,Helvetica,sans-serif;font-size:11pt;color:#1f2937;}
        .title{font-size:18pt;font-weight:700;color:#111827;margin-bottom:4px;}
        .subtitle{font-size:10pt;color:#6b7280;margin-bottom:14px;}
        .summary td{border:1px solid #d1d5db;padding:7px 10px;}
        .summary .label{background:#f3f4f6;font-weight:700;color:#374151;}
        table.data{border-collapse:collapse;width:100%;margin-top:14px;}
        table.data th{background:#111827;color:#ffffff;font-weight:700;border:1px solid #111827;padding:8px 7px;text-align:left;}
        table.data td{border:1px solid #d1d5db;padding:7px;vertical-align:top;}
        table.data tr:nth-child(even) td{background:#f9fafb;}
        .right{text-align:right;}
        .status-void{background:#fee2e2;color:#991b1b;font-weight:700;}
        .status-ok{background:#dcfce7;color:#166534;font-weight:700;}
        .status-room{background:#e0f2fe;color:#075985;font-weight:700;}
    </style></head><body>";

    echo '<div class="title">POS Orders Export</div>';
    echo '<div class="subtitle">Generated ' . poso_excel_cell(date('Y-m-d H:i:s')) . '</div>';

    echo '<table class="summary" cellspacing="0" cellpadding="0">';
    echo '<tr><td class="label">Date From</td><td>' . poso_excel_cell($dateFrom) . '</td><td class="label">Date To</td><td>' . poso_excel_cell($dateTo) . '</td></tr>';
    echo '<tr><td class="label">Store</td><td>' . poso_excel_cell($filterStore) . '</td><td class="label">Status</td><td>' . poso_excel_cell($status !== '' ? ucwords(str_replace('_',' ', $status)) : 'All') . '</td></tr>';
    echo '<tr><td class="label">Payment</td><td>' . poso_excel_cell($paymentMethod !== '' ? ucwords(str_replace('_',' ', $paymentMethod)) : 'All') . '</td><td class="label">Search</td><td>' . poso_excel_cell($search !== '' ? $search : '—') . '</td></tr>';
    echo '<tr><td class="label">Receipts</td><td class="right">' . (int)$summary['count'] . '</td><td class="label">Sales</td><td class="right">' . money_fmt($summary['sales']) . '</td></tr>';
    echo '<tr><td class="label">Voids</td><td class="right">' . money_fmt($summary['voids']) . '</td><td class="label">Reversal Lines</td><td class="right">' . (int)$summary['reversal_lines'] . '</td></tr>';
    echo '</table>';

    echo '<table class="data" cellspacing="0" cellpadding="0">';
    echo '<thead><tr>';
    foreach (['Date','Receipt','Store','Guest','Room','Payment','Status','Lines','Qty Total','Deducted','Reversed','Subtotal','Tax','Discount','Total','Void Reason'] as $head) {
        echo '<th>' . poso_excel_cell($head) . '</th>';
    }
    echo '</tr></thead><tbody>';

    if (!$orders) {
        echo '<tr><td colspan="16">No POS receipts found for selected filters.</td></tr>';
    } else {
        foreach ($orders as $o) {
            $statusText = ucwords(str_replace('_',' ', (string)($o['status'] ?? '')));
            $statusClass = ($o['status'] ?? '') === 'void' ? 'status-void' : ((($o['status'] ?? '') === 'charged_to_room') ? 'status-room' : 'status-ok');
            echo '<tr>';
            echo '<td>' . poso_excel_cell(date('Y-m-d H:i', strtotime((string)$o['created_at']))) . '</td>';
            echo '<td><strong>' . poso_excel_cell($o['pos_no'] ?? '') . '</strong></td>';
            echo '<td>' . poso_excel_cell($o['location_name'] ?: 'Store') . '</td>';
            echo '<td>' . poso_excel_cell($o['guest_name'] ?: 'Walk-in') . '</td>';
            echo '<td>' . poso_excel_cell($o['room_label'] ?: '') . '</td>';
            echo '<td>' . poso_excel_cell(ucwords(str_replace('_',' ', (string)($o['payment_method'] ?: '—')))) . '</td>';
            echo '<td class="' . $statusClass . '">' . poso_excel_cell($statusText) . '</td>';
            echo '<td class="right">' . (int)$o['line_count'] . '</td>';
            echo '<td class="right">' . money_fmt($o['qty_total']) . '</td>';
            echo '<td class="right">' . (int)$o['deduction_count'] . '</td>';
            echo '<td class="right">' . (int)$o['reversal_count'] . '</td>';
            echo '<td class="right">' . money_fmt($o['subtotal']) . '</td>';
            echo '<td class="right">' . money_fmt($o['tax_amount']) . '</td>';
            echo '<td class="right">' . money_fmt($o['discount_amount']) . '</td>';
            echo '<td class="right"><strong>' . money_fmt($o['total_amount']) . '</strong></td>';
            echo '<td>' . poso_excel_cell($o['void_reason'] ?? '') . '</td>';
            echo '</tr>';
        }
    }

    echo '</tbody></table>';
    echo '</body></html>';
    exit;
}

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

if ($viewId > 0) {
    try {
        $managerNameExpr = poso_user_name_expr($pdo, 'mu');

        $stmt = $pdo->prepare("
            SELECT po.*, sl.location_name, {$managerNameExpr} AS voided_by_name
            FROM pos_orders po
            LEFT JOIN store_locations sl ON sl.id = po.store_id
            " . (poso_table_exists($pdo, 'users') ? "LEFT JOIN users mu ON mu.id = po.voided_by" : "") . "
            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);

            if (poso_table_exists($pdo, 'manager_approval_log')) {
                $stmt = $pdo->prepare("
                    SELECT mal.*, " . poso_user_name_expr($pdo, 'u') . " AS manager_name
                    FROM manager_approval_log mal
                    " . (poso_table_exists($pdo, 'users') ? "LEFT JOIN users u ON u.id = mal.manager_user_id" : "") . "
                    WHERE mal.reference_type='pos_order'
                      AND mal.reference_id=:id
                    ORDER BY mal.created_at DESC
                ");
                $stmt->execute([':id' => $viewId]);
                $viewApprovals = $stmt->fetchAll(PDO::FETCH_ASSOC);
            }
        }
    } catch (Throwable $e) {
        $errors[] = 'Could not load POS order detail: ' . $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, stock deductions, room charges and safely void receipts with manager approval.
            </div>
        </div>
        <div class="col-lg-4 text-lg-end">
            <?php $exportQuery = $_GET; $exportQuery['export_excel'] = '1'; unset($exportQuery['view_id']); ?>
            <a href="pos_orders.php?<?php echo h(http_build_query($exportQuery)); ?>" class="btn btn-success me-2">
                <i class="bi bi-file-earmark-excel me-2"></i>Export Excel
            </a>
            <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; ?>
                <?php if (!empty($viewOrder['voided_by_name'])): ?> • Approved by <?php echo h($viewOrder['voided_by_name']); ?><?php endif; ?>
            </div>
        <?php endif; ?>

        <?php if ($viewApprovals): ?>
            <div class="alert alert-success">
                <strong>Manager approval log:</strong>
                <?php foreach ($viewApprovals as $a): ?>
                    <div class="small">
                        <?php echo h($a['created_at']); ?> —
                        <?php echo h($a['manager_name'] ?: ('Manager #' . $a['manager_user_id'])); ?>
                        approved <?php echo h($a['action_label'] ?: $a['permission_key']); ?>.
                    </div>
                <?php endforeach; ?>
            </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: ?>
                    <?php 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; ?>
                <?php 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: ?>
                    <?php 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; ?>
                <?php endif; ?>
                </tbody>
            </table>
        </div>

        <?php if ($viewOrder['status'] !== 'void'): ?>
            <div class="void-box no-print">
                <form method="post" id="voidReceiptForm">
                    <?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']; ?>">
                    <input type="hidden" name="manager_approved" value="0">
                    <input type="hidden" name="manager_password" value="">

                    <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 type="button"
                                class="btn btn-outline-danger manager-approval-trigger"
                                data-action-title="Void POS Receipt <?php echo h($viewOrder['pos_no']); ?>"
                                data-action-message="Manager approval is required to void this receipt and reverse deducted stock."
                                data-target-form="#voidReceiptForm">
                            <i class="bi bi-x-octagon me-1"></i>Void & Reverse Stock
                        </button>
                    </div>
                    <div class="small text-muted mt-2">
                        This action requires manager/admin password or PIN before it can continue.
                    </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 flex-wrap gap-2">
        <h5 class="mb-0">Receipt History</h5>
        <div class="d-flex align-items-center gap-2">
            <?php $exportQuery = $_GET; $exportQuery['export_excel'] = '1'; unset($exportQuery['view_id']); ?>
            <a href="pos_orders.php?<?php echo h(http_build_query($exportQuery)); ?>" class="btn btn-sm btn-outline-success">
                <i class="bi bi-file-earmark-excel me-1"></i>Export Excel
            </a>
            <span class="text-muted small">Showing latest 700 matching receipts</span>
        </div>
    </div>
    <div class="card-body p-0">
<div class="pos-table-wrap">
    <table class="table table-modern align-middle mb-0 pos-table">
                <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: ?>
                    <?php 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; ?>
                <?php 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}
}
/* ===== POS Orders Sticky Header ===== */

.pos-table-wrap{
    max-height: 650px;
    overflow: auto;
    position: relative;
}

/* Freeze header */
.pos-table thead th{
    position: sticky;
    top: 0;
    z-index: 100;
    background: #ffffff;
    color: #0f172a;
    box-shadow: 0 2px 6px rgba(15,23,42,.12);
}

/* Clean separation */
.pos-table thead th{
    border-bottom: 2px solid #e2e8f0;
}
</style>

<?php
if (file_exists(__DIR__ . '/../../includes/manager_approval_modal.php')) {
    require_once __DIR__ . '/../../includes/manager_approval_modal.php';
}
?>

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