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

$pageTitle = 'Bar Display';

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

if (!function_exists('bar_flash')) {
    function bar_flash(string $type, string $message): void {
        $_SESSION['bar_display_flash'][] = ['type' => $type, 'message' => $message];
    }
}

if (!function_exists('bar_get_flash')) {
    function bar_get_flash(): array {
        $items = $_SESSION['bar_display_flash'] ?? [];
        unset($_SESSION['bar_display_flash']);
        return $items;
    }
}

if (!function_exists('bar_table_exists')) {
    function bar_table_exists(PDO $pdo, string $tableName): bool {
        $stmt = $pdo->prepare("\n            SELECT COUNT(*)\n            FROM information_schema.tables\n            WHERE table_schema = DATABASE()\n              AND table_name = :table_name\n        ");
        $stmt->execute([':table_name' => $tableName]);
        return (int)$stmt->fetchColumn() > 0;
    }
}

if (!function_exists('bar_column_exists')) {
    function bar_column_exists(PDO $pdo, string $tableName, string $columnName): bool {
        $stmt = $pdo->prepare("\n            SELECT COUNT(*)\n            FROM information_schema.columns\n            WHERE table_schema = DATABASE()\n              AND table_name = :table_name\n              AND column_name = :column_name\n        ");
        $stmt->execute([':table_name' => $tableName, ':column_name' => $columnName]);
        return (int)$stmt->fetchColumn() > 0;
    }
}

$errors = [];
$jobs = [];
$summary = [
    'pending' => 0,
    'printing' => 0,
    'total' => 0,
];

try {
    if (!bar_table_exists($pdo, 'restaurant_print_jobs')) {
        throw new RuntimeException('restaurant_print_jobs table does not exist yet. Run the restaurant schema first.');
    }

    if (!bar_column_exists($pdo, 'restaurant_print_jobs', 'restaurant_order_id')) {
        throw new RuntimeException('restaurant_print_jobs.restaurant_order_id column is missing. Your display must use restaurant_order_id, not order_id.');
    }

    if (!bar_column_exists($pdo, 'restaurant_print_jobs', 'printer_role')) {
        throw new RuntimeException('restaurant_print_jobs.printer_role column is missing.');
    }
} catch (Throwable $e) {
    $errors[] = $e->getMessage();
}

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

        $action = (string)($_POST['action'] ?? '');
        $jobId = (int)($_POST['job_id'] ?? 0);

        if ($jobId <= 0) {
            throw new RuntimeException('Invalid print job selected.');
        }

        $allowedActions = [
            'mark_printing' => 'printing',
            'mark_printed' => 'printed',
            'mark_failed' => 'failed',
        ];

        if (!isset($allowedActions[$action])) {
            throw new RuntimeException('Invalid action selected.');
        }

        $newStatus = $allowedActions[$action];

        if ($newStatus === 'printed') {
            $stmt = $pdo->prepare("\n                UPDATE restaurant_print_jobs\n                SET status = 'printed', printed_at = NOW(), error_message = NULL\n                WHERE id = :id\n                  AND LOWER(COALESCE(printer_role, '')) IN ('bar','drinks','beverage','beverages')\n            ");
            $stmt->execute([':id' => $jobId]);
            bar_flash('success', 'Bar ticket marked as printed.');
        } elseif ($newStatus === 'failed') {
            $stmt = $pdo->prepare("\n                UPDATE restaurant_print_jobs\n                SET status = 'failed', error_message = 'Marked failed from Bar Display'\n                WHERE id = :id\n                  AND LOWER(COALESCE(printer_role, '')) IN ('bar','drinks','beverage','beverages')\n            ");
            $stmt->execute([':id' => $jobId]);
            bar_flash('warning', 'Bar ticket marked as failed.');
        } else {
            $stmt = $pdo->prepare("\n                UPDATE restaurant_print_jobs\n                SET status = 'printing', error_message = NULL\n                WHERE id = :id\n                  AND LOWER(COALESCE(printer_role, '')) IN ('bar','drinks','beverage','beverages')\n            ");
            $stmt->execute([':id' => $jobId]);
            bar_flash('info', 'Bar ticket marked as printing.');
        }

        header('Location: bar_display.php');
        exit;
    } catch (Throwable $e) {
        bar_flash('danger', $e->getMessage());
        header('Location: bar_display.php');
        exit;
    }
}

