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

$pageTitle = 'Restaurant Cashier';

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('cashier_current_user_id')) {
    function cashier_current_user_id(): ?int {
        foreach (['user_id','ss_user_id','id','uid'] as $k) {
            if (isset($_SESSION[$k]) && (int)$_SESSION[$k] > 0) return (int)$_SESSION[$k];
        }
        return null;
    }
}
if (!function_exists('cashier_flash')) {
    function cashier_flash(string $type, string $message): void {
        $_SESSION['restaurant_cashier_flash'][] = ['type'=>$type,'message'=>$message];
    }
    function cashier_get_flash(): array {
        $x = $_SESSION['restaurant_cashier_flash'] ?? [];
        unset($_SESSION['restaurant_cashier_flash']);
        return $x;
    }
}
if (!function_exists('cashier_table_exists')) {
    function cashier_table_exists(PDO $pdo, string $table): bool {
        $s = $pdo->prepare("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name=:t");
        $s->execute([':t'=>$table]);
        return (int)$s->fetchColumn() > 0;
    }
}
if (!function_exists('cashier_column_exists')) {
    function cashier_column_exists(PDO $pdo, string $table, string $column): bool {
        $s = $pdo->prepare("SELECT COUNT(*) FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name=:t AND column_name=:c");
        $s->execute([':t'=>$table, ':c'=>$column]);
        return (int)$s->fetchColumn() > 0;
    }
}
if (!function_exists('cashier_order_total_paid')) {
    function cashier_order_total_paid(PDO $pdo, int $orderId): float {
        $s = $pdo->prepare("SELECT COALESCE(SUM(amount),0) FROM restaurant_payments WHERE restaurant_order_id=:id AND status='posted'");
        $s->execute([':id'=>$orderId]);
        return round((float)$s->fetchColumn(), 2);
    }
}
if (!function_exists('cashier_recalc_order')) {
    function cashier_recalc_order(PDO $pdo, int $orderId): void {
        $s = $pdo->prepare("SELECT COALESCE(SUM(line_total),0) AS sub, COALESCE(SUM(tax_amount),0) AS tax FROM restaurant_order_items WHERE restaurant_order_id=:id AND status='active'");
        $s->execute([':id'=>$orderId]);
        $r = $s->fetch(PDO::FETCH_ASSOC) ?: [];
        $sub = round((float)($r['sub'] ?? 0), 2);
        $tax = round((float)($r['tax'] ?? 0), 2);
        $total = round($sub + $tax, 2);
        $paid = cashier_order_total_paid($pdo, $orderId);
        $status = $paid <= 0 ? 'unpaid' : (($paid + 0.0001 >= $total) ? 'paid' : 'part_paid');

        $pdo->prepare("UPDATE restaurant_orders SET subtotal=:s,tax_total=:t,total_amount=:g,payment_status=IF(payment_status='room_charged','room_charged',:ps),updated_at=NOW() WHERE id=:id")
            ->execute([':s'=>$sub, ':t'=>$tax, ':g'=>$total, ':ps'=>$status, ':id'=>$orderId]);
    }
}
if (!function_exists('cashier_close_if_paid')) {
    function cashier_close_if_paid(PDO $pdo, int $orderId): void {
        cashier_recalc_order($pdo, $orderId);
        $s = $pdo->prepare("SELECT table_id, total_amount, payment_status FROM restaurant_orders WHERE id=:id LIMIT 1");
        $s->execute([':id'=>$orderId]);
        $o = $s->fetch(PDO::FETCH_ASSOC);
        if (!$o) return;
        $paid = cashier_order_total_paid($pdo, $orderId);
        if ($paid + 0.0001 >= (float)$o['total_amount']) {
            $pdo->prepare("UPDATE restaurant_orders SET status='closed', closed_by=:u, closed_at=NOW(), payment_status='paid' WHERE id=:id")
                ->execute([':u'=>cashier_current_user_id(), ':id'=>$orderId]);
            if (!empty($o['table_id'])) {
                $pdo->prepare("UPDATE restaurant_tables SET status='available' WHERE id=:id")
                    ->execute([':id'=>(int)$o['table_id']]);
            }
        }
    }
}

$errors = [];

