<?php
// dashboards/workshop.php — included by dashboard.php (session already started)
include $_SERVER['DOCUMENT_ROOT'] . "/app/dashboard/classes/dashboard.class.php";
$username = $_SESSION['username'] ?? 'Workshop';
$db = new db_safeguard();

// ── ALL STOCK ─────────────────────────────────────────────
$stock_res = $db->query("stock",
    "SELECT s.record_id, s.stock_no, s.item_name, s.type, s.size,
            s.unit_of_measure, s.status AS qty, s.serial_number,
            st.name AS type_name
     FROM stock s
     LEFT JOIN stock_types st ON st.record_id = s.stock_type_id
     ORDER BY s.item_name ASC"
);
$all_stock = [];
while ($row = $stock_res->fetch_assoc()) $all_stock[] = $row;

// ── RECENT TRANSACTIONS (last 50) ────────────────────────
$trans_res = $db->query("stock_trans",
    "SELECT record_id, stock_no, item_name, quantity, status, order_no, datetime_created
     FROM stock_trans
     ORDER BY record_id DESC
     LIMIT 50"
);
$transactions = [];
while ($row = $trans_res->fetch_assoc()) $transactions[] = $row;

// ── STATS ─────────────────────────────────────────────────
$total_items = count($all_stock);
$low_count   = count(array_filter($all_stock, fn($s) => (int)$s['qty'] <= 1));
$out_count   = count(array_filter($all_stock, fn($s) => (int)$s['qty'] <= 0));

// Transactions today
$today_res = $db->query("stock_trans",
    "SELECT COUNT(*) AS cnt FROM stock_trans WHERE DATE(datetime_created) = CURDATE()"
);
$today_count = (int)($today_res->fetch_assoc()['cnt'] ?? 0);