try {
    if (!$errors) {
        $stmt = $pdo->query("\n            SELECT\n                j.*,\n                ro.order_no,\n                ro.total_amount,\n                ro.status AS restaurant_order_status,\n                rt.table_no,\n                rt.table_name\n            FROM restaurant_print_jobs j\n            LEFT JOIN restaurant_orders ro\n                ON ro.id = j.restaurant_order_id\n            LEFT JOIN restaurant_tables rt\n                ON rt.id = ro.table_id\n            WHERE LOWER(COALESCE(j.printer_role, '')) IN ('bar','drinks','beverage','beverages')\n              AND j.status IN ('pending','printing')\n            ORDER BY\n                CASE j.status WHEN 'printing' THEN 0 ELSE 1 END,\n                j.created_at ASC,\n                j.id ASC\n            LIMIT 100\n        ");
        $jobs = $stmt->fetchAll(PDO::FETCH_ASSOC);

        foreach ($jobs as $job) {
            $summary['total']++;
            $status = strtolower((string)($job['status'] ?? ''));
            if (isset($summary[$status])) {
                $summary[$status]++;
            }
        }
    }
} catch (Throwable $e) {
    $errors[] = 'Could not load bar jobs: ' . $e->getMessage();
}

$flashes = bar_get_flash();

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

<div class="hero-band bar-hero">
    <div class="d-flex justify-content-between align-items-center gap-3 flex-wrap">
        <div>
            <div class="page-eyebrow text-white-50">
                <i class="bi bi-cup-straw"></i> Production
            </div>
            <div class="hero-title mt-1">Bar Display</div>
            <div class="hero-subtitle mt-1">Pending drink and beverage tickets from restaurant orders.</div>
        </div>
        <div class="d-flex gap-2 flex-wrap">
            <a class="btn btn-outline-light btn-sm" href="planner.php">
                <i class="bi bi-grid-3x3-gap me-1"></i>Planner
            </a>
            <a class="btn btn-outline-light btn-sm" href="kitchen_display.php">
                <i class="bi bi-display me-1"></i>Kitchen
            </a>
            <button class="btn btn-light btn-sm" onclick="location.reload()">
                <i class="bi bi-arrow-repeat me-1"></i>Refresh
            </button>
        </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">
        <div class="fw-bold mb-2">Please fix the following:</div>
        <ul class="mb-0">
            <?php foreach ($errors as $error): ?>
                <li><?php echo h($error); ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

<div class="row g-3 mb-3">
    <div class="col-md-4">
        <div class="metric-card mini-metric">
            <div class="metric-icon bg-primary-subtle text-primary"><i class="bi bi-cup-straw"></i></div>
            <div>
                <div class="metric-label">Open Bar Tickets</div>
                <div class="metric-value"><?php echo (int)$summary['total']; ?></div>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="metric-card mini-metric">
            <div class="metric-icon bg-warning-subtle text-warning"><i class="bi bi-hourglass-split"></i></div>
            <div>
                <div class="metric-label">Pending</div>
                <div class="metric-value"><?php echo (int)$summary['pending']; ?></div>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="metric-card mini-metric">
            <div class="metric-icon bg-info-subtle text-info"><i class="bi bi-printer"></i></div>
            <div>
                <div class="metric-label">Printing</div>
                <div class="metric-value"><?php echo (int)$summary['printing']; ?></div>
            </div>
        </div>
    </div>
</div>