try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS restaurant_payments (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        restaurant_order_id BIGINT UNSIGNED NOT NULL,
        payment_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        payment_method VARCHAR(60) NOT NULL,
        amount DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        bank_account_id INT UNSIGNED NULL,
        pos_machine_id INT UNSIGNED NULL,
        reference_no VARCHAR(120) NULL,
        created_by INT UNSIGNED NULL,
        status ENUM('posted','void') NOT NULL DEFAULT 'posted',
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        INDEX idx_rest_payment_order(restaurant_order_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    if (!cashier_column_exists($pdo, 'restaurant_payments', 'split_group')) {
        try { $pdo->exec("ALTER TABLE restaurant_payments ADD COLUMN split_group VARCHAR(80) NULL AFTER reference_no"); } catch (Throwable $e) {}
    }
    if (!cashier_column_exists($pdo, 'restaurant_payments', 'split_type')) {
        try { $pdo->exec("ALTER TABLE restaurant_payments ADD COLUMN split_type VARCHAR(30) NULL AFTER split_group"); } catch (Throwable $e) {}
    }
    if (!cashier_column_exists($pdo, 'restaurant_payments', 'payer_name')) {
        try { $pdo->exec("ALTER TABLE restaurant_payments ADD COLUMN payer_name VARCHAR(180) NULL AFTER split_type"); } catch (Throwable $e) {}
    }

    $pdo->exec("CREATE TABLE IF NOT EXISTS restaurant_bill_splits (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        restaurant_order_id BIGINT UNSIGNED NOT NULL,
        split_no VARCHAR(80) NOT NULL,
        split_type ENUM('equal','item','custom') NOT NULL DEFAULT 'custom',
        payer_name VARCHAR(180) NULL,
        amount DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        percent_value DECIMAL(8,4) NULL,
        item_ids TEXT NULL,
        notes TEXT NULL,
        status ENUM('open','paid','void') NOT NULL DEFAULT 'open',
        created_by INT UNSIGNED NULL,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        INDEX idx_rest_bill_split_order(restaurant_order_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
} catch (Throwable $e) {
    $errors[] = $e->getMessage();
}

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

        if ($action === 'post_payment') {
            $orderId = (int)($_POST['restaurant_order_id'] ?? 0);
            $method = trim((string)($_POST['payment_method'] ?? ''));
            $amount = round((float)($_POST['amount'] ?? 0), 2);
            $reference = trim((string)($_POST['reference_no'] ?? '')) ?: null;
            $payerName = trim((string)($_POST['payer_name'] ?? '')) ?: null;
            $splitType = trim((string)($_POST['split_type'] ?? 'direct')) ?: 'direct';
            $splitGroup = trim((string)($_POST['split_group'] ?? '')) ?: null;

            if ($orderId <= 0) throw new RuntimeException('Invalid restaurant order.');
            if ($method === '') throw new RuntimeException('Select payment method.');
            if ($amount <= 0) throw new RuntimeException('Payment amount must be greater than zero.');

            cashier_recalc_order($pdo, $orderId);
            $pdo->prepare("INSERT INTO restaurant_payments(restaurant_order_id,payment_method,amount,reference_no,split_group,split_type,payer_name,created_by) VALUES(:rid,:m,:a,:r,:sg,:st,:payer,:u)")
                ->execute([
                    ':rid'=>$orderId, ':m'=>$method, ':a'=>$amount, ':r'=>$reference,
                    ':sg'=>$splitGroup, ':st'=>$splitType, ':payer'=>$payerName, ':u'=>cashier_current_user_id()
                ]);
            cashier_close_if_paid($pdo, $orderId);
            cashier_flash('success', 'Payment posted successfully.');
            header('Location: cashier.php?restaurant_order_id=' . $orderId);
            exit;
        }

        if ($action === 'post_multiple_payments') {
            $orderId = (int)($_POST['restaurant_order_id'] ?? 0);
            if ($orderId <= 0) throw new RuntimeException('Invalid restaurant order.');
            $methods = $_POST['payment_method'] ?? [];
            $amounts = $_POST['amount'] ?? [];
            $refs = $_POST['reference_no'] ?? [];
            $payers = $_POST['payer_name'] ?? [];
            if (!is_array($methods) || !is_array($amounts)) throw new RuntimeException('Invalid payment lines.');

            $splitGroup = 'MIX-' . date('YmdHis') . '-' . $orderId;
            $posted = 0;
            $pdo->beginTransaction();
            foreach ($amounts as $i => $rawAmount) {
                $amount = round((float)$rawAmount, 2);
                $method = trim((string)($methods[$i] ?? ''));
                if ($amount <= 0 && $method === '') continue;
                if ($amount <= 0 || $method === '') throw new RuntimeException('Each payment line needs method and amount.');
                $pdo->prepare("INSERT INTO restaurant_payments(restaurant_order_id,payment_method,amount,reference_no,split_group,split_type,payer_name,created_by) VALUES(:rid,:m,:a,:r,:sg,'mixed',:payer,:u)")
                    ->execute([
                        ':rid'=>$orderId, ':m'=>$method, ':a'=>$amount,
                        ':r'=>trim((string)($refs[$i] ?? '')) ?: null,
                        ':sg'=>$splitGroup,
                        ':payer'=>trim((string)($payers[$i] ?? '')) ?: null,
                        ':u'=>cashier_current_user_id()
                    ]);
                $posted++;
            }
            if ($posted <= 0) throw new RuntimeException('No valid payment lines were entered.');
            $pdo->commit();
            cashier_close_if_paid($pdo, $orderId);
            cashier_flash('success', $posted . ' payment line(s) posted.');
            header('Location: cashier.php?restaurant_order_id=' . $orderId);
            exit;
        }

        if ($action === 'save_equal_split') {
            $orderId = (int)($_POST['restaurant_order_id'] ?? 0);
            $parts = max(1, (int)($_POST['parts'] ?? 1));
            if ($orderId <= 0) throw new RuntimeException('Invalid order.');
            cashier_recalc_order($pdo, $orderId);
            $s = $pdo->prepare("SELECT total_amount FROM restaurant_orders WHERE id=:id LIMIT 1");
            $s->execute([':id'=>$orderId]);
            $total = round((float)$s->fetchColumn(), 2);
            if ($total <= 0) throw new RuntimeException('Order has no balance to split.');

            $splitNo = 'EQ-' . date('YmdHis') . '-' . $orderId;
            $each = floor(($total / $parts) * 100) / 100;
            $running = 0.0;
            $pdo->beginTransaction();
            $pdo->prepare("UPDATE restaurant_bill_splits SET status='void' WHERE restaurant_order_id=:id AND status='open'")->execute([':id'=>$orderId]);
            for ($i=1; $i <= $parts; $i++) {
                $amount = ($i === $parts) ? round($total - $running, 2) : round($each, 2);
                $running += $amount;
                $pdo->prepare("INSERT INTO restaurant_bill_splits(restaurant_order_id,split_no,split_type,payer_name,amount,percent_value,created_by) VALUES(:rid,:no,'equal',:payer,:amt,:pct,:u)")
                    ->execute([
                        ':rid'=>$orderId, ':no'=>$splitNo, ':payer'=>'Guest ' . $i,
                        ':amt'=>$amount, ':pct'=>round(100/$parts,4), ':u'=>cashier_current_user_id()
                    ]);
            }
            $pdo->commit();
            cashier_flash('success', 'Equal bill split created.');
            header('Location: cashier.php?restaurant_order_id=' . $orderId);
            exit;
        }

        if ($action === 'save_custom_split') {
            $orderId = (int)($_POST['restaurant_order_id'] ?? 0);
            if ($orderId <= 0) throw new RuntimeException('Invalid order.');
            $payerNames = $_POST['custom_payer_name'] ?? [];
            $amounts = $_POST['custom_amount'] ?? [];
            $percents = $_POST['custom_percent'] ?? [];
            if (!is_array($payerNames)) $payerNames = [];
            $splitNo = 'CU-' . date('YmdHis') . '-' . $orderId;
            cashier_recalc_order($pdo, $orderId);
            $s = $pdo->prepare("SELECT total_amount FROM restaurant_orders WHERE id=:id LIMIT 1");
            $s->execute([':id'=>$orderId]);
            $total = round((float)$s->fetchColumn(), 2);
            if ($total <= 0) throw new RuntimeException('Order has no balance to split.');

            $pdo->beginTransaction();
            $pdo->prepare("UPDATE restaurant_bill_splits SET status='void' WHERE restaurant_order_id=:id AND status='open'")->execute([':id'=>$orderId]);
            $sum = 0.0;
            $count = 0;
            foreach ($payerNames as $i => $payer) {
                $payer = trim((string)$payer) ?: ('Guest ' . ($i + 1));
                $amount = round((float)($amounts[$i] ?? 0), 2);
                $percent = round((float)($percents[$i] ?? 0), 4);
                if ($amount <= 0 && $percent > 0) $amount = round($total * ($percent / 100), 2);
                if ($amount <= 0) continue;
                $sum += $amount;
                $count++;
                $pdo->prepare("INSERT INTO restaurant_bill_splits(restaurant_order_id,split_no,split_type,payer_name,amount,percent_value,created_by) VALUES(:rid,:no,'custom',:payer,:amt,:pct,:u)")
                    ->execute([':rid'=>$orderId, ':no'=>$splitNo, ':payer'=>$payer, ':amt'=>$amount, ':pct'=>$percent ?: null, ':u'=>cashier_current_user_id()]);
            }
            if ($count <= 0) throw new RuntimeException('Enter at least one custom split line.');
            if (abs($sum - $total) > 0.05) throw new RuntimeException('Custom split total ' . money_fmt($sum) . ' must equal bill total ' . money_fmt($total) . '.');
            $pdo->commit();
            cashier_flash('success', 'Custom bill split saved.');
            header('Location: cashier.php?restaurant_order_id=' . $orderId);
            exit;
        }

        if ($action === 'save_item_split') {
            $orderId = (int)($_POST['restaurant_order_id'] ?? 0);
            $payerName = trim((string)($_POST['item_payer_name'] ?? '')) ?: 'Guest';
            $itemIds = $_POST['item_ids'] ?? [];
            if (!is_array($itemIds)) $itemIds = [$itemIds];
            $clean = [];
            foreach ($itemIds as $id) { $id = (int)$id; if ($id > 0) $clean[$id] = $id; }
            if ($orderId <= 0) throw new RuntimeException('Invalid order.');
            if (!$clean) throw new RuntimeException('Select at least one item for this payer.');
            $in = implode(',', array_fill(0, count($clean), '?'));
            $params = array_values($clean);
            array_unshift($params, $orderId);
            $s = $pdo->prepare("SELECT COALESCE(SUM(line_total + tax_amount),0) FROM restaurant_order_items WHERE restaurant_order_id=? AND id IN ($in) AND status='active'");
            $s->execute($params);
            $amount = round((float)$s->fetchColumn(), 2);
            if ($amount <= 0) throw new RuntimeException('Selected items have no value.');
            $splitNo = 'IT-' . date('YmdHis') . '-' . $orderId;
            $pdo->prepare("INSERT INTO restaurant_bill_splits(restaurant_order_id,split_no,split_type,payer_name,amount,item_ids,created_by) VALUES(:rid,:no,'item',:payer,:amt,:items,:u)")
                ->execute([':rid'=>$orderId, ':no'=>$splitNo, ':payer'=>$payerName, ':amt'=>$amount, ':items'=>implode(',', array_values($clean)), ':u'=>cashier_current_user_id()]);
            cashier_flash('success', 'Item split saved for ' . $payerName . '.');
            header('Location: cashier.php?restaurant_order_id=' . $orderId);
            exit;
        }

    } catch (Throwable $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        cashier_flash('danger', $e->getMessage());
        header('Location: cashier.php' . (!empty($_POST['restaurant_order_id']) ? '?restaurant_order_id=' . (int)$_POST['restaurant_order_id'] : ''));
        exit;
    }
}

$selectedOrderId = (int)($_GET['restaurant_order_id'] ?? 0);
$orders = [];
$order = null;
$orderItems = [];
$payments = [];
$splits = [];
$error = '';

try {
    $stmt = $pdo->query("
        SELECT
            ro.*,
            rt.table_no,
            rt.table_name,
            rt.seats,
            CASE
                WHEN COALESCE(ro.merged_table_ids,'') <> '' THEN ro.merged_table_ids
                ELSE CAST(ro.table_id AS CHAR)
            END AS table_group
        FROM restaurant_orders ro
        LEFT JOIN restaurant_tables rt ON rt.id = ro.table_id
        WHERE ro.status IN ('open','preparing','served','bill_requested','sent')
        ORDER BY ro.created_at ASC, ro.id ASC
    ");
    $orders = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if ($selectedOrderId <= 0 && $orders) {
        $selectedOrderId = (int)$orders[0]['id'];
    }

    if ($selectedOrderId > 0) {
        $s = $pdo->prepare("SELECT ro.*, rt.table_no, rt.table_name FROM restaurant_orders ro LEFT JOIN restaurant_tables rt ON rt.id=ro.table_id WHERE ro.id=:id LIMIT 1");
        $s->execute([':id'=>$selectedOrderId]);
        $order = $s->fetch(PDO::FETCH_ASSOC) ?: null;

        if ($order) {
            cashier_recalc_order($pdo, $selectedOrderId);
            $s->execute([':id'=>$selectedOrderId]);
            $order = $s->fetch(PDO::FETCH_ASSOC) ?: $order;

            $i = $pdo->prepare("SELECT * FROM restaurant_order_items WHERE restaurant_order_id=:id ORDER BY status ASC, id ASC");
            $i->execute([':id'=>$selectedOrderId]);
            $orderItems = $i->fetchAll(PDO::FETCH_ASSOC) ?: [];

            $p = $pdo->prepare("SELECT * FROM restaurant_payments WHERE restaurant_order_id=:id ORDER BY id ASC");
            $p->execute([':id'=>$selectedOrderId]);
            $payments = $p->fetchAll(PDO::FETCH_ASSOC) ?: [];

            $sp = $pdo->prepare("SELECT * FROM restaurant_bill_splits WHERE restaurant_order_id=:id AND status <> 'void' ORDER BY id ASC");
            $sp->execute([':id'=>$selectedOrderId]);
            $splits = $sp->fetchAll(PDO::FETCH_ASSOC) ?: [];
        }
    }
} catch (Throwable $e) {
    $error = $e->getMessage();
}

$flashes = cashier_get_flash();
$total = $order ? (float)($order['total_amount'] ?? 0) : 0;
$paid = $order ? cashier_order_total_paid($pdo, (int)$order['id']) : 0;
$balance = max(0, round($total - $paid, 2));
$isWalkin = $order && strtolower((string)($order['order_type'] ?? '')) === 'walkin';

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

<div class="hero-band cashier-hero">
    <div class="d-flex justify-content-between align-items-center flex-wrap gap-2">
        <div>
            <div class="page-eyebrow text-white-50"><i class="bi bi-cash-register"></i> Restaurant</div>
            <div class="hero-title mt-1">Cashier / Bill Sharing</div>
            <div class="hero-subtitle mt-1">Close orders with equal, item, custom and mixed-method payments.</div>
        </div>
        <div class="d-flex gap-2 flex-wrap">
            <a class="btn btn-light btn-sm" href="planner.php">Table Planner</a>
            <?php if ($order): ?><a class="btn btn-outline-light btn-sm" href="order_view.php?id=<?php echo (int)$order['id']; ?>">View Order</a><?php endif; ?>
        </div>
    </div>
</div>

<?php foreach ($flashes as $f): ?><div class="alert alert-<?php echo h($f['type']); ?> py-2"><?php echo h($f['message']); ?></div><?php endforeach; ?>
<?php if ($error): ?><div class="alert alert-danger">Could not load open orders: <?php echo h($error); ?></div><?php endif; ?>
<?php foreach ($errors as $err): ?><div class="alert alert-danger py-2"><?php echo h($err); ?></div><?php endforeach; ?>

<div class="row g-3">
    <div class="col-xl-4">
        <div class="card panel-card mb-3">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Open Orders</h5>
                <span class="badge text-bg-light border"><?php echo count($orders); ?></span>
            </div>
            <div class="card-body p-0 open-orders-list">
                <?php if (!$orders): ?>
                    <div class="text-center text-muted py-5">No open restaurant tables/orders to close.</div>
                <?php else: foreach ($orders as $o): ?>
                    <?php $active = ((int)$o['id'] === $selectedOrderId); ?>
                    <a class="order-list-item <?php echo $active ? 'active' : ''; ?>" href="cashier.php?restaurant_order_id=<?php echo (int)$o['id']; ?>">
                        <div>
                            <strong><?php echo h($o['order_no'] ?: '#'.$o['id']); ?></strong>
                            <span><?php echo h(($o['order_type'] ?? '') === 'walkin' ? 'Walk-in' : ('Table ' . ($o['table_no'] ?: '-'))); ?></span>
                            <?php if (!empty($o['guest_name'])): ?><small><?php echo h($o['guest_name']); ?><?php echo !empty($o['room_no']) && ($o['order_type'] ?? '') !== 'walkin' ? ' • Room ' . h($o['room_no']) : ''; ?></small><?php endif; ?>
                        </div>
                        <div class="text-end">
                            <strong><?php echo money_fmt($o['total_amount'] ?? 0); ?></strong>
                            <small><?php echo h(str_replace('_',' ', (string)$o['status'])); ?></small>
                        </div>
                    </a>
                <?php endforeach; endif; ?>
            </div>
        </div>
    </div>

    <div class="col-xl-8">
        <?php if (!$order): ?>
            <div class="alert alert-info">Select an open order to close.</div>
        <?php else: ?>
            <div class="card panel-card mb-3">
                <div class="card-body">
                    <div class="d-flex justify-content-between flex-wrap gap-2">
                        <div>
                            <div class="small text-muted">Order</div>
                            <h4 class="mb-1"><?php echo h($order['order_no'] ?: '#'.$order['id']); ?></h4>
                            <div class="text-muted">
                                <?php echo $isWalkin ? 'Direct Walk-in' : 'Table ' . h($order['table_no'] ?: '-'); ?>
                                <?php echo !empty($order['guest_name']) ? ' • ' . h($order['guest_name']) : ''; ?>
                                <?php echo (!$isWalkin && !empty($order['room_no'])) ? ' • Room ' . h($order['room_no']) : ''; ?>
                            </div>
                        </div>
                        <div class="bill-summary-grid">
                            <div><span>Total</span><strong><?php echo money_fmt($total); ?></strong></div>
                            <div><span>Paid</span><strong><?php echo money_fmt($paid); ?></strong></div>
                            <div><span>Balance</span><strong><?php echo money_fmt($balance); ?></strong></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="row g-3">
                <div class="col-lg-6">
                    <div class="card panel-card h-100">
                        <div class="card-header"><h5 class="mb-0">Order Items</h5></div>
                        <div class="card-body p-0 order-items-wrap">
                            <table class="table table-sm table-modern mb-0 align-middle">
                                <thead><tr><th>Item</th><th class="text-end">Qty</th><th class="text-end">Amount</th></tr></thead>
                                <tbody>
                                <?php foreach ($orderItems as $it): ?>
                                    <tr class="<?php echo ($it['status'] ?? '') === 'void' ? 'text-muted text-decoration-line-through' : ''; ?>">
                                        <td><strong><?php echo h($it['item_name']); ?></strong><div class="small text-muted"><?php echo h($it['printer_role'] ?? ''); ?></div></td>
                                        <td class="text-end"><?php echo h($it['qty']); ?></td>
                                        <td class="text-end"><?php echo money_fmt((float)$it['line_total'] + (float)$it['tax_amount']); ?></td>
                                    </tr>
                                <?php endforeach; ?>
                                <?php if (!$orderItems): ?><tr><td colspan="3" class="text-center text-muted py-4">No items.</td></tr><?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <div class="col-lg-6">
                    <div class="card panel-card h-100">
                        <div class="card-header"><h5 class="mb-0">Payments Posted</h5></div>
                        <div class="card-body p-0 order-items-wrap">
                            <table class="table table-sm table-modern mb-0 align-middle">
                                <thead><tr><th>Method</th><th>Payer</th><th class="text-end">Amount</th></tr></thead>
                                <tbody>
                                <?php foreach ($payments as $p): ?>
                                    <tr class="<?php echo ($p['status'] ?? '') === 'void' ? 'text-muted text-decoration-line-through' : ''; ?>">
                                        <td><strong><?php echo h($p['payment_method']); ?></strong><div class="small text-muted"><?php echo h($p['reference_no'] ?? ''); ?></div></td>
                                        <td><?php echo h($p['payer_name'] ?? ''); ?><div class="small text-muted"><?php echo h($p['split_type'] ?? ''); ?></div></td>
                                        <td class="text-end"><?php echo money_fmt($p['amount']); ?></td>
                                    </tr>
                                <?php endforeach; ?>
                                <?php if (!$payments): ?><tr><td colspan="3" class="text-center text-muted py-4">No payments posted.</td></tr><?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <div class="card panel-card mt-3">
                <div class="card-header d-flex justify-content-between align-items-center flex-wrap gap-2">
                    <h5 class="mb-0">Close / Split Bill</h5>
                    <div class="small text-muted">Direct room posting is not shown here. Use planner/order room-folio workflow for lodge guests.</div>
                </div>
                <div class="card-body">
                    <ul class="nav nav-pills gap-2 mb-3" role="tablist">
                        <li class="nav-item"><button class="nav-link active" data-bs-toggle="pill" data-bs-target="#tabSingle" type="button">Single Payment</button></li>
                        <li class="nav-item"><button class="nav-link" data-bs-toggle="pill" data-bs-target="#tabMixed" type="button">Multiple Methods</button></li>
                        <li class="nav-item"><button class="nav-link" data-bs-toggle="pill" data-bs-target="#tabEqual" type="button">Split Equal</button></li>
                        <li class="nav-item"><button class="nav-link" data-bs-toggle="pill" data-bs-target="#tabItems" type="button">Split Items</button></li>
                        <li class="nav-item"><button class="nav-link" data-bs-toggle="pill" data-bs-target="#tabCustom" type="button">Custom Split</button></li>
                    </ul>

                    <div class="tab-content">
                        <div class="tab-pane fade show active" id="tabSingle">
                            <form method="post" class="row g-2 align-items-end">
                                <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                                <input type="hidden" name="action" value="post_payment">
                                <input type="hidden" name="restaurant_order_id" value="<?php echo (int)$order['id']; ?>">
                                <input type="hidden" name="split_type" value="direct">
                                <div class="col-md-3"><label class="form-label">Payer</label><input name="payer_name" class="form-control" placeholder="Optional"></div>
                                <div class="col-md-3"><label class="form-label">Method</label><select name="payment_method" class="form-select" required><option>Cash</option><option>Card</option><option>POS</option><option>Mobile Money</option><option>Bank Transfer</option></select></div>
                                <div class="col-md-3"><label class="form-label">Amount</label><input type="number" step="0.01" name="amount" class="form-control" value="<?php echo h($balance ?: $total); ?>" required></div>
                                <div class="col-md-3"><label class="form-label">Reference</label><input name="reference_no" class="form-control"></div>
                                <div class="col-12 d-grid"><button class="btn btn-success">Post Payment</button></div>
                            </form>
                        </div>

                        <div class="tab-pane fade" id="tabMixed">
                            <form method="post" id="mixedPaymentForm">
                                <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                                <input type="hidden" name="action" value="post_multiple_payments">
                                <input type="hidden" name="restaurant_order_id" value="<?php echo (int)$order['id']; ?>">
                                <div id="mixedPaymentRows" class="vstack gap-2"></div>
                                <div class="d-flex justify-content-between align-items-center mt-2 flex-wrap gap-2">
                                    <button type="button" class="btn btn-outline-primary btn-sm" id="addMixedRow">Add Payment Line</button>
                                    <div class="fw-bold">Entered: <span id="mixedTotal">0.00</span> / Due <?php echo money_fmt($balance ?: $total); ?></div>
                                </div>
                                <button class="btn btn-success w-100 mt-3">Post Multiple Payments</button>
                            </form>
                        </div>

                        <div class="tab-pane fade" id="tabEqual">
                            <form method="post" class="row g-2 align-items-end">
                                <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                                <input type="hidden" name="action" value="save_equal_split">
                                <input type="hidden" name="restaurant_order_id" value="<?php echo (int)$order['id']; ?>">
                                <div class="col-md-4"><label class="form-label">Number of diners</label><input type="number" min="2" name="parts" id="equalParts" value="2" class="form-control"></div>
                                <div class="col-md-4"><label class="form-label">Each pays</label><input type="text" id="equalEach" class="form-control" readonly></div>
                                <div class="col-md-4 d-grid"><button class="btn btn-primary">Create Equal Split</button></div>
                            </form>
                        </div>

                        <div class="tab-pane fade" id="tabItems">
                            <form method="post">
                                <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                                <input type="hidden" name="action" value="save_item_split">
                                <input type="hidden" name="restaurant_order_id" value="<?php echo (int)$order['id']; ?>">
                                <div class="row g-2 mb-2">
                                    <div class="col-md-6"><label class="form-label">Payer Name</label><input name="item_payer_name" class="form-control" placeholder="e.g. Guest 1"></div>
                                    <div class="col-md-6"><label class="form-label">Selected Total</label><input id="itemSplitTotal" class="form-control" readonly></div>
                                </div>
                                <div class="item-select-list">
                                    <?php foreach ($orderItems as $it): if (($it['status'] ?? '') !== 'active') continue; $amt = (float)$it['line_total'] + (float)$it['tax_amount']; ?>
                                        <label class="item-check-row">
                                            <input type="checkbox" name="item_ids[]" value="<?php echo (int)$it['id']; ?>" data-amount="<?php echo h($amt); ?>">
                                            <span><?php echo h($it['qty'] . ' x ' . $it['item_name']); ?></span>
                                            <strong><?php echo money_fmt($amt); ?></strong>
                                        </label>
                                    <?php endforeach; ?>
                                </div>
                                <button class="btn btn-primary w-100 mt-3">Save Item Split</button>
                            </form>
                        </div>

                        <div class="tab-pane fade" id="tabCustom">
                            <form method="post" id="customSplitForm">
                                <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                                <input type="hidden" name="action" value="save_custom_split">
                                <input type="hidden" name="restaurant_order_id" value="<?php echo (int)$order['id']; ?>">
                                <div id="customSplitRows" class="vstack gap-2"></div>
                                <div class="d-flex justify-content-between align-items-center mt-2 flex-wrap gap-2">
                                    <button type="button" class="btn btn-outline-primary btn-sm" id="addCustomRow">Add Split Line</button>
                                    <div class="fw-bold">Split Total: <span id="customSplitTotal">0.00</span> / Bill <?php echo money_fmt($total); ?></div>
                                </div>
                                <button class="btn btn-primary w-100 mt-3">Save Custom Split</button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>

            <?php if ($splits): ?>
                <div class="card panel-card mt-3">
                    <div class="card-header"><h5 class="mb-0">Saved Splits</h5></div>
                    <div class="card-body p-0">
                        <table class="table table-sm table-modern mb-0">
                            <thead><tr><th>Type</th><th>Payer</th><th>Split No</th><th class="text-end">Amount</th></tr></thead>
                            <tbody>
                                <?php foreach ($splits as $sp): ?>
                                    <tr><td><?php echo h($sp['split_type']); ?></td><td><?php echo h($sp['payer_name']); ?></td><td><?php echo h($sp['split_no']); ?></td><td class="text-end"><?php echo money_fmt($sp['amount']); ?></td></tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            <?php endif; ?>
        <?php endif; ?>
    </div>
</div>

<style>
.cashier-hero{padding:12px 16px!important;margin-bottom:10px!important}.panel-card{border-radius:16px;box-shadow:0 12px 30px rgba(15,23,42,.07)}.open-orders-list{max-height:calc(100vh - 220px);overflow:auto}.order-list-item{display:flex;justify-content:space-between;gap:10px;padding:12px 14px;border-bottom:1px solid #eef2f7;text-decoration:none;color:#0f172a}.order-list-item:hover,.order-list-item.active{background:#eff6ff}.order-list-item span,.order-list-item small{display:block;color:#64748b}.bill-summary-grid{display:grid;grid-template-columns:repeat(3,minmax(90px,1fr));gap:8px}.bill-summary-grid div{border:1px solid #e5e7eb;border-radius:12px;padding:8px 12px;background:#f8fafc;text-align:right}.bill-summary-grid span{display:block;font-size:.72rem;color:#64748b;text-transform:uppercase;font-weight:800}.bill-summary-grid strong{font-size:1.15rem}.table-modern thead th{font-size:.72rem;text-transform:uppercase;color:#64748b;background:#f8fafc;white-space:nowrap}.table-modern td,.table-modern th{font-size:.85rem;padding:.55rem .65rem;border-bottom:1px solid #eef2f7}.order-items-wrap{max-height:270px;overflow:auto}.item-select-list{border:1px solid #e5e7eb;border-radius:12px;overflow:hidden;max-height:260px;overflow:auto}.item-check-row{display:grid;grid-template-columns:28px 1fr 90px;gap:8px;align-items:center;padding:9px 12px;border-bottom:1px solid #eef2f7;margin:0}.item-check-row:last-child{border-bottom:0}.split-row{display:grid;grid-template-columns:1fr 150px 150px 42px;gap:8px}.mixed-row{display:grid;grid-template-columns:1fr 140px 130px 1fr 42px;gap:8px}@media(max-width:768px){.split-row,.mixed-row{grid-template-columns:1fr}.bill-summary-grid{grid-template-columns:1fr}}
</style>

<script>
document.addEventListener('DOMContentLoaded', function(){
    const billTotal = <?php echo json_encode(round($total, 2)); ?>;
    const billBalance = <?php echo json_encode(round($balance ?: $total, 2)); ?>;

    const equalParts = document.getElementById('equalParts');
    const equalEach = document.getElementById('equalEach');
    function updateEqual(){
        if(!equalParts || !equalEach) return;
        const n = Math.max(1, parseInt(equalParts.value || '1', 10));
        equalEach.value = (billTotal / n).toFixed(2);
    }
    if(equalParts) equalParts.addEventListener('input', updateEqual);
    updateEqual();

    const itemSplitTotal = document.getElementById('itemSplitTotal');
    function updateItemTotal(){
        let total = 0;
        document.querySelectorAll('input[name="item_ids[]"]:checked').forEach(cb => total += parseFloat(cb.dataset.amount || '0') || 0);
        if(itemSplitTotal) itemSplitTotal.value = total.toFixed(2);
    }
    document.querySelectorAll('input[name="item_ids[]"]').forEach(cb => cb.addEventListener('change', updateItemTotal));
    updateItemTotal();

    const customRows = document.getElementById('customSplitRows');
    const addCustom = document.getElementById('addCustomRow');
    const customTotal = document.getElementById('customSplitTotal');
    function recalcCustom(){
        let total = 0;
        if(customRows){
            customRows.querySelectorAll('input[name="custom_amount[]"]').forEach(inp => total += parseFloat(inp.value || '0') || 0);
        }
        if(customTotal) customTotal.textContent = total.toFixed(2);
    }
    function addCustomRow(name='', amount='', percent=''){
        if(!customRows) return;
        const div = document.createElement('div');
        div.className = 'split-row';
        div.innerHTML = `<input name="custom_payer_name[]" class="form-control" placeholder="Payer" value="${name}">
            <input type="number" step="0.01" name="custom_amount[]" class="form-control" placeholder="Amount" value="${amount}">
            <input type="number" step="0.0001" name="custom_percent[]" class="form-control" placeholder="% Optional" value="${percent}">
            <button type="button" class="btn btn-outline-danger remove-row">×</button>`;
        customRows.appendChild(div);
        div.querySelectorAll('input').forEach(i => i.addEventListener('input', recalcCustom));
        div.querySelector('.remove-row').addEventListener('click', () => { div.remove(); recalcCustom(); });
        recalcCustom();
    }
    if(addCustom) addCustom.addEventListener('click', () => addCustomRow());
    if(customRows && !customRows.children.length){ addCustomRow('Guest 1', (billTotal/2).toFixed(2), '50'); addCustomRow('Guest 2', (billTotal/2).toFixed(2), '50'); }

    const mixedRows = document.getElementById('mixedPaymentRows');
    const addMixed = document.getElementById('addMixedRow');
    const mixedTotal = document.getElementById('mixedTotal');
    function recalcMixed(){
        let total = 0;
        if(mixedRows){ mixedRows.querySelectorAll('input[name="amount[]"]').forEach(inp => total += parseFloat(inp.value || '0') || 0); }
        if(mixedTotal) mixedTotal.textContent = total.toFixed(2);
    }
    function addMixedRow(method='Cash', amount='', payer=''){
        if(!mixedRows) return;
        const div = document.createElement('div');
        div.className = 'mixed-row';
        div.innerHTML = `<input name="payer_name[]" class="form-control" placeholder="Payer" value="${payer}">
            <select name="payment_method[]" class="form-select"><option${method==='Cash'?' selected':''}>Cash</option><option${method==='Card'?' selected':''}>Card</option><option${method==='POS'?' selected':''}>POS</option><option${method==='Mobile Money'?' selected':''}>Mobile Money</option><option${method==='Bank Transfer'?' selected':''}>Bank Transfer</option></select>
            <input type="number" step="0.01" name="amount[]" class="form-control" placeholder="Amount" value="${amount}">
            <input name="reference_no[]" class="form-control" placeholder="Reference">
            <button type="button" class="btn btn-outline-danger remove-row">×</button>`;
        mixedRows.appendChild(div);
        div.querySelectorAll('input').forEach(i => i.addEventListener('input', recalcMixed));
        div.querySelector('.remove-row').addEventListener('click', () => { div.remove(); recalcMixed(); });
        recalcMixed();
    }
    if(addMixed) addMixed.addEventListener('click', () => addMixedRow());
    if(mixedRows && !mixedRows.children.length){ addMixedRow('Cash', billBalance.toFixed(2), ''); }
});
</script>

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