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

$pageTitle = 'POS Printers';

if (!function_exists('h')) {
    function h($value): string { return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8'); }
}
if (!function_exists('pp_table_exists')) {
    function pp_table_exists(PDO $pdo, string $tableName): bool {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = :table_name");
        $stmt->execute([':table_name' => $tableName]);
        return (int)$stmt->fetchColumn() > 0;
    }
}
if (!function_exists('pp_column_exists')) {
    function pp_column_exists(PDO $pdo, string $tableName, string $columnName): bool {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = :table_name AND column_name = :column_name");
        $stmt->execute([':table_name' => $tableName, ':column_name' => $columnName]);
        return (int)$stmt->fetchColumn() > 0;
    }
}
if (!function_exists('pp_flash')) {
    function pp_flash(string $type, string $message): void {
        $_SESSION['pos_printer_flash'][] = ['type' => $type, 'message' => $message];
    }
}
if (!function_exists('pp_get_flash')) {
    function pp_get_flash(): array {
        $items = $_SESSION['pos_printer_flash'] ?? [];
        unset($_SESSION['pos_printer_flash']);
        return $items;
    }
}

$errors = [];

try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS pos_printers (
        id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        printer_name VARCHAR(120) NOT NULL,
        printer_role ENUM('kitchen','bar','icecream','master','other') NOT NULL DEFAULT 'kitchen',
        connection_type ENUM('windows_share','network_ip','browser','agent_queue','other') NOT NULL DEFAULT 'agent_queue',
        printer_path VARCHAR(255) NULL,
        printer_ip VARCHAR(80) NULL,
        printer_port INT UNSIGNED NULL DEFAULT 9100,
        is_master_printer TINYINT(1) NOT NULL DEFAULT 0,
        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,
        INDEX idx_pos_printer_active (is_active),
        INDEX idx_pos_printer_role (printer_role)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $pdo->exec("CREATE TABLE IF NOT EXISTS pos_print_jobs (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        pos_order_id BIGINT UNSIGNED NOT NULL,
        printer_id INT UNSIGNED NULL,
        printer_name VARCHAR(120) NULL,
        print_type ENUM('master','station','reprint','void') NOT NULL DEFAULT 'station',
        payload_text MEDIUMTEXT NOT NULL,
        status ENUM('pending','printing','printed','failed','cancelled') NOT NULL DEFAULT 'pending',
        copies INT UNSIGNED NOT NULL DEFAULT 1,
        attempts INT UNSIGNED NOT NULL DEFAULT 0,
        last_error TEXT NULL,
        printed_at DATETIME NULL,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_print_jobs_order (pos_order_id),
        INDEX idx_print_jobs_printer (printer_id),
        INDEX idx_print_jobs_status (status)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    if (pp_table_exists($pdo, 'inventory_items') && !pp_column_exists($pdo, 'inventory_items', 'default_pos_printer_id')) {
        $after = pp_column_exists($pdo, 'inventory_items', 'subcategory_id') ? ' AFTER subcategory_id' : ' AFTER category_id';
        $pdo->exec("ALTER TABLE inventory_items ADD COLUMN default_pos_printer_id INT UNSIGNED NULL" . $after);
    }

    if (pp_table_exists($pdo, 'pos_order_items')) {
        if (!pp_column_exists($pdo, 'pos_order_items', 'prep_printer_id')) {
            $pdo->exec("ALTER TABLE pos_order_items ADD COLUMN prep_printer_id INT UNSIGNED NULL AFTER tax_rate");
        }
        if (!pp_column_exists($pdo, 'pos_order_items', 'prep_printer_name')) {
            $pdo->exec("ALTER TABLE pos_order_items ADD COLUMN prep_printer_name VARCHAR(120) NULL AFTER prep_printer_id");
        }
    }
} catch (Throwable $e) {
    $errors[] = 'Could not prepare POS printer tables: ' . $e->getMessage();
}

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

        if ($action === 'save_printer') {
            $id = (int)($_POST['id'] ?? 0);
            $printerName = trim((string)($_POST['printer_name'] ?? ''));
            $printerRole = trim((string)($_POST['printer_role'] ?? 'kitchen'));
            $connectionType = trim((string)($_POST['connection_type'] ?? 'agent_queue'));
            $printerPath = trim((string)($_POST['printer_path'] ?? ''));
            $printerIp = trim((string)($_POST['printer_ip'] ?? ''));
            $printerPort = (int)($_POST['printer_port'] ?? 9100);
            $isMaster = isset($_POST['is_master_printer']) ? 1 : 0;
            $isActive = isset($_POST['is_active']) ? 1 : 0;
            $notes = trim((string)($_POST['notes'] ?? ''));

            if ($printerName === '') throw new RuntimeException('Printer name is required.');
            if (!in_array($printerRole, ['kitchen','bar','icecream','master','other'], true)) $printerRole = 'kitchen';
            if (!in_array($connectionType, ['windows_share','network_ip','browser','agent_queue','other'], true)) $connectionType = 'agent_queue';
            if ($printerPort <= 0) $printerPort = 9100;

            if ($isMaster) {
                $pdo->exec("UPDATE pos_printers SET is_master_printer = 0");
            }

            if ($id > 0) {
                $stmt = $pdo->prepare("UPDATE pos_printers SET printer_name=:printer_name, printer_role=:printer_role, connection_type=:connection_type, printer_path=:printer_path, printer_ip=:printer_ip, printer_port=:printer_port, is_master_printer=:is_master_printer, is_active=:is_active, notes=:notes WHERE id=:id");
                $stmt->execute([
                    ':printer_name' => $printerName,
                    ':printer_role' => $printerRole,
                    ':connection_type' => $connectionType,
                    ':printer_path' => $printerPath !== '' ? $printerPath : null,
                    ':printer_ip' => $printerIp !== '' ? $printerIp : null,
                    ':printer_port' => $printerPort,
                    ':is_master_printer' => $isMaster,
                    ':is_active' => $isActive,
                    ':notes' => $notes !== '' ? $notes : null,
                    ':id' => $id,
                ]);
                pp_flash('success', 'Printer updated successfully.');
            } else {
                $stmt = $pdo->prepare("INSERT INTO pos_printers (printer_name, printer_role, connection_type, printer_path, printer_ip, printer_port, is_master_printer, is_active, notes) VALUES (:printer_name, :printer_role, :connection_type, :printer_path, :printer_ip, :printer_port, :is_master_printer, :is_active, :notes)");
                $stmt->execute([
                    ':printer_name' => $printerName,
                    ':printer_role' => $printerRole,
                    ':connection_type' => $connectionType,
                    ':printer_path' => $printerPath !== '' ? $printerPath : null,
                    ':printer_ip' => $printerIp !== '' ? $printerIp : null,
                    ':printer_port' => $printerPort,
                    ':is_master_printer' => $isMaster,
                    ':is_active' => $isActive,
                    ':notes' => $notes !== '' ? $notes : null,
                ]);
                pp_flash('success', 'Printer created successfully.');
            }

            header('Location: pos_printers.php');
            exit;
        }

        if ($action === 'delete_printer') {
            $id = (int)($_POST['id'] ?? 0);
            if ($id <= 0) throw new RuntimeException('Invalid printer selected.');
            $pdo->prepare("UPDATE inventory_items SET default_pos_printer_id = NULL WHERE default_pos_printer_id = :id")->execute([':id' => $id]);
            $pdo->prepare("UPDATE pos_printers SET is_active = 0 WHERE id = :id")->execute([':id' => $id]);
            pp_flash('success', 'Printer deactivated and unlinked from items.');
            header('Location: pos_printers.php');
            exit;
        }

        if ($action === 'save_item_printers') {
            $assignments = $_POST['printer_id'] ?? [];
            if (!is_array($assignments)) $assignments = [];
            $stmt = $pdo->prepare("UPDATE inventory_items SET default_pos_printer_id = :printer_id WHERE id = :id");
            foreach ($assignments as $itemId => $printerId) {
                $itemId = (int)$itemId;
                $printerId = (int)$printerId;
                if ($itemId <= 0) continue;
                $stmt->execute([
                    ':printer_id' => $printerId > 0 ? $printerId : null,
                    ':id' => $itemId,
                ]);
            }
            pp_flash('success', 'Item printer routing saved.');
            header('Location: pos_printers.php');
            exit;
        }

        throw new RuntimeException('Invalid action.');
    } catch (Throwable $e) {
        pp_flash('danger', $e->getMessage());
        header('Location: pos_printers.php');
        exit;
    }
}