function w_esc($s) { return htmlspecialchars($s ?? '', ENT_QUOTES, 'UTF-8'); }
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Workshop — Stock</title>
    <link href="https://fonts.googleapis.com/css2?family=Bebas+Neue&family=DM+Sans:wght@300;400;500;600&family=DM+Mono:wght@400;500&display=swap" rel="stylesheet">    <style>
        *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
        :root {
            --bg:         #f0f4fa;
            --surface:    #ffffff;
            --border:     #d0daea;
            --blue:       #1a56c4;
            --blue-light: #e8f0fd;
            --orange:     #e8720a;
            --orange-lt:  #fff3e8;
            --green:      #16a34a;
            --green-lt:   #dcfce7;
            --red:        #dc2626;
            --red-lt:     #fee2e2;
            --text:       #0f1e3d;
            --muted:      #6b7fa8;
            --white:      #ffffff;
            --radius:     8px;
        }

        html, body { height: 100%; background: var(--bg); color: var(--text);
            font-family: 'DM Sans', sans-serif; }

        /* ── SHELL ── */
        .shell { display: grid; grid-template-rows: 52px 1fr; height: 100vh; }

        /* ── TOPBAR ── */
        .topbar { display: flex; align-items: center; justify-content: space-between;
            padding: 0 24px; background: var(--blue); position: sticky; top: 0; z-index: 20; }
        .topbar-left { display: flex; align-items: center; gap: 14px; }
        .logo-mark { width: 28px; height: 28px; background: var(--orange); flex-shrink: 0;
            clip-path: polygon(50% 0%,100% 25%,100% 75%,50% 100%,0% 75%,0% 25%); }
        .page-title { font-family: 'Bebas Neue'; font-size: 20px; letter-spacing: 2px; color: #fff; }
        .page-title span { color: var(--orange); }
        .divider-v { width: 1px; height: 24px; background: rgba(255,255,255,.25); }
        .role-badge { padding: 3px 10px; border-radius: 20px; background: var(--orange);
            font-size: 11px; font-weight: 700; letter-spacing: 1px; color: #fff; text-transform: uppercase; }
        .user-name { font-size: 13px; color: rgba(255,255,255,.85); font-weight: 500; }
        .btn-refresh { display: flex; align-items: center; gap: 6px; padding: 6px 14px;
            background: rgba(255,255,255,.12); border: 1px solid rgba(255,255,255,.25);
            color: #fff; border-radius: var(--radius); font-size: 12px; font-weight: 600;
            cursor: pointer; text-decoration: none; transition: background .2s; }
        .btn-refresh:hover { background: rgba(255,255,255,.22); }

        /* ── MAIN LAYOUT ── */
        .main {
            display: grid;
            grid-template-columns: 1fr 320px;
            grid-template-rows: auto 1fr;
            gap: 12px;
            padding: 12px;
            overflow: hidden;
            height: 100%;
        }

        /* ── STAT STRIP ── */
        .stat-strip {
            grid-column: 1 / 3;
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 12px;
        }
        .stat-tile { background: var(--white); border: 1px solid var(--border);
            border-radius: var(--radius); padding: 14px 16px;
            display: flex; align-items: center; gap: 14px;
            box-shadow: 0 1px 4px rgba(26,86,196,.06);
            position: relative; overflow: hidden; }
        .stat-tile::before { content: ''; position: absolute; top: 0; left: 0;
            width: 3px; height: 100%; }
        .stat-tile-blue::before   { background: var(--blue); }
        .stat-tile-orange::before { background: var(--orange); }
        .stat-tile-red::before    { background: var(--red); }
        .stat-tile-green::before  { background: var(--green); }
        .stat-icon { width: 36px; height: 36px; border-radius: 8px; flex-shrink: 0;
            display: flex; align-items: center; justify-content: center; }
        .stat-icon-blue   { background: var(--blue-light); color: var(--blue); }
        .stat-icon-orange { background: var(--orange-lt);  color: var(--orange); }
        .stat-icon-red    { background: var(--red-lt);     color: var(--red); }
        .stat-icon-green  { background: var(--green-lt);   color: var(--green); }
        .stat-info { flex: 1; min-width: 0; }
        .stat-num { font-family: 'Bebas Neue'; font-size: 32px; line-height: 1; letter-spacing: 1px; }
        .stat-num-blue   { color: var(--blue); }
        .stat-num-orange { color: var(--orange); }
        .stat-num-red    { color: var(--red); }
        .stat-num-green  { color: var(--green); }
        .stat-lbl { font-size: 10px; font-weight: 700; text-transform: uppercase;
            letter-spacing: 1px; color: var(--muted); margin-top: 1px; }

        /* ── PANEL ── */
        .panel { background: var(--white); border: 1px solid var(--border);
            border-radius: var(--radius); display: flex; flex-direction: column;
            overflow: hidden; position: relative; box-shadow: 0 1px 4px rgba(26,86,196,.07); }
        .panel::before { content: ''; position: absolute; top: 0; left: 0; right: 0; height: 3px;
            background: linear-gradient(90deg, var(--blue), var(--orange));
            border-radius: var(--radius) var(--radius) 0 0; }
        .panel-head { display: flex; align-items: center; justify-content: space-between;
            gap: 8px; padding: 10px 14px; border-bottom: 1px solid var(--border); flex-shrink: 0; }
        .panel-label { font-size: 10px; font-weight: 700; text-transform: uppercase;
            letter-spacing: 1.5px; color: var(--blue); }
        .badge { font-family: 'DM Mono'; font-size: 10px; padding: 2px 8px; border-radius: 20px;
            background: var(--blue-light); border: 1px solid var(--border); color: var(--blue); font-weight: 600; }
        .panel-body-flush { flex: 1; overflow: hidden; display: flex; flex-direction: column; }

        /* ── SEARCH + FILTER BAR ── */
        .toolbar { display: flex; align-items: center; gap: 8px;
            padding: 8px 12px; border-bottom: 1px solid var(--border); flex-shrink: 0; flex-wrap: wrap; }
        .search-input { flex: 1; min-width: 140px; padding: 6px 10px; border: 1px solid var(--border);
            border-radius: var(--radius); font-family: 'DM Sans'; font-size: 12px;
            background: var(--bg); color: var(--text); transition: border-color .2s; }
        .search-input:focus { outline: none; border-color: var(--blue); }
        .filter-select { padding: 6px 10px; border: 1px solid var(--border);
            border-radius: var(--radius); font-family: 'DM Sans'; font-size: 12px;
            background: var(--bg); color: var(--text); cursor: pointer; }
        .filter-select:focus { outline: none; border-color: var(--blue); }

        /* ── STOCK TABLE ── */
        .tbl-wrap { flex: 1; overflow-y: auto; overflow-x: auto; -webkit-overflow-scrolling: touch; }
        .tbl-wrap::-webkit-scrollbar { width: 4px; height: 4px; }
        .tbl-wrap::-webkit-scrollbar-thumb { background: var(--border); border-radius: 4px; }
        table { width: 100%; border-collapse: collapse; min-width: 560px; }
        thead th { position: sticky; top: 0; background: var(--blue-light);
            padding: 7px 10px; font-size: 10px; font-weight: 700; text-transform: uppercase;
            letter-spacing: 1px; color: var(--blue); text-align: left; border-bottom: 1px solid var(--border); }
        tbody tr { border-bottom: 1px solid var(--border); transition: background .15s; }
        tbody tr:hover { background: var(--blue-light); }
        tbody td { padding: 7px 10px; font-size: 12px; color: var(--text); }
        .td-mono  { font-family: 'DM Mono'; font-size: 11px; }
        .td-muted { color: var(--muted); font-size: 11px; }
        tr.hidden-row { display: none; }
        tr.row-out  td { color: var(--red); }
        tr.row-low  td:last-child { /* handled by qty badge */ }

        /* ── QTY BADGE ── */
        .qty { display: inline-flex; align-items: center; justify-content: center;
            min-width: 28px; height: 22px; padding: 0 6px; border-radius: 6px;
            font-family: 'DM Mono'; font-size: 12px; font-weight: 700; }
        .qty-ok  { background: var(--green-lt); color: var(--green); }
        .qty-low { background: #fff7ed; color: #c2410c; }
        .qty-out { background: var(--red-lt); color: var(--red); }

        /* ── ACTION BUTTONS ── */
        .btn-in, .btn-out {
            display: inline-flex; align-items: center; gap: 4px;
            padding: 4px 10px; border-radius: 6px; font-size: 11px;
            font-weight: 700; cursor: pointer; border: none; transition: opacity .2s; }
        .btn-in  { background: var(--green-lt); color: var(--green); }
        .btn-out { background: var(--orange-lt); color: var(--orange); }
        .btn-in:hover,
        .btn-out:hover { opacity: .75; }
        .btn-out:disabled { opacity: .35; cursor: not-allowed; }
        .btn-actions { display: flex; gap: 5px; }

        /* ── TRANSACTION PANEL ── */
        .trans-list { flex: 1; overflow-y: auto; -webkit-overflow-scrolling: touch; }
        .trans-list::-webkit-scrollbar { width: 4px; }
        .trans-list::-webkit-scrollbar-thumb { background: var(--border); border-radius: 4px; }
        .trans-item { display: flex; align-items: flex-start; gap: 10px;
            padding: 10px 14px; border-bottom: 1px solid var(--border);
            transition: background .15s; }
        .trans-item:hover { background: var(--bg); }
        .trans-dot { width: 8px; height: 8px; border-radius: 50%; margin-top: 4px; flex-shrink: 0; }
        .dot-in  { background: var(--green); }
        .dot-out { background: var(--orange); }
        .trans-body { flex: 1; min-width: 0; }
        .trans-name { font-size: 12px; font-weight: 600; color: var(--text);
            white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        .trans-meta { font-size: 11px; color: var(--muted); margin-top: 2px; }
        .trans-badge { flex-shrink: 0; font-family: 'DM Mono'; font-size: 11px;
            font-weight: 700; padding: 2px 7px; border-radius: 6px; }
        .trans-badge-in  { background: var(--green-lt); color: var(--green); }
        .trans-badge-out { background: var(--orange-lt); color: var(--orange); }

        /* ── MODAL ── */
        .modal-backdrop { display: none; position: fixed; inset: 0;
            background: rgba(15,30,61,.5); backdrop-filter: blur(3px);
            z-index: 100; align-items: center; justify-content: center; padding: 16px; }
        .modal-backdrop.open { display: flex; }
        .modal { background: var(--white); border-radius: 12px; width: 100%;
            max-width: 420px; box-shadow: 0 20px 60px rgba(15,30,61,.2);
            overflow: hidden; animation: modalIn .2s ease; }
        @keyframes modalIn { from { transform: scale(.95); opacity: 0; } to { transform: scale(1); opacity: 1; } }
        .modal-header { padding: 16px 20px; border-bottom: 1px solid var(--border);
            display: flex; align-items: center; justify-content: space-between; }
        .modal-title { font-family: 'Bebas Neue'; font-size: 18px; letter-spacing: 1px; }
        .modal-title-in  { color: var(--green); }
        .modal-title-out { color: var(--orange); }
        .modal-close { width: 28px; height: 28px; border-radius: 50%; border: none;
            background: var(--bg); cursor: pointer; display: flex; align-items: center;
            justify-content: center; color: var(--muted); transition: background .2s; }
        .modal-close:hover { background: var(--border); }
        .modal-body { padding: 20px; display: flex; flex-direction: column; gap: 14px; }
        .modal-item-name { font-size: 13px; font-weight: 600; color: var(--text);
            padding: 10px 12px; background: var(--bg); border-radius: 6px;
            border: 1px solid var(--border); }
        .modal-item-meta { font-size: 11px; color: var(--muted); margin-top: 3px; }
        .form-group { display: flex; flex-direction: column; gap: 5px; }
        .form-label { font-size: 10px; font-weight: 700; text-transform: uppercase;
            letter-spacing: 1px; color: var(--muted); }
        .form-input { padding: 8px 12px; border: 1px solid var(--border);
            border-radius: var(--radius); font-family: 'DM Sans'; font-size: 13px;
            color: var(--text); background: var(--white); transition: border-color .2s; }
        .form-input:focus { outline: none; border-color: var(--blue); }
        .avail-note { font-size: 11px; color: var(--muted); }
        .avail-note strong { color: var(--text); }
        .modal-footer { padding: 14px 20px; border-top: 1px solid var(--border);
            display: flex; gap: 8px; justify-content: flex-end; }
        .btn-cancel { padding: 8px 18px; border: 1px solid var(--border); border-radius: var(--radius);
            background: var(--white); color: var(--muted); font-size: 13px; font-weight: 600;
            cursor: pointer; transition: background .2s; }
        .btn-cancel:hover { background: var(--bg); }
        .btn-submit { padding: 8px 20px; border: none; border-radius: var(--radius);
            font-size: 13px; font-weight: 700; cursor: pointer; transition: opacity .2s; color: #fff; }
        .btn-submit-in  { background: var(--green); }
        .btn-submit-out { background: var(--orange); }
        .btn-submit:hover { opacity: .85; }
        .btn-submit:disabled { opacity: .5; cursor: not-allowed; }

        /* ── TOAST ── */
        .toast { position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%) translateY(80px);
            padding: 10px 20px; border-radius: 8px; font-size: 13px; font-weight: 600;
            color: #fff; z-index: 200; transition: transform .3s ease; pointer-events: none;
            white-space: nowrap; }
        .toast.show { transform: translateX(-50%) translateY(0); }
        .toast-success { background: var(--green); }
        .toast-error   { background: var(--red); }

        /* ── EMPTY ── */
        .empty-state td { text-align: center; padding: 32px; color: var(--muted); font-style: italic; }

        /* ── RESPONSIVE OVERRIDES ── */
        @media (max-width: 1023px) {
            .main {
                display: flex !important;
                flex-direction: column !important;
                height: auto !important;
                overflow: visible !important;
            }
            .stat-strip {
                grid-template-columns: repeat(2, 1fr);
            }
            .panel { min-height: 300px; }
            .tbl-wrap { max-height: 360px; }
            .trans-list { max-height: 300px; }
        }
        @media (max-width: 600px) {
            .stat-strip { grid-template-columns: repeat(2, 1fr); gap: 8px; }
            .stat-num { font-size: 26px; }
            .stat-icon { width: 30px; height: 30px; }
            .toolbar { gap: 6px; }
            .filter-select { width: 100%; }
            .modal { max-width: 100%; margin: 0; border-radius: 12px 12px 0 0;
                position: fixed; bottom: 0; left: 0; right: 0; }
            .modal-backdrop { align-items: flex-end; padding: 0; }
        }

        /* ── DISPATCH MOBILE OVERRIDES ── */
        @media (max-width: 767px) {
            .btn-refresh { font-size: 30px; }
            .item_class {font-size: 30px;}
            .stat-icon   { width: 50px; height: 50px; }
            .stat-num    { font-size: 70px; }
            .pannel  { min-height: 300px;}
            .panel-label { font-size: 40px !important; }
            .stat-lbl { font-size: 30px !important; }
            .badge       { font-size: 30px !important; }
            .search-input  { font-size: 35px !important; }
            .page-title  { font-size: 40px !important; }
            .topbar  { height: 80px; }
            .filter-select { font-size: 35px !important;}
            thead th     { font-size: 30px !important; }
            .qty     { font-size: 30px !important; }
            .btn-in     { font-size: 30px !important; }
            .btn-out     { font-size: 30px !important; }
            .td-mono     { font-size: 30px !important; }
            .td-muted     { font-size: 30px !important; }
            .tbody td     { font-size: 30px !important; }
            .trans-name    { font-size: 40px !important; }
            .trans-meta    { font-size: 40px !important; }
            .trans-badge    { font-size: 40px !important; }
        }
    </style>
    <link rel="stylesheet" href="/app/dashboard/dashboard_responsive.css">
</head>
<body>
<div class="shell">

    <!-- TOPBAR -->
    <header class="topbar">
        <div class="topbar-left">
            <div class="logo-mark"></div>
            <span class="page-title">WORKSHOP <span>STOCK</span></span>
            <div class="divider-v"></div>
            <span class="role-badge">Workshop</span>
            <span class="user-name"><?= w_esc($username) ?></span>
        </div>
        <a class="btn-refresh" href="?">
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/>
                <path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/>
            </svg>
            Refresh
        </a>
    </header>

    <main class="main">

        <!-- ── STAT STRIP ── -->
        <div class="stat-strip">

            <div class="stat-tile stat-tile-blue">
                <div class="stat-icon stat-icon-blue">
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="2" y="3" width="20" height="14" rx="2"/><path d="M8 21h8M12 17v4"/></svg>
                </div>
                <div class="stat-info">
                    <div class="stat-num stat-num-blue"><?= $total_items ?></div>
                    <div class="stat-lbl">Total Items</div>
                </div>
            </div>

            <div class="stat-tile stat-tile-green">
                <div class="stat-icon stat-icon-green">
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="20 6 9 17 4 12"/></svg>
                </div>
                <div class="stat-info">
                    <div class="stat-num stat-num-green"><?= $today_count ?></div>
                    <div class="stat-lbl">Transactions Today</div>
                </div>
            </div>

            <div class="stat-tile stat-tile-orange">
                <div class="stat-icon stat-icon-orange">
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>
                </div>
                <div class="stat-info">
                    <div class="stat-num stat-num-orange"><?= $low_count ?></div>
                    <div class="stat-lbl">Low Stock (≤1)</div>
                </div>
            </div>

            <div class="stat-tile stat-tile-red">
                <div class="stat-icon stat-icon-red">
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
                </div>
                <div class="stat-info">
                    <div class="stat-num stat-num-red"><?= $out_count ?></div>
                    <div class="stat-lbl">Out of Stock</div>
                </div>
            </div>

        </div>

        <!-- ── STOCK TABLE PANEL ── -->
        <div class="panel">
            <div class="panel-head">
                <span class="panel-label">Stock Items</span>
                <span class="badge" id="stock-count"><?= $total_items ?> items</span>
            </div>
            <div class="panel-body-flush">
                <div class="toolbar">
                    <input type="text" class="search-input" placeholder="Search item, stock no, type…"
                           oninput="filterStock(this)">
                    <select class="filter-select" onchange="filterStock(this)" id="qty-filter">
                        <option value="all">All stock</option>
                        <option value="low">Low / Out</option>
                        <option value="ok">In stock</option>
                    </select>
                    <select class="filter-select" onchange="filterStock(this)" id="type-filter">
                        <option value="">All types</option>
                        <?php
                        $types = array_unique(array_filter(array_column($all_stock, 'type_name')));
                        sort($types);
                        foreach ($types as $t): ?>
                        <option value="<?= w_esc($t) ?>"><?= w_esc($t) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="tbl-wrap">
                    <table id="stock-table">
                        <thead>
                            <tr>
                                <th>Stock No</th>
                                <th>Item Name</th>
                                <th class="hide-mobile">Type</th>
                                <th class="hide-mobile">Size</th>
                                <th>Qty</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody id="stock-tbody">
                        <?php if (empty($all_stock)): ?>
                            <tr class="empty-state"><td colspan="6">No stock items found</td></tr>
                        <?php else: foreach ($all_stock as $item):
                            $qty    = (int) $item['qty'];
                            $qcls   = $qty <= 0 ? 'qty-out' : ($qty <= 1 ? 'qty-low' : 'qty-ok');
                            $rowcls = $qty <= 0 ? 'row-out' : '';
                            $disabled = $qty <= 0 ? 'disabled' : '';
                        ?>
                            <tr class="stock-row <?= $rowcls ?>"
                                data-id="<?= (int)$item['record_id'] ?>"
                                data-name="<?= w_esc($item['item_name']) ?>"
                                data-stockno="<?= w_esc($item['stock_no']) ?>"
                                data-type="<?= w_esc($item['type_name'] ?? '') ?>"
                                data-size="<?= w_esc($item['size'] ?? '') ?>"
                                data-unit="<?= w_esc($item['unit_of_measure'] ?? '') ?>"
                                data-qty="<?= $qty ?>"
                                data-search="<?= w_esc(strtolower($item['item_name'].' '.$item['stock_no'].' '.($item['type_name']??'').' '.($item['size']??''))) ?>">
                                <td class="td-mono"><?= w_esc($item['stock_no']) ?></td>
                                <td><strong class="item_class"><?= w_esc($item['item_name']) ?></strong>
                                    <?php if ($item['serial_number']): ?>
                                    <div class="td-muted td-mono"><?= w_esc($item['serial_number']) ?></div>
                                    <?php endif; ?>
                                </td>
                                <td class="td-muted hide-mobile"><?= w_esc($item['type_name'] ?? '—') ?></td>
                                <td class="td-muted hide-mobile"><?= w_esc($item['size'] ?? '—') ?></td>
                                <td><span class="qty <?= $qcls ?>"><?= $qty ?></span></td>
                                <td>
                                    <div class="btn-actions">
                                        <button class="btn-in"
                                                onclick="openModal('in', this.closest('tr'))">
                                            <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
                                            In
                                        </button>
                                        <button class="btn-out" <?= $disabled ?>
                                                onclick="openModal('out', this.closest('tr'))">
                                            <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="5" y1="12" x2="19" y2="12"/></svg>
                                            Out
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- ── RECENT TRANSACTIONS PANEL ── -->
        <div class="panel">
            <div class="panel-head">
                <span class="panel-label">Recent Transactions</span>
                <span class="badge" id="trans-count"><?= count($transactions) ?></span>
            </div>
            <div class="trans-list" id="trans-list">
            <?php if (empty($transactions)): ?>
                <div style="padding:24px;text-align:center;color:var(--muted);font-size:12px">No transactions yet</div>
            <?php else: foreach ($transactions as $t):
                $is_in  = strtoupper($t['status']) === 'IN';
                $dotcls = $is_in ? 'dot-in' : 'dot-out';
                $badcls = $is_in ? 'trans-badge-in' : 'trans-badge-out';
                $label  = $is_in ? '+' . $t['quantity'] : '−' . $t['quantity'];
                $dt     = substr($t['datetime_created'] ?? '', 0, 16);
            ?>
                <div class="trans-item">
                    <span class="trans-dot <?= $dotcls ?>"></span>
                    <div class="trans-body">
                        <div class="trans-name"><?= w_esc($t['item_name']) ?></div>
                        <div class="trans-meta">
                            <?= w_esc($t['stock_no']) ?>
                            <?php if ($t['order_no']): ?> · Order <?= w_esc($t['order_no']) ?><?php endif; ?>
                            <br><?= w_esc($dt) ?>
                        </div>
                    </div>
                    <span class="trans-badge <?= $badcls ?>"><?= $label ?></span>
                </div>
            <?php endforeach; endif; ?>
            </div>
        </div>

    </main>
</div><!-- /shell -->

<!-- ═══ MODAL ═══════════════════════════════════════════ -->
<div class="modal-backdrop" id="modal-backdrop" onclick="closeModal(event)">
    <div class="modal">
        <div class="modal-header">
            <span class="modal-title" id="modal-title">Check In</span>
            <button class="modal-close" onclick="closeModal()">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
            </button>
        </div>
        <div class="modal-body">
            <div>
                <div class="modal-item-name" id="modal-item-name">—</div>
                <div class="modal-item-meta" id="modal-item-meta"></div>
            </div>

            <div class="avail-note" id="modal-avail"></div>

            <div class="form-group">
                <label class="form-label">Quantity</label>
                <input type="number" class="form-input" id="modal-qty"
                       min="1" value="1" placeholder="Enter quantity">
            </div>

            <div class="form-group" id="order-group">
                <label class="form-label">Order / Job Reference <span style="color:var(--muted)">(optional)</span></label>
                <input type="text" class="form-input" id="modal-order"
                       placeholder="e.g. JC-123 or PO-456">
            </div>
        </div>
        <div class="modal-footer">
            <button class="btn-cancel" onclick="closeModal()">Cancel</button>
            <button class="btn-submit" id="modal-submit" onclick="submitTransaction()">Confirm</button>
        </div>
    </div>
</div>

<!-- ═══ TOAST ════════════════════════════════════════════ -->
<div class="toast" id="toast"></div>

<script>
let currentAction = null;
let currentRow    = null;

// ── MODAL OPEN ────────────────────────────────────────────
function openModal(action, row) {
    currentAction = action;
    currentRow    = row;

    const name   = row.dataset.name;
    const stockno= row.dataset.stockno;
    const size   = row.dataset.size;
    const unit   = row.dataset.unit;
    const qty    = parseInt(row.dataset.qty);
    const type   = row.dataset.type;

    const isIn   = action === 'in';
    const title  = document.getElementById('modal-title');
    const submit = document.getElementById('modal-submit');

    title.textContent  = isIn ? 'Check In Stock' : 'Check Out Stock';
    title.className    = 'modal-title ' + (isIn ? 'modal-title-in' : 'modal-title-out');
    submit.className   = 'btn-submit ' + (isIn ? 'btn-submit-in' : 'btn-submit-out');
    submit.textContent = isIn ? 'Check In' : 'Check Out';

    document.getElementById('modal-item-name').textContent = name;
    document.getElementById('modal-item-meta').textContent =
        [stockno, type, size, unit].filter(Boolean).join(' · ');

    const avail = document.getElementById('modal-avail');
    avail.innerHTML = isIn
        ? `Current stock: <strong>${qty}</strong>`
        : `Available: <strong>${qty}</strong> ${unit || ''}`;

    document.getElementById('order-group').style.display = isIn ? 'none' : 'flex';
    document.getElementById('modal-qty').value   = 1;
    document.getElementById('modal-qty').max     = isIn ? 9999 : qty;
    document.getElementById('modal-order').value = '';

    document.getElementById('modal-backdrop').classList.add('open');
    setTimeout(() => document.getElementById('modal-qty').focus(), 100);
}

function closeModal(e) {
    if (e && e.target !== document.getElementById('modal-backdrop')) return;
    document.getElementById('modal-backdrop').classList.remove('open');
    currentAction = null;
    currentRow    = null;
}

// ── SUBMIT TRANSACTION ────────────────────────────────────
function submitTransaction() {
    const qty     = parseInt(document.getElementById('modal-qty').value);
    const orderNo = document.getElementById('modal-order').value.trim();
    const stockId = currentRow.dataset.id;
    const submit  = document.getElementById('modal-submit');

    if (!qty || qty < 1) { showToast('Enter a valid quantity', 'error'); return; }

    submit.disabled     = true;
    submit.textContent  = 'Saving…';

    const fd = new FormData();
    fd.append('action',   currentAction);
    fd.append('stock_id', stockId);
    fd.append('quantity', qty);
    fd.append('order_no', orderNo);

    fetch('/app/dashboard/ajax/workshop_transaction.ajax.php', { method:'POST', body: fd })
        .then(r => r.json())
        .then(res => {
            submit.disabled    = false;
            submit.textContent = currentAction === 'in' ? 'Check In' : 'Check Out';

            if (!res.ok) {
                showToast(res.error || 'Transaction failed', 'error');
                return;
            }

            // ── UPDATE ROW IN TABLE ───────────────────────
            const newQty  = res.new_qty;
            currentRow.dataset.qty = newQty;

            const qtyBadge = currentRow.querySelector('.qty');
            qtyBadge.textContent = newQty;
            qtyBadge.className   = 'qty ' + qtyClass(newQty);

            // Enable/disable Out button
            const outBtn = currentRow.querySelector('.btn-out');
            outBtn.disabled = newQty <= 0;

            // Row highlight
            currentRow.classList.toggle('row-out', newQty <= 0);

            // ── PREPEND TRANSACTION TO LIST ───────────────
            prependTransaction({
                item_name:        res.item,
                stock_no:         currentRow.dataset.stockno,
                quantity:         qty,
                status:           currentAction === 'in' ? 'IN' : 'BOOKED',
                order_no:         orderNo,
                datetime_created: new Date().toISOString().slice(0,16).replace('T',' ')
            });

            const msg = currentAction === 'in'
                ? `+${qty} checked in — ${res.item}`
                : `${qty} checked out — ${res.item}`;
            showToast(msg, 'success');
            document.getElementById('modal-backdrop').classList.remove('open');
        })
        .catch(() => {
            submit.disabled = false;
            showToast('Network error — try again', 'error');
        });
}

// ── PREPEND TRANSACTION ───────────────────────────────────
function prependTransaction(t) {
    const list  = document.getElementById('trans-list');
    const isIn  = t.status === 'IN';
    const label = isIn ? '+' + t.quantity : '−' + t.quantity;

    const el = document.createElement('div');
    el.className = 'trans-item';
    el.style.animation = 'modalIn .3s ease';
    el.innerHTML = `
        <span class="trans-dot ${isIn ? 'dot-in' : 'dot-out'}"></span>
        <div class="trans-body">
            <div class="trans-name">${esc(t.item_name)}</div>
            <div class="trans-meta">
                ${esc(t.stock_no)}
                ${t.order_no ? ' · Order ' + esc(t.order_no) : ''}
                <br>${esc(t.datetime_created)}
            </div>
        </div>
        <span class="trans-badge ${isIn ? 'trans-badge-in' : 'trans-badge-out'}">${label}</span>`;

    // Remove empty state if present
    const empty = list.querySelector('div[style]');
    if (empty) empty.remove();

    list.prepend(el);

    // Update trans count badge
    const cnt = list.querySelectorAll('.trans-item').length;
    document.getElementById('trans-count').textContent = cnt;
}

// ── FILTER / SEARCH ───────────────────────────────────────
function filterStock(input) {
    const q       = document.querySelector('.search-input').value.toLowerCase();
    const qtyF    = document.getElementById('qty-filter').value;
    const typeF   = document.getElementById('type-filter').value.toLowerCase();
    let   visible = 0;

    document.querySelectorAll('.stock-row').forEach(row => {
        const matchSearch = !q || row.dataset.search.includes(q);
        const qty         = parseInt(row.dataset.qty);
        const matchQty    = qtyF === 'all'
            || (qtyF === 'low' && qty <= 1)
            || (qtyF === 'ok'  && qty > 1);
        const matchType   = !typeF || row.dataset.type.toLowerCase() === typeF;
        const show        = matchSearch && matchQty && matchType;
        row.classList.toggle('hidden-row', !show);
        if (show) visible++;
    });
    document.getElementById('stock-count').textContent = visible + ' items';
}

// ── HELPERS ───────────────────────────────────────────────
function qtyClass(q) {
    return q <= 0 ? 'qty-out' : q <= 1 ? 'qty-low' : 'qty-ok';
}

function showToast(msg, type) {
    const t = document.getElementById('toast');
    t.textContent  = msg;
    t.className    = 'toast toast-' + type + ' show';
    setTimeout(() => t.classList.remove('show'), 3000);
}

function esc(s) {
    return String(s ?? '').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
}

// Keyboard: Enter to submit, Escape to close
document.addEventListener('keydown', e => {
    if (!document.getElementById('modal-backdrop').classList.contains('open')) return;
    if (e.key === 'Enter')  submitTransaction();
    if (e.key === 'Escape') closeModal();
});
</script>
</body>
</html>