<?php
/*
|--------------------------------------------------------------------------
| company/sp_part_request_queue.php — Request Form Queue (stock control).
| Shows ALL requests for the company. Only staff with Manage access to the
| Request Form module can see it (assign via Assign Access).
|--------------------------------------------------------------------------
*/
ob_start(); session_start();
require_once '../config/database.php';
require_once '../config/modules.php';
require_once '../config/module_access.php';
require_once '../config/part_request_flow.php';
if (!isset($_SESSION['user_id']) || empty($_SESSION['company_id'])) { header('Location: ../auth/login.php'); exit; }
$companyId=(int)$_SESSION['company_id']; $userId=(int)$_SESSION['user_id']; $role=$_SESSION['role']??''; $companyName=$_SESSION['company_name']??'Company';
$enabled=company_enabled_modules($pdo,$companyId);
if(!module_on($enabled,'part_request')){http_response_code(403);exit('Request Form is not enabled for your company.');}
if(!function_exists('esc')){function esc($v){return htmlspecialchars((string)$v,ENT_QUOTES,'UTF-8');}}
pr_ensure_schema($pdo);
$prole=pr_role($pdo,$companyId,$userId,$role);
if(!pr_can_queue($prole)){http_response_code(403);exit('You do not have access to the Request Queue. Ask your admin to give you a Packing, Stock or Manager role.');}

// Which stages does this person handle?
$seePacking = in_array($prole,['packing','manager'],true); // NEW requests -> build packing list
$seeStock   = in_array($prole,['stock','manager'],true);   // PACKED requests -> hand over / complete

// Load all requests, split by stage
$baseSel = "SELECT r.*, (SELECT COUNT(*) FROM sp_part_request_items i WHERE i.request_id=r.id AND i.company_id=r.company_id) AS item_count
            FROM sp_part_requests r WHERE r.company_id=? ORDER BY r.id DESC";
$qAll=$pdo->prepare($baseSel); $qAll->execute([$companyId]);
$newReqs=[]; $packedReqs=[]; $readyReqs=[]; $doneReqs=[];
foreach($qAll->fetchAll(PDO::FETCH_ASSOC) as $r){
    switch(pr_stage($r['status'])){
        case 'completed': $doneReqs[]=$r; break;
        case 'ready':     $readyReqs[]=$r; break;
        case 'packed':    $packedReqs[]=$r; break;
        default:          $newReqs[]=$r;
    }
}

