<?php
/**
 * restaurant_split_reprint.php
 * Put this file in: /rooms/modules/reservations/
 *
 * Purpose:
 * - View CLOSED restaurant orders that were split/posted to room/guest/master folios.
 * - Show each split destination and item allocation where available.
 * - Reprint one split bill or all split bills WITHOUT posting to PMS again.
 *
 * It only creates restaurant_print_jobs and dispatches them to PrintNode.
 * It does NOT insert folio_transactions and does NOT settle/pay/post anything.
 */

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

$pageTitle = 'Restaurant Split Bill Reprint';

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('rsr_flash')) {
    function rsr_flash(string $type, string $message): void {
        $_SESSION['restaurant_split_reprint_flash'][] = ['type' => $type, 'message' => $message];
    }
    function rsr_get_flash(): array {
        $x = $_SESSION['restaurant_split_reprint_flash'] ?? [];
        unset($_SESSION['restaurant_split_reprint_flash']);
        return $x;
    }
}

function rsr_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;
}
function rsr_current_user_name(): string {
    foreach (['currentUserName','current_user_name','user_name','username','full_name','name'] as $k) {
        if (isset($_SESSION[$k]) && trim((string)$_SESSION[$k]) !== '') return trim((string)$_SESSION[$k]);
    }
    return 'Logged cashier';
}
function rsr_table_exists(PDO $pdo, string $table): bool {
    static $cache = [];
    $key = strtolower($table);
    if (array_key_exists($key, $cache)) return $cache[$key];
    try {
        $s = $pdo->prepare("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = :t");
        $s->execute([':t' => $table]);
        return $cache[$key] = ((int)$s->fetchColumn() > 0);
    } catch (Throwable $e) { return $cache[$key] = false; }
}
function rsr_column_exists(PDO $pdo, string $table, string $column): bool {
    static $cache = [];
    $key = strtolower($table . '.' . $column);
    if (array_key_exists($key, $cache)) return $cache[$key];
    try {
        $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 $cache[$key] = ((int)$s->fetchColumn() > 0);
    } catch (Throwable $e) { return $cache[$key] = false; }
}
function rsr_wrap_line(string $text, int $width = 38): array {
    $text = trim($text);
    if ($text === '') return [''];
    $lines = [];
    foreach (explode("\n", $text) as $part) {
        $part = trim($part);
        if ($part === '') { $lines[] = ''; continue; }
        $wrapped = wordwrap($part, $width, "\n", true);
        foreach (explode("\n", $wrapped) as $w) $lines[] = $w;
    }
    return $lines;
}
function rsr_center_text(string $text, int $width = 42): string {
    $out = '';
    foreach (explode("\n", trim($text)) as $line) {
        $line = trim($line);
        $pad = max(0, (int)floor(($width - strlen($line)) / 2));
        $out .= str_repeat(' ', $pad) . $line . "\n";
    }
    return $out;
}
function rsr_money_line(string $label, float $amount, int $width = 42): string {
    $amt = money_fmt($amount);
    $label = substr($label, 0, max(1, $width - strlen($amt) - 1));
    return str_pad($label, $width - strlen($amt), ' ', STR_PAD_RIGHT) . $amt . "\n";
}