$editPrinter = null;
if (isset($_GET['edit'])) {
    $stmt = $pdo->prepare("SELECT * FROM pos_printers WHERE id = :id LIMIT 1");
    $stmt->execute([':id' => (int)$_GET['edit']]);
    $editPrinter = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
}

$printers = [];
$items = [];
$jobs = [];
try {
    $printers = $pdo->query("SELECT * FROM pos_printers ORDER BY is_active DESC, printer_role ASC, printer_name ASC")->fetchAll(PDO::FETCH_ASSOC);

    if (pp_table_exists($pdo, 'inventory_items')) {
        $stmt = $pdo->query("SELECT ii.id, ii.item_name, ii.item_code, ii.item_type, ii.default_pos_printer_id, c.category_name, sc.subcategory_name FROM inventory_items ii LEFT JOIN inventory_item_categories c ON c.id = ii.category_id LEFT JOIN inventory_item_subcategories sc ON sc.id = ii.subcategory_id WHERE ii.is_active = 1 AND ii.is_pos_item = 1 ORDER BY c.category_name ASC, sc.subcategory_name ASC, ii.item_name ASC");
        $items = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    $jobs = $pdo->query("SELECT j.*, po.pos_no FROM pos_print_jobs j LEFT JOIN pos_orders po ON po.id = j.pos_order_id ORDER BY j.id DESC LIMIT 80")->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $errors[] = 'Could not load POS printer data: ' . $e->getMessage();
}

$flashes = pp_get_flash();
require_once __DIR__ . '/../../includes/header.php';
?>

<div class="hero-band compact-printer-hero">
    <div class="row g-2 align-items-center">
        <div class="col-lg-8">
            <div class="page-eyebrow text-white-50"><i class="bi bi-printer"></i> POS Routing</div>
            <div class="hero-title mt-1">POS Printers</div>
            <div class="hero-subtitle mt-1">Route kitchen, bar, ice cream and master POS tickets by default item printer.</div>
        </div>
        <div class="col-lg-4 text-lg-end">
            <a href="/rooms/modules/pos/pos.php" class="btn btn-light btn-sm"><i class="bi bi-cash-register me-1"></i>Back to POS</a>
        </div>
    </div>
</div>

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

<div class="row g-4">
    <div class="col-xl-4">
        <div class="card panel-card mb-4">
            <div class="card-header"><h5 class="mb-0"><?php echo $editPrinter ? 'Edit Printer' : 'Register Printer'; ?></h5></div>
            <div class="card-body">
                <form method="post">
                    <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                    <input type="hidden" name="action" value="save_printer">
                    <input type="hidden" name="id" value="<?php echo (int)($editPrinter['id'] ?? 0); ?>">

                    <div class="mb-3"><label class="form-label">Printer Name</label><input type="text" name="printer_name" class="form-control" value="<?php echo h($editPrinter['printer_name'] ?? ''); ?>" placeholder="Kitchen Printer / Bar Printer" required></div>
                    <div class="row g-2">
                        <div class="col-md-6"><label class="form-label">Role</label><select name="printer_role" class="form-select"><?php foreach (['kitchen'=>'Kitchen','bar'=>'Bar','icecream'=>'Ice Cream','master'=>'Master','other'=>'Other'] as $v=>$l): ?><option value="<?php echo h($v); ?>" <?php echo (($editPrinter['printer_role'] ?? '') === $v) ? 'selected' : ''; ?>><?php echo h($l); ?></option><?php endforeach; ?></select></div>
                        <div class="col-md-6"><label class="form-label">Connection</label><select name="connection_type" class="form-select"><?php foreach (['agent_queue'=>'Print Agent Queue','network_ip'=>'Network IP','windows_share'=>'Windows Share','browser'=>'Browser','other'=>'Other'] as $v=>$l): ?><option value="<?php echo h($v); ?>" <?php echo (($editPrinter['connection_type'] ?? 'agent_queue') === $v) ? 'selected' : ''; ?>><?php echo h($l); ?></option><?php endforeach; ?></select></div>
                    </div>
                    <div class="mt-3"><label class="form-label">Printer Path / Share Name</label><input type="text" name="printer_path" class="form-control" value="<?php echo h($editPrinter['printer_path'] ?? ''); ?>" placeholder="\\\\SERVER\\KitchenPrinter or local queue name"></div>
                    <div class="row g-2 mt-1"><div class="col-md-8"><label class="form-label">Printer IP</label><input type="text" name="printer_ip" class="form-control" value="<?php echo h($editPrinter['printer_ip'] ?? ''); ?>" placeholder="192.168.1.50"></div><div class="col-md-4"><label class="form-label">Port</label><input type="number" name="printer_port" class="form-control" value="<?php echo h($editPrinter['printer_port'] ?? 9100); ?>"></div></div>
                    <div class="form-check mt-3"><input class="form-check-input" type="checkbox" name="is_master_printer" id="isMaster" <?php echo !empty($editPrinter['is_master_printer']) ? 'checked' : ''; ?>><label class="form-check-label" for="isMaster">Master printer copy</label></div>
                    <div class="form-check mt-2"><input class="form-check-input" type="checkbox" name="is_active" id="isActive" <?php echo !isset($editPrinter['is_active']) || (int)$editPrinter['is_active'] === 1 ? 'checked' : ''; ?>><label class="form-check-label" for="isActive">Active</label></div>
                    <div class="mt-3"><label class="form-label">Notes</label><textarea name="notes" class="form-control" rows="2"><?php echo h($editPrinter['notes'] ?? ''); ?></textarea></div>
                    <button class="btn btn-primary w-100 mt-3"><i class="bi bi-save me-1"></i>Save Printer</button>
                    <?php if ($editPrinter): ?><a href="pos_printers.php" class="btn btn-light w-100 mt-2">Cancel Edit</a><?php endif; ?>
                </form>
            </div>
        </div>

        <div class="card panel-card">
            <div class="card-header"><h5 class="mb-0">Printers</h5></div>
            <div class="card-body p-0">
                <table class="table table-sm table-modern mb-0 align-middle">
                    <thead><tr><th>Name</th><th>Role</th><th>Status</th><th class="text-end">Action</th></tr></thead>
                    <tbody>
                    <?php if (!$printers): ?><tr><td colspan="4" class="text-center text-muted py-3">No printers configured.</td></tr><?php endif; ?>
                    <?php foreach ($printers as $p): ?>
                        <tr>
                            <td><strong><?php echo h($p['printer_name']); ?></strong><?php if ((int)$p['is_master_printer'] === 1): ?><div class="small text-primary">Master copy</div><?php endif; ?></td>
                            <td><?php echo h(ucwords($p['printer_role'])); ?></td>
                            <td><span class="badge text-bg-<?php echo (int)$p['is_active'] === 1 ? 'success' : 'secondary'; ?>"><?php echo (int)$p['is_active'] === 1 ? 'Active' : 'Off'; ?></span></td>
                            <td class="text-end"><a class="btn btn-sm btn-outline-primary" href="pos_printers.php?edit=<?php echo (int)$p['id']; ?>">Edit</a><form method="post" class="d-inline" onsubmit="return confirm('Deactivate this printer and unlink it from items?');"><?php if (function_exists('csrf_field')) echo csrf_field(); ?><input type="hidden" name="action" value="delete_printer"><input type="hidden" name="id" value="<?php echo (int)$p['id']; ?>"><button class="btn btn-sm btn-outline-danger">Off</button></form></td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <div class="col-xl-8">
        <div class="card panel-card mb-4">
            <div class="card-header d-flex justify-content-between align-items-center"><h5 class="mb-0">Item Default Printer Mapping</h5><span class="text-muted small">Kitchen/bar tickets are split using this mapping</span></div>
            <div class="card-body p-0">
                <form method="post">
                    <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                    <input type="hidden" name="action" value="save_item_printers">
                    <div class="table-responsive printer-map-wrap">
                        <table class="table table-modern table-sm align-middle mb-0">
                            <thead><tr><th>Item</th><th>Category</th><th style="width:260px;">Default Printer</th></tr></thead>
                            <tbody>
                            <?php if (!$items): ?><tr><td colspan="3" class="text-center text-muted py-3">No POS items found.</td></tr><?php endif; ?>
                            <?php foreach ($items as $item): ?>
                                <tr>
                                    <td><strong><?php echo h($item['item_name']); ?></strong><div class="small text-muted"><?php echo h($item['item_code'] ?? ''); ?></div></td>
                                    <td><?php echo h(($item['category_name'] ?? 'Uncategorised') . (!empty($item['subcategory_name']) ? ' • ' . $item['subcategory_name'] : '')); ?></td>
                                    <td><select name="printer_id[<?php echo (int)$item['id']; ?>]" class="form-select form-select-sm"><option value="0">No station printer</option><?php foreach ($printers as $pr): if ((int)$pr['is_active'] !== 1) continue; ?><option value="<?php echo (int)$pr['id']; ?>" <?php echo (int)($item['default_pos_printer_id'] ?? 0) === (int)$pr['id'] ? 'selected' : ''; ?>><?php echo h($pr['printer_name'] . ' (' . ucwords($pr['printer_role']) . ')'); ?></option><?php endforeach; ?></select></td>
                                </tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <div class="p-3 border-top text-end"><button class="btn btn-success"><i class="bi bi-check2-circle me-1"></i>Save Item Routing</button></div>
                </form>
            </div>
        </div>

        <div class="card panel-card">
            <div class="card-header"><h5 class="mb-0">Recent Print Jobs</h5></div>
            <div class="card-body p-0">
                <div class="table-responsive printer-jobs-wrap">
                    <table class="table table-modern table-sm align-middle mb-0">
                        <thead><tr><th>Created</th><th>POS</th><th>Printer</th><th>Type</th><th>Status</th></tr></thead>
                        <tbody>
                        <?php if (!$jobs): ?><tr><td colspan="5" class="text-center text-muted py-3">No print jobs yet.</td></tr><?php endif; ?>
                        <?php foreach ($jobs as $job): ?>
                            <tr><td><?php echo h($job['created_at']); ?></td><td><?php echo h($job['pos_no'] ?: ('#' . $job['pos_order_id'])); ?></td><td><?php echo h($job['printer_name'] ?: ('Printer #' . $job['printer_id'])); ?></td><td><?php echo h($job['print_type']); ?></td><td><span class="badge text-bg-light border"><?php echo h($job['status']); ?></span></td></tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.compact-printer-hero{padding:10px 14px!important;margin-bottom:10px!important}.compact-printer-hero .hero-title{font-size:1.25rem!important;line-height:1.1!important}.compact-printer-hero .hero-subtitle{font-size:.78rem!important;line-height:1.15!important}.printer-map-wrap{max-height:520px;overflow:auto}.printer-map-wrap thead th,.printer-jobs-wrap thead th{position:sticky;top:0;background:#fff;z-index:5;box-shadow:0 1px 0 #e5e7eb}.printer-jobs-wrap{max-height:260px;overflow:auto}.panel-card .card-header{padding:10px 14px}.form-label{font-weight:700;font-size:.78rem;color:#475569}
</style>

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