/* Render one stage table. */
function pr_queue_table(array $rows, string $rowBg, string $numClass, string $emptyMsg){
    ?>
    <div class="table-scroll">
        <table>
            <thead>
                <tr>
                    <th style="width:44px;">#</th>
                    <th>Req No</th><th>Date</th><th>Machine No</th><th>Customer</th>
                    <th>Issued By</th><th>Items</th><th>Status</th>
                </tr>
            </thead>
            <tbody>
                <?php if ($rows): $n=0; foreach ($rows as $r): $n++;
                        list($bLabel,$bFg,$bBg)=pr_status_badge($r['status']);
                        $link='sp_part_request_view.php?id='.(int)$r['id'];
                    ?>
                    <tr class="qrow" style="background:<?= $rowBg ?>;" onclick="location.href='<?= $link ?>'">
                        <td><span class="num-pill <?= $numClass ?>"><?= $n ?></span></td>
                        <td><a class="req-no" href="<?= $link ?>"><?= esc($r['req_no']) ?></a></td>
                        <td><?= $r['req_date'] ? esc(date('d/m/Y', strtotime($r['req_date']))) : '' ?></td>
                        <td><?= esc($r['machine_no']) ?></td>
                        <td><?= esc($r['customer_name']) ?></td>
                        <td><?= esc($r['issued_by_name']) ?></td>
                        <td><span class="count-pill"><?= (int)$r['item_count'] ?></span></td>
                        <td><span class="badge" style="color:<?= $bFg ?>; background:<?= $bBg ?>;"><?= esc($bLabel) ?></span></td>
                    </tr>
                <?php endforeach; else: ?>
                    <tr><td colspan="8" style="text-align:center; padding:28px;" class="muted"><?= esc($emptyMsg) ?></td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    <?php
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Request Form Queue</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Lao:wght@400;500;600;700&family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>
        :root { --bg:#f3f6fb; --card:#fff; --ink:#111827; --muted:#64748b; --line:#e6eaf2; --brand:#2563eb; --brand2:#1d4ed8; --shadow:0 12px 30px rgba(30,41,59,.08); --shadow-sm:0 2px 6px rgba(30,41,59,.06); }
        * { box-sizing:border-box; }
        body { margin:0; font-family:'Noto Sans Lao','Inter',Arial,sans-serif; background:var(--bg); color:var(--ink); }
        .wrap { max-width:1180px; margin:0 auto; padding:10px 16px 24px; }
        .page-head { display:flex; align-items:center; justify-content:space-between; gap:14px; flex-wrap:wrap; margin-bottom:12px; }
        .page-head h1 { margin:0; font-size:22px; font-weight:800; }
        .card { background:var(--card); border:1px solid var(--line); border-radius:14px; box-shadow:var(--shadow); padding:16px 18px; margin-bottom:14px; }
        .filters { display:flex; gap:8px; flex-wrap:wrap; margin-bottom:14px; }
        .filters a { padding:8px 14px; border-radius:999px; text-decoration:none; font-weight:700; font-size:13px; border:1px solid var(--line); background:#fff; color:#475569; }
        .filters a:hover { border-color:#bfdbfe; color:var(--brand); }
        .filters a.on { background:var(--brand); color:#fff; border-color:var(--brand); }
        .table-scroll { overflow-x:auto; border-radius:12px; }
        table { width:100%; border-collapse:collapse; min-width:860px; }
        thead th { background:#f8fafc; color:var(--muted); text-transform:uppercase; font-size:11px; letter-spacing:.04em; font-weight:700; padding:11px 10px; text-align:left; border-bottom:1px solid var(--line); white-space:nowrap; }
        tbody td { padding:11px 10px; border-bottom:1px solid var(--line); font-size:13px; }
        tbody tr:hover { background:#f9fafe; cursor:pointer; }
        .req-no { font-weight:800; color:#0f172a; text-decoration:none; }
        .badge { display:inline-block; padding:3px 10px; border-radius:999px; font-size:12px; font-weight:700; }
        .muted { color:#94a3b8; }
        .count-pill { display:inline-block; min-width:24px; text-align:center; background:#eff6ff; color:#1d4ed8; border-radius:999px; padding:2px 9px; font-weight:800; font-size:12px; }
        .card-head { display:flex; align-items:center; justify-content:space-between; gap:12px; flex-wrap:wrap; margin-bottom:12px; }
        .card-head h2 { margin:0; font-size:16px; font-weight:800; display:flex; align-items:center; gap:8px; }
        .count-tag { display:inline-flex; align-items:center; justify-content:center; min-width:22px; height:22px; padding:0 7px; border-radius:999px; background:#16a34a; color:#fff; font-size:12px; font-weight:800; }
        .count-tag.amber { background:#d97706; }
        .count-tag.done { background:#94a3b8; }
        .role-chip { display:inline-block; font-size:11px; font-weight:800; letter-spacing:.05em; background:#e0e7ff; color:#3730a3; padding:3px 9px; border-radius:999px; vertical-align:middle; margin-left:6px; }
        .legend { font-size:12px; color:#64748b; display:flex; align-items:center; gap:4px; }
        .legend .dot { display:inline-block; width:11px; height:11px; border-radius:3px; margin-right:2px; }
        .legend .dot-new { background:#bbf7d0; border:1px solid #86efac; }
        .legend .dot-packed { background:#fed7aa; border:1px solid #fdba74; }
        .num-pill { display:inline-flex; align-items:center; justify-content:center; width:24px; height:24px; border-radius:7px; font-weight:800; font-size:12px; }
        .num-new { background:#16a34a; color:#fff; }
        .num-packed { background:#d97706; color:#fff; }
        .num-done { background:#e2e8f0; color:#475569; }
        .qrow:hover { filter:brightness(0.98); }
    </style>
</head>
<body>
    <div class="wrap">
        <?php $spActive='queue'; include 'sp_nav.php'; ?>

        <?php $roleTitle = ['manager'=>'Request Queue — Manager','stock'=>'Stock Queue','packing'=>'Packing Queue'][$prole] ?? 'Request Queue'; ?>
        <div class="page-head">
            <h1><?= esc($roleTitle) ?> <span class="role-chip"><?= esc(strtoupper($prole)) ?></span></h1>
            <a href="sp_part_request_form.php" class="btn" style="background:#059669;color:#fff;border:none;padding:10px 16px;border-radius:10px;font-weight:700;text-decoration:none;">+ New Form</a>
        </div>

        <?php if ($seePacking): ?>
        <!-- ===== Stage 2: NEW requests to pack ===== -->
        <div class="card">
            <div class="card-head">
                <h2>🆕 New Requests — build packing list <span class="count-tag"><?= count($newReqs) ?></span></h2>
                <span class="legend"><span class="dot dot-new"></span>Waiting for packing — click a row to make its packing list</span>
            </div>
            <?php pr_queue_table($newReqs, '#effdf3', 'num-new', 'No new requests. All caught up 🎉'); ?>
        </div>
        <?php endif; ?>

        <?php if ($seeStock): ?>
        <!-- ===== Stage 3: PACKED requests ready for stock ===== -->
        <div class="card">
            <div class="card-head">
                <h2>📦 Packed — ready for stock hand-over <span class="count-tag amber"><?= count($packedReqs) ?></span></h2>
                <span class="legend"><span class="dot dot-packed"></span>Packing list done — take parts &amp; mark completed</span>
            </div>
            <?php pr_queue_table($packedReqs, '#fff8ef', 'num-packed', 'Nothing waiting for stock right now.'); ?>
        </div>
        <?php endif; ?>

        <!-- ===== Ready for pickup (waiting on requester) ===== -->
        <div class="card">
            <div class="card-head">
                <h2>🟢 Ready — waiting for pickup <span class="count-tag"><?= count($readyReqs) ?></span></h2>
                <span class="legend">Stock done — the requester confirms receipt to complete.</span>
            </div>
            <?php pr_queue_table($readyReqs, '#effdf3', 'num-new', 'Nothing waiting for pickup.'); ?>
        </div>

        <!-- ===== Completed ===== -->
        <div class="card">
            <div class="card-head">
                <h2>✅ Request Form Completed <span class="count-tag done"><?= count($doneReqs) ?></span></h2>
            </div>
            <?php pr_queue_table($doneReqs, '#ffffff', 'num-done', 'No completed requests yet.'); ?>
        </div>
    </div>
</body>
</html>