function rsr_ensure_print_tables(PDO $pdo): void {
    $pdo->exec("CREATE TABLE IF NOT EXISTS restaurant_printers (
        id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        property_id INT UNSIGNED NULL,
        printer_name VARCHAR(120) NOT NULL,
        printer_role VARCHAR(60) NOT NULL,
        printnode_printer_id BIGINT UNSIGNED NULL,
        qz_printer_name VARCHAR(180) NULL,
        printer_ip VARCHAR(100) NULL,
        printer_port INT NOT NULL DEFAULT 9100,
        printer_type VARCHAR(40) NOT NULL DEFAULT 'printnode',
        is_active TINYINT(1) NOT NULL DEFAULT 1,
        sort_order INT NOT NULL DEFAULT 1,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_rest_printer_role(printer_role,is_active),
        INDEX idx_rest_printer_printnode(printnode_printer_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $pdo->exec("CREATE TABLE IF NOT EXISTS restaurant_print_jobs (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        restaurant_order_id BIGINT UNSIGNED NULL,
        printer_role VARCHAR(60) NOT NULL DEFAULT 'receipt',
        printer_id INT UNSIGNED NULL,
        job_type VARCHAR(40) NOT NULL DEFAULT 'bill',
        payload MEDIUMTEXT NULL,
        status VARCHAR(30) NOT NULL DEFAULT 'pending',
        error_message TEXT NULL,
        printed_at DATETIME NULL,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        INDEX idx_rest_print_order(restaurant_order_id),
        INDEX idx_rest_print_status(status)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    if (!rsr_column_exists($pdo, 'restaurant_print_jobs', 'printer_id')) {
        try { $pdo->exec("ALTER TABLE restaurant_print_jobs ADD COLUMN printer_id INT UNSIGNED NULL AFTER printer_role"); } catch (Throwable $e) {}
    }
    try { $pdo->exec("ALTER TABLE restaurant_print_jobs MODIFY job_type VARCHAR(40) NOT NULL DEFAULT 'bill'"); } catch (Throwable $e) {}
    try { $pdo->exec("ALTER TABLE restaurant_print_jobs MODIFY status VARCHAR(30) NOT NULL DEFAULT 'pending'"); } catch (Throwable $e) {}
}

function rsr_printnode_printer_id_for_role(PDO $pdo, string $role, ?int $printerRowId = null): int {
    rsr_ensure_print_tables($pdo);
    $role = strtolower(trim($role ?: 'receipt'));

    if ($printerRowId && $printerRowId > 0) {
        try {
            $s = $pdo->prepare("SELECT printnode_printer_id FROM restaurant_printers WHERE id = :id AND is_active = 1 LIMIT 1");
            $s->execute([':id' => $printerRowId]);
            $id = (int)$s->fetchColumn();
            if ($id > 0) return $id;
        } catch (Throwable $e) {}
    }

    foreach (array_values(array_unique([$role, 'receipt', 'bar', 'master'])) as $r) {
        try {
            $s = $pdo->prepare("SELECT printnode_printer_id FROM restaurant_printers WHERE LOWER(printer_role) = :role AND is_active = 1 AND printnode_printer_id IS NOT NULL AND printnode_printer_id > 0 ORDER BY sort_order ASC, id ASC LIMIT 1");
            $s->execute([':role' => strtolower($r)]);
            $id = (int)$s->fetchColumn();
            if ($id > 0) return $id;
        } catch (Throwable $e) {}
    }
    return 0;
}
function rsr_split_bill_print_role(PDO $pdo): string {
    if (rsr_printnode_printer_id_for_role($pdo, 'receipt') > 0) return 'receipt';
    if (rsr_printnode_printer_id_for_role($pdo, 'bar') > 0) return 'bar';
    return 'receipt';
}
function rsr_build_escpos_bytes(string $payload): string {
    // Basic ESC/POS wrapper: initialize, normal text, line feeds, cut.
    return "\x1B\x40" . $payload . "\n\n\n" . "\x1D\x56\x00";
}
function rsr_dispatch_printnode_jobs(PDO $pdo, array $jobIds): array {
    $jobIds = array_values(array_unique(array_filter(array_map('intval', $jobIds))));
    if (!$jobIds) return ['ok' => 0, 'failed' => 0, 'messages' => []];

    if (!function_exists('printnode_send_raw')) {
        $pnFile = __DIR__ . '/printnode_print.php';
        if (is_file($pnFile)) require_once $pnFile;
    }
    if (!function_exists('printnode_send_raw')) {
        throw new RuntimeException('printnode_print.php was not found in this folder, or printnode_send_raw() is missing.');
    }

    rsr_ensure_print_tables($pdo);
    $in = implode(',', array_fill(0, count($jobIds), '?'));
    $s = $pdo->prepare("SELECT * FROM restaurant_print_jobs WHERE id IN ($in) ORDER BY id ASC");
    $s->execute($jobIds);
    $jobs = $s->fetchAll(PDO::FETCH_ASSOC) ?: [];

    $ok = 0; $failed = 0; $messages = [];
    foreach ($jobs as $job) {
        $role = strtolower(trim((string)($job['printer_role'] ?? 'receipt')));
        $printerRowId = isset($job['printer_id']) ? (int)$job['printer_id'] : null;
        $printNodeId = rsr_printnode_printer_id_for_role($pdo, $role, $printerRowId);
        if ($printNodeId <= 0) {
            $failed++;
            $msg = 'No ACTIVE PrintNode Printer ID configured for role ' . $role . '.';
            $messages[] = $msg;
            try { $pdo->prepare("UPDATE restaurant_print_jobs SET status='failed', error_message=:e WHERE id=:id")->execute([':e'=>$msg, ':id'=>(int)$job['id']]); } catch (Throwable $e) {}
            continue;
        }
        $payload = (string)($job['payload'] ?? '');
        if (trim($payload) === '') {
            $failed++;
            $msg = 'Empty print payload for job #' . (int)$job['id'];
            $messages[] = $msg;
            try { $pdo->prepare("UPDATE restaurant_print_jobs SET status='failed', error_message=:e WHERE id=:id")->execute([':e'=>$msg, ':id'=>(int)$job['id']]); } catch (Throwable $e) {}
            continue;
        }
        $res = printnode_send_raw($printNodeId, rsr_build_escpos_bytes($payload), 'Restaurant Split Bill Reprint - Order ' . ($job['restaurant_order_id'] ?? ''));
        if (!empty($res['ok'])) {
            $ok++;
            try { $pdo->prepare("UPDATE restaurant_print_jobs SET status='printed', printed_at=NOW(), error_message=NULL WHERE id=:id")->execute([':id'=>(int)$job['id']]); } catch (Throwable $e) {}
        } else {
            $failed++;
            $err = (string)($res['error'] ?? 'PrintNode error');
            $messages[] = $role . ': ' . $err;
            try { $pdo->prepare("UPDATE restaurant_print_jobs SET status='failed', error_message=:e WHERE id=:id")->execute([':e'=>$err, ':id'=>(int)$job['id']]); } catch (Throwable $e) {}
        }
    }
    return ['ok' => $ok, 'failed' => $failed, 'messages' => $messages];
}

function rsr_order_row(PDO $pdo, int $orderId): array {
    $tableSelect = "ro.table_id AS table_label";
    $tableJoin = '';
    if (rsr_table_exists($pdo, 'restaurant_tables')) {
        $tableSelect = "COALESCE(rt.table_no, rt.table_name, ro.table_id) AS table_label";
        $tableJoin = " LEFT JOIN restaurant_tables rt ON rt.id = ro.table_id ";
    }
    $s = $pdo->prepare("SELECT ro.*, {$tableSelect} FROM restaurant_orders ro {$tableJoin} WHERE ro.id = :id LIMIT 1");
    $s->execute([':id' => $orderId]);
    return $s->fetch(PDO::FETCH_ASSOC) ?: [];
}
function rsr_folio_label(PDO $pdo, int $folioId): array {
    $out = ['folio_no'=>'', 'folio_name'=>'', 'room_no'=>'', 'label'=>''];
    if ($folioId <= 0 || !rsr_table_exists($pdo, 'folios')) return $out;
    try {
        $roomSelect = "'' AS room_no";
        $roomJoin = '';
        if (rsr_table_exists($pdo, 'rooms') && rsr_column_exists($pdo, 'folios', 'room_id')) {
            $roomJoin = " LEFT JOIN rooms r ON r.id = f.room_id ";
            $roomSelect = "COALESCE(r.room_no,'') AS room_no";
        } elseif (rsr_column_exists($pdo, 'folios', 'room_no')) {
            $roomSelect = "COALESCE(f.room_no,'') AS room_no";
        }
        $occ = rsr_column_exists($pdo, 'folios', 'occupant_name') ? 'f.occupant_name' : "''";
        $s = $pdo->prepare("SELECT f.folio_no, f.folio_name, {$occ} AS occupant_name, {$roomSelect} FROM folios f {$roomJoin} WHERE f.id=:id LIMIT 1");
        $s->execute([':id' => $folioId]);
        $r = $s->fetch(PDO::FETCH_ASSOC) ?: [];
        if ($r) {
            $out['folio_no'] = trim((string)($r['folio_no'] ?? ''));
            $out['folio_name'] = trim((string)($r['folio_name'] ?: ($r['occupant_name'] ?? '')));
            $out['room_no'] = trim((string)($r['room_no'] ?? ''));
            $bits = [];
            if ($out['room_no'] !== '') $bits[] = 'Room ' . $out['room_no'];
            if ($out['folio_name'] !== '') $bits[] = $out['folio_name'];
            if ($out['folio_no'] !== '') $bits[] = $out['folio_no'];
            $out['label'] = implode(' / ', array_values(array_unique($bits)));
        }
    } catch (Throwable $e) {}
    return $out;
}

function rsr_fetch_recent_orders(PDO $pdo, string $search = ''): array {
    if (!rsr_table_exists($pdo, 'restaurant_orders')) return [];
    $params = [];
    $where = " WHERE 1=1 ";
    if ($search !== '') {
        $where .= " AND (ro.id = :id_exact OR ro.order_no LIKE :q OR ro.guest_name LIKE :q OR ro.room_no LIKE :q OR ro.group_name LIKE :q) ";
        $params[':id_exact'] = ctype_digit($search) ? (int)$search : -1;
        $params[':q'] = '%' . $search . '%';
    }
    $sql = "
        SELECT
            ro.id, ro.order_no, ro.status, ro.order_type, ro.guest_name, ro.room_no, ro.group_name,
            ro.total_amount, ro.payment_status, ro.closed_at, ro.opened_at,
            COUNT(DISTINCT s.id) AS split_count,
            COALESCE(SUM(DISTINCT s.split_amount),0) AS split_total
        FROM restaurant_orders ro
        INNER JOIN restaurant_bill_splits s ON s.restaurant_order_id = ro.id
        {$where}
        GROUP BY ro.id
        ORDER BY COALESCE(ro.closed_at, ro.opened_at, ro.id) DESC
        LIMIT 80
    ";
    $s = $pdo->prepare($sql);
    $s->execute($params);
    return $s->fetchAll(PDO::FETCH_ASSOC) ?: [];
}

function rsr_fetch_split_bills(PDO $pdo, int $orderId): array {
    if ($orderId <= 0 || !rsr_table_exists($pdo, 'restaurant_bill_splits')) return [];

    $hasSettlements = rsr_table_exists($pdo, 'restaurant_split_settlements');
    $hasAlloc = rsr_table_exists($pdo, 'restaurant_item_allocations');

    $amountCol = rsr_column_exists($pdo, 'restaurant_bill_splits', 'split_amount') ? 's.split_amount' : (rsr_column_exists($pdo, 'restaurant_bill_splits', 'amount') ? 's.amount' : '0');
    $statusSql = rsr_column_exists($pdo, 'restaurant_bill_splits', 'status') ? " AND COALESCE(s.status,'open') <> 'void' " : '';

    $settleSelect = $hasSettlements ? ", ss.id AS settlement_id, ss.destination_type, ss.folio_id, ss.payer_name AS settlement_payer, ss.amount AS settlement_amount, ss.reference_no AS settlement_ref, ss.note AS settlement_note" : ", NULL AS settlement_id, NULL AS destination_type, NULL AS folio_id, NULL AS settlement_payer, NULL AS settlement_amount, NULL AS settlement_ref, NULL AS settlement_note";
    $settleJoin = $hasSettlements ? " LEFT JOIN restaurant_split_settlements ss ON ss.split_id = s.id AND ss.restaurant_order_id = s.restaurant_order_id " : '';

    $s = $pdo->prepare("SELECT s.id AS split_id, s.restaurant_order_id, s.split_type, s.payer_name, s.payment_method, {$amountCol} AS split_amount, s.reference_no {$settleSelect}
        FROM restaurant_bill_splits s
        {$settleJoin}
        WHERE s.restaurant_order_id = :rid {$statusSql}
        ORDER BY s.id ASC");
    $s->execute([':rid' => $orderId]);
    $rows = $s->fetchAll(PDO::FETCH_ASSOC) ?: [];

    $bills = [];
    foreach ($rows as $r) {
        $splitId = (int)$r['split_id'];
        $settlementId = (int)($r['settlement_id'] ?? 0);
        $folioId = (int)($r['folio_id'] ?? 0);
        $dest = strtolower(trim((string)($r['destination_type'] ?? '')));
        $payer = trim((string)($r['settlement_payer'] ?: $r['payer_name'] ?: 'Guest'));
        $amount = round((float)($r['settlement_amount'] ?: $r['split_amount']), 2);
        $ref = trim((string)($r['settlement_ref'] ?: $r['reference_no']));
        $folio = rsr_folio_label($pdo, $folioId);
        $label = $folio['label'] !== '' ? $folio['label'] : ($payer !== '' ? $payer : ucwords(str_replace('_',' ', $dest ?: 'Split')));

        $key = $settlementId > 0 ? ('settlement_'.$settlementId) : ('split_'.$splitId);
        $bills[$key] = [
            'key' => $key,
            'split_id' => $splitId,
            'settlement_id' => $settlementId,
            'folio_id' => $folioId,
            'destination_type' => $dest,
            'payment_method' => trim((string)($r['payment_method'] ?? '')),
            'payer' => $payer,
            'label' => $label,
            'room_no' => $folio['room_no'],
            'amount' => $amount,
            'ref' => $ref,
            'note' => trim((string)($r['settlement_note'] ?? '')),
            'items' => [],
            'line_label' => ucwords(str_replace('_',' ', (string)($r['split_type'] ?: 'Split'))),
        ];
    }

    // If item allocation audit exists, attach exact item lines to each bill.
    if ($hasAlloc && $bills) {
        try {
            $s = $pdo->prepare("SELECT a.*, oi.item_name, oi.qty AS original_qty, oi.unit_price, oi.line_total, oi.tax_amount, oi.notes AS item_notes
                FROM restaurant_item_allocations a
                LEFT JOIN restaurant_order_items oi ON oi.id = a.restaurant_order_item_id
                WHERE a.restaurant_order_id = :rid
                ORDER BY a.folio_id ASC, a.split_id ASC, a.id ASC");
            $s->execute([':rid' => $orderId]);
            foreach ($s->fetchAll(PDO::FETCH_ASSOC) ?: [] as $a) {
                $splitId = (int)($a['split_id'] ?? 0);
                $folioId = (int)($a['folio_id'] ?? 0);
                $dest = strtolower(trim((string)($a['destination_type'] ?? '')));
                $targetKey = null;
                foreach ($bills as $k => $b) {
                    if ($splitId > 0 && (int)$b['split_id'] === $splitId) { $targetKey = $k; break; }
                }
                if ($targetKey === null) {
                    foreach ($bills as $k => $b) {
                        if ($folioId > 0 && (int)$b['folio_id'] === $folioId && ($dest === '' || $dest === $b['destination_type'])) { $targetKey = $k; break; }
                    }
                }
                if ($targetKey === null) continue;
                $bills[$targetKey]['items'][] = [
                    'id' => (int)($a['restaurant_order_item_id'] ?? 0),
                    'name' => trim((string)($a['item_name'] ?? ('Item #' . (int)($a['restaurant_order_item_id'] ?? 0)))),
                    'qty' => max(1, (float)($a['qty'] ?? $a['unit_qty'] ?? 1)),
                    'amount' => round((float)($a['amount'] ?? 0), 2),
                    'notes' => trim((string)($a['item_notes'] ?? '')),
                ];
            }
        } catch (Throwable $e) {}
    }

    // If there are no allocations, create one summary line per split so a reprint is still possible.
    foreach ($bills as &$b) {
        if (!$b['items']) {
            $b['items'][] = [
                'id' => 0,
                'name' => $b['line_label'] . ' - ' . $b['label'],
                'qty' => 1,
                'amount' => (float)$b['amount'],
                'notes' => 'Summary reprint from posted split record',
            ];
        }
    }
    unset($b);

    return array_values($bills);
}

function rsr_create_split_bill_job(PDO $pdo, int $orderId, array $bill): int {
    rsr_ensure_print_tables($pdo);
    $order = rsr_order_row($pdo, $orderId);
    if (!$order) throw new RuntimeException('Restaurant order not found.');

    $label = trim((string)($bill['label'] ?? 'Split Bill'));
    $dest = trim((string)($bill['destination_type'] ?? ''));
    $method = trim((string)($bill['payment_method'] ?? ''));
    if ($method === '' && $dest !== '') $method = ucwords(str_replace('_',' ', $dest));
    $ref = trim((string)($bill['ref'] ?? ''));
    $items = is_array($bill['items'] ?? null) ? $bill['items'] : [];

    $total = 0.0;
    foreach ($items as $it) $total += round((float)($it['amount'] ?? 0), 2);
    if ($total <= 0) $total = round((float)($bill['amount'] ?? 0), 2);

    $payload = '';
    $payload .= "==========================================\n";
    $payload .= rsr_center_text('SPLIT BILL REPRINT');
    $payload .= rsr_center_text(strtoupper($label));
    $payload .= "==========================================\n";
    $payload .= 'Order: ' . (string)($order['order_no'] ?? ('#'.$orderId)) . "\n";
    if (!empty($order['table_label'])) $payload .= 'Table: ' . (string)$order['table_label'] . "\n";
    if (!empty($order['guest_name'])) $payload .= 'Guest: ' . (string)$order['guest_name'] . "\n";
    if (!empty($order['room_no'])) $payload .= 'Order Room: ' . (string)$order['room_no'] . "\n";
    if ($method !== '') $payload .= 'Posted To: ' . $method . "\n";
    if ($ref !== '') $payload .= 'Reference: ' . $ref . "\n";
    $payload .= 'Printed: ' . date('Y-m-d H:i:s') . "\n";
    $payload .= 'Cashier: ' . rsr_current_user_name() . "\n";
    $payload .= "==========================================\n";

    foreach ($items as $it) {
        $qty = (float)($it['qty'] ?? 1);
        if ($qty <= 0) $qty = 1;
        $amount = round((float)($it['amount'] ?? 0), 2);
        if ($amount <= 0) continue;
        $name = trim((string)($it['name'] ?? 'Item'));
        $qtyText = rtrim(rtrim(number_format($qty, 2, '.', ''), '0'), '.');
        $left = $qtyText . ' x ' . $name;
        $lineTotal = money_fmt($amount);
        $unit = money_fmt($amount / max($qty, 0.0001));
        $first = true;
        foreach (rsr_wrap_line($left, 30) as $wrapped) {
            if ($first) {
                $payload .= str_pad(substr($wrapped, 0, 30), 31) . str_pad($lineTotal, 10, ' ', STR_PAD_LEFT) . "\n";
                $payload .= '   @ ' . $unit . "\n";
                $first = false;
            } else {
                $payload .= '   ' . $wrapped . "\n";
            }
        }
        $notes = trim((string)($it['notes'] ?? ''));
        if ($notes !== '') {
            foreach (rsr_wrap_line('Note: ' . $notes, 38) as $n) $payload .= '   ' . $n . "\n";
        }
    }

    $payload .= "------------------------------------------\n";
    $payload .= rsr_money_line('TOTAL POSTED', $total);
    $payload .= "==========================================\n";
    $payload .= rsr_center_text('Thank you.');

    $role = rsr_split_bill_print_role($pdo);
    if (rsr_column_exists($pdo, 'restaurant_print_jobs', 'printer_id')) {
        $s = $pdo->prepare("INSERT INTO restaurant_print_jobs(restaurant_order_id, printer_role, printer_id, job_type, payload, status) VALUES(:rid, :role, NULL, 'bill', :payload, 'pending')");
        $s->execute([':rid' => $orderId, ':role' => $role, ':payload' => $payload]);
    } else {
        $s = $pdo->prepare("INSERT INTO restaurant_print_jobs(restaurant_order_id, printer_role, job_type, payload, status) VALUES(:rid, :role, 'bill', :payload, 'pending')");
        $s->execute([':rid' => $orderId, ':role' => $role, ':payload' => $payload]);
    }
    return (int)$pdo->lastInsertId();
}

$errors = [];
$selectedOrderId = (int)($_GET['restaurant_order_id'] ?? $_POST['restaurant_order_id'] ?? 0);
$search = trim((string)($_GET['q'] ?? ''));

try {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $action = (string)($_POST['action'] ?? '');
        $orderId = (int)($_POST['restaurant_order_id'] ?? 0);
        if ($orderId <= 0) throw new RuntimeException('Invalid restaurant order.');

        $bills = rsr_fetch_split_bills($pdo, $orderId);
        if (!$bills) throw new RuntimeException('No split bills were found for this restaurant order.');

        $toPrint = [];
        if ($action === 'reprint_one') {
            $key = trim((string)($_POST['bill_key'] ?? ''));
            foreach ($bills as $b) {
                if ((string)$b['key'] === $key) { $toPrint[] = $b; break; }
            }
            if (!$toPrint) throw new RuntimeException('Selected split bill was not found.');
        } elseif ($action === 'reprint_all') {
            $toPrint = $bills;
        } else {
            throw new RuntimeException('Unknown action.');
        }

        $jobIds = [];
        foreach ($toPrint as $bill) $jobIds[] = rsr_create_split_bill_job($pdo, $orderId, $bill);
        $result = rsr_dispatch_printnode_jobs($pdo, $jobIds);

        if ((int)$result['failed'] > 0) {
            rsr_flash('warning', (int)$result['ok'] . ' bill(s) printed, ' . (int)$result['failed'] . ' failed. ' . implode(' | ', $result['messages'] ?? []));
        } else {
            rsr_flash('success', (int)$result['ok'] . ' split bill(s) reprinted successfully.');
        }
        header('Location: restaurant_split_reprint.php?restaurant_order_id=' . $orderId);
        exit;
    }
} catch (Throwable $e) {
    $errors[] = $e->getMessage();
}

$orders = [];
$selectedOrder = [];
$bills = [];
try {
    $orders = rsr_fetch_recent_orders($pdo, $search);
    if ($selectedOrderId > 0) {
        $selectedOrder = rsr_order_row($pdo, $selectedOrderId);
        $bills = rsr_fetch_split_bills($pdo, $selectedOrderId);
    }
} catch (Throwable $e) {
    $errors[] = $e->getMessage();
}

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

<div class="hero-band mb-3" style="padding:12px 16px!important;border-radius:16px;">
    <div class="d-flex flex-wrap justify-content-between align-items-center gap-2">
        <div>
            <div class="page-eyebrow text-white-50"><i class="bi bi-printer"></i> Restaurant POS</div>
            <div class="hero-title" style="font-size:1.2rem;">Split Bill Reprint</div>
            <div class="hero-subtitle" style="font-size:.82rem;">View closed split postings and reprint room/folio bills without reposting charges.</div>
        </div>
        <div class="d-flex gap-2 flex-wrap">
            <a href="planner.php" class="btn btn-sm btn-outline-light"><i class="bi bi-arrow-left me-1"></i>Planner</a>
        </div>
    </div>
</div>

<?php foreach (rsr_get_flash() as $f): ?>
    <div class="alert alert-<?php echo h($f['type']); ?>"><?php echo h($f['message']); ?></div>
<?php endforeach; ?>
<?php if ($errors): ?>
    <div class="alert alert-danger">
        <strong>Please fix:</strong>
        <ul class="mb-0">
            <?php foreach ($errors as $err): ?><li><?php echo h($err); ?></li><?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

<div class="card panel-card mb-3">
    <div class="card-body">
        <form method="get" class="row g-2 align-items-end">
            <div class="col-md-4">
                <label class="form-label">Restaurant Order ID</label>
                <input type="number" name="restaurant_order_id" class="form-control form-control-sm" value="<?php echo $selectedOrderId > 0 ? (int)$selectedOrderId : ''; ?>" placeholder="e.g. 123">
            </div>
            <div class="col-md-5">
                <label class="form-label">Search recent split orders</label>
                <input type="text" name="q" class="form-control form-control-sm" value="<?php echo h($search); ?>" placeholder="Order no, guest, room, group, or ID">
            </div>
            <div class="col-md-3 d-flex gap-2">
                <button class="btn btn-sm btn-primary"><i class="bi bi-search me-1"></i>Load</button>
                <a href="restaurant_split_reprint.php" class="btn btn-sm btn-outline-secondary">Reset</a>
            </div>
        </form>
    </div>
</div>

<?php if ($selectedOrder): ?>
<div class="card panel-card mb-3">
    <div class="card-header d-flex justify-content-between align-items-center flex-wrap gap-2">
        <div>
            <h5 class="mb-0">Order <?php echo h($selectedOrder['order_no'] ?? ('#'.$selectedOrderId)); ?></h5>
            <small class="text-muted">
                Status: <?php echo h($selectedOrder['status'] ?? ''); ?> |
                Guest: <?php echo h($selectedOrder['guest_name'] ?? ''); ?> |
                Room: <?php echo h($selectedOrder['room_no'] ?? ''); ?> |
                Total: <?php echo money_fmt($selectedOrder['total_amount'] ?? 0); ?>
            </small>
        </div>
        <?php if ($bills): ?>
            <form method="post" onsubmit="return confirm('Reprint ALL split bills for this order? This will NOT repost to folio.');">
                <input type="hidden" name="action" value="reprint_all">
                <input type="hidden" name="restaurant_order_id" value="<?php echo (int)$selectedOrderId; ?>">
                <button class="btn btn-sm btn-success"><i class="bi bi-printer me-1"></i>Reprint All Split Bills</button>
            </form>
        <?php endif; ?>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-modern table-striped align-middle mb-0">
                <thead>
                    <tr>
                        <th>Destination</th>
                        <th>Split</th>
                        <th>Items / Details</th>
                        <th class="text-end">Amount</th>
                        <th class="text-end">Action</th>
                    </tr>
                </thead>
                <tbody>
                <?php if (!$bills): ?>
                    <tr><td colspan="5" class="text-center text-muted py-4">No split bills found for this order.</td></tr>
                <?php else: ?>
                    <?php foreach ($bills as $bill): ?>
                        <tr>
                            <td>
                                <strong><?php echo h($bill['label']); ?></strong>
                                <div class="small text-muted">
                                    <?php echo h(ucwords(str_replace('_',' ', $bill['destination_type'] ?: 'split'))); ?>
                                    <?php echo (int)$bill['folio_id'] > 0 ? ' | Folio ID '.(int)$bill['folio_id'] : ''; ?>
                                </div>
                            </td>
                            <td>
                                <span class="badge text-bg-secondary">Split #<?php echo (int)$bill['split_id']; ?></span>
                                <?php if ((int)$bill['settlement_id'] > 0): ?>
                                    <span class="badge text-bg-info">Settlement #<?php echo (int)$bill['settlement_id']; ?></span>
                                <?php endif; ?>
                                <?php if ($bill['ref'] !== ''): ?><div class="small text-muted">Ref: <?php echo h($bill['ref']); ?></div><?php endif; ?>
                            </td>
                            <td>
                                <?php foreach ($bill['items'] as $it): ?>
                                    <div class="small">
                                        <?php echo h(rtrim(rtrim(number_format((float)$it['qty'], 2, '.', ''), '0'), '.')); ?> x
                                        <?php echo h($it['name']); ?>
                                        <span class="text-muted">- <?php echo money_fmt($it['amount']); ?></span>
                                    </div>
                                <?php endforeach; ?>
                            </td>
                            <td class="text-end"><strong><?php echo money_fmt($bill['amount']); ?></strong></td>
                            <td class="text-end">
                                <form method="post" onsubmit="return confirm('Reprint this split bill only? This will NOT repost to folio.');">
                                    <input type="hidden" name="action" value="reprint_one">
                                    <input type="hidden" name="restaurant_order_id" value="<?php echo (int)$selectedOrderId; ?>">
                                    <input type="hidden" name="bill_key" value="<?php echo h($bill['key']); ?>">
                                    <button class="btn btn-sm btn-outline-primary"><i class="bi bi-printer me-1"></i>Reprint</button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
<?php endif; ?>

<div class="card panel-card">
    <div class="card-header">
        <h5 class="mb-0">Recent Restaurant Orders With Splits</h5>
        <small class="text-muted">Click View to inspect and reprint split bills.</small>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-modern table-hover align-middle mb-0">
                <thead>
                    <tr>
                        <th>Order</th>
                        <th>Status</th>
                        <th>Guest / Room</th>
                        <th>Closed</th>
                        <th class="text-end">Split Count</th>
                        <th class="text-end">Total</th>
                        <th class="text-end">Action</th>
                    </tr>
                </thead>
                <tbody>
                <?php if (!$orders): ?>
                    <tr><td colspan="7" class="text-center text-muted py-4">No split orders found.</td></tr>
                <?php else: ?>
                    <?php foreach ($orders as $o): ?>
                        <tr>
                            <td>
                                <strong><?php echo h($o['order_no'] ?: ('#'.$o['id'])); ?></strong>
                                <div class="small text-muted">ID <?php echo (int)$o['id']; ?></div>
                            </td>
                            <td><span class="badge text-bg-<?php echo strtolower((string)$o['status']) === 'closed' ? 'dark' : 'warning'; ?>"><?php echo h($o['status']); ?></span></td>
                            <td>
                                <?php echo h($o['guest_name'] ?: $o['group_name'] ?: 'Guest'); ?>
                                <?php if (!empty($o['room_no'])): ?><div class="small text-muted">Room <?php echo h($o['room_no']); ?></div><?php endif; ?>
                            </td>
                            <td><small><?php echo h($o['closed_at'] ?: $o['opened_at']); ?></small></td>
                            <td class="text-end"><?php echo (int)$o['split_count']; ?></td>
                            <td class="text-end"><?php echo money_fmt($o['total_amount']); ?></td>
                            <td class="text-end"><a class="btn btn-sm btn-outline-primary" href="restaurant_split_reprint.php?restaurant_order_id=<?php echo (int)$o['id']; ?>">View</a></td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<style>
.table-modern th,.table-modern td{font-size:.86rem;}
</style>

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