<div class="row g-3">
    <?php if (!$jobs && !$errors): ?>
        <div class="col-12">
            <div class="alert alert-success clear-state">
                <i class="bi bi-check-circle me-2"></i>Bar clear. No pending drink tickets.
            </div>
        </div>
    <?php else: ?>
        <?php foreach ($jobs as $j): ?>
            <?php
                $isPrinting = strtolower((string)$j['status']) === 'printing';
                $orderLabel = trim((string)($j['order_no'] ?? ''));
                if ($orderLabel === '') {
                    $orderLabel = 'Order #' . (int)($j['restaurant_order_id'] ?? 0);
                }
                $tableLabel = trim((string)($j['table_no'] ?? ''));
                if ($tableLabel === '') {
                    $tableLabel = '-';
                }
            ?>
            <div class="col-md-6 col-xl-4">
                <div class="card ticket-card h-100 <?php echo $isPrinting ? 'is-printing' : ''; ?>">
                    <div class="card-header d-flex justify-content-between align-items-center gap-2">
                        <div>
                            <strong><?php echo h($orderLabel); ?></strong>
                            <div class="small text-muted">Ticket #<?php echo (int)$j['id']; ?></div>
                        </div>
                        <span class="badge <?php echo $isPrinting ? 'text-bg-info' : 'text-bg-primary'; ?>">
                            <?php echo $isPrinting ? 'Printing' : 'Bar'; ?>
                        </span>
                    </div>

                    <div class="card-body">
                        <div class="ticket-meta mb-2">
                            <span><i class="bi bi-grid-3x3-gap me-1"></i>Table <?php echo h($tableLabel); ?></span>
                            <span><i class="bi bi-clock me-1"></i><?php echo h($j['created_at']); ?></span>
                        </div>

                        <pre class="ticket-payload"><?php echo h($j['payload'] ?? ''); ?></pre>
                    </div>

                    <div class="card-footer bg-white d-flex gap-2 flex-wrap justify-content-end">
                        <?php if (!$isPrinting): ?>
                            <form method="post" class="d-inline">
                                <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                                <input type="hidden" name="action" value="mark_printing">
                                <input type="hidden" name="job_id" value="<?php echo (int)$j['id']; ?>">
                                <button class="btn btn-sm btn-outline-primary">
                                    <i class="bi bi-printer me-1"></i>Start
                                </button>
                            </form>
                        <?php endif; ?>

                        <form method="post" class="d-inline">
                            <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                            <input type="hidden" name="action" value="mark_printed">
                            <input type="hidden" name="job_id" value="<?php echo (int)$j['id']; ?>">
                            <button class="btn btn-sm btn-success" onclick="return confirm('Mark this bar ticket as completed?');">
                                <i class="bi bi-check2-circle me-1"></i>Done
                            </button>
                        </form>

                        <form method="post" class="d-inline">
                            <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                            <input type="hidden" name="action" value="mark_failed">
                            <input type="hidden" name="job_id" value="<?php echo (int)$j['id']; ?>">
                            <button class="btn btn-sm btn-outline-danger" onclick="return confirm('Mark this ticket as failed?');">
                                <i class="bi bi-exclamation-triangle me-1"></i>Fail
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    <?php endif; ?>
</div>

<style>
.bar-hero{padding:12px 16px!important;margin-bottom:10px!important}
.bar-hero .hero-title{font-size:1.35rem!important;line-height:1.05!important}
.bar-hero .hero-subtitle{font-size:.82rem!important;opacity:.9!important}
.mini-metric{padding:12px 14px!important;min-height:62px!important;border-radius:16px!important}
.mini-metric .metric-icon{width:36px!important;height:36px!important;border-radius:12px!important}
.ticket-card{border-radius:16px;border:1px solid #dbeafe;overflow:hidden;box-shadow:0 14px 30px rgba(15,23,42,.07)}
.ticket-card.is-printing{border-color:#7dd3fc;background:#f0f9ff}
.ticket-card .card-header{background:#ffffff}
.ticket-meta{display:flex;align-items:center;justify-content:space-between;gap:8px;flex-wrap:wrap;color:#64748b;font-size:.78rem;font-weight:600}
.ticket-payload{white-space:pre-wrap;font-family:inherit;background:#f8fafc;border-radius:12px;padding:10px;font-size:.88rem;min-height:150px;margin:0;border:1px solid #e2e8f0}
.clear-state{border-radius:16px;font-weight:700}
</style>

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