<?php
/*
|--------------------------------------------------------------------------
| company/sp_part_request_view.php — view a Part / Toner Request + fulfil
|--------------------------------------------------------------------------
*/
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'; $userName=$_SESSION['name']??'Staff';
$enabled=company_enabled_modules($pdo,$companyId);
if(!module_on($enabled,'part_request')){http_response_code(403);exit('Part/Toner Request 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);
$canView=($prole!=='none');
$canPack=pr_can_pack($prole);
$canStock=pr_can_stock($prole);
$canHandle=pr_can_queue($prole); // packing/stock/manager
if(!$canView){http_response_code(403);exit('You do not have access to the Request Form.');}
// current staff code
$myCode=''; try{ $s=$pdo->prepare("SELECT staff_code FROM company_staff WHERE company_id=? AND user_id=? LIMIT 1"); $s->execute([$companyId,$userId]); $myCode=(string)($s->fetchColumn()?:''); }catch(Throwable $e){}

/* Tables (idempotent) */
$pdo->exec("
  CREATE TABLE IF NOT EXISTS sp_part_requests (
    id INT AUTO_INCREMENT PRIMARY KEY,
    company_id INT NOT NULL,
    req_no VARCHAR(40) DEFAULT NULL,
    req_date DATE DEFAULT NULL,
    machine_no VARCHAR(100) DEFAULT NULL,
    sd_no VARCHAR(50) DEFAULT NULL,
    customer_name VARCHAR(255) DEFAULT NULL,
    location VARCHAR(255) DEFAULT NULL,
    issued_by_user_id INT DEFAULT NULL,
    issued_by_code VARCHAR(50) DEFAULT NULL,
    issued_by_name VARCHAR(255) DEFAULT NULL,
    ack_manager VARCHAR(255) DEFAULT NULL,
    note TEXT,
    packing_no VARCHAR(100) DEFAULT NULL,
    status VARCHAR(20) NOT NULL DEFAULT 'open',
    handled_by_user_id INT DEFAULT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    INDEX(company_id,status)
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
");
$pdo->exec("
  CREATE TABLE IF NOT EXISTS sp_part_request_items (
    id INT AUTO_INCREMENT PRIMARY KEY,
    company_id INT NOT NULL,
    request_id INT NOT NULL,
    order_code VARCHAR(100) DEFAULT NULL,
    part_details VARCHAR(500) DEFAULT NULL,
    color VARCHAR(20) DEFAULT NULL,
    qty INT NOT NULL DEFAULT 0,
    barcode VARCHAR(150) DEFAULT NULL,
    note VARCHAR(255) DEFAULT NULL,
    done TINYINT(1) NOT NULL DEFAULT 0,
    INDEX(company_id,request_id)
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
");

$id=(int)($_GET['id'] ?? 0);
$flash='';

/* Verify a request belongs to this company; returns its status or null. */
function pr_req_status(PDO $pdo,int $rid,int $companyId){
    $chk=$pdo->prepare("SELECT status FROM sp_part_requests WHERE id=? AND company_id=? LIMIT 1");
    $chk->execute([$rid,$companyId]);
    $s=$chk->fetchColumn();
    return $s===false ? null : (string)$s;
}

/* Stage 2 — Packing person builds the packing list -> status 'packed'. */
if (isset($_POST['pack'])) {
    if (!$canPack) { http_response_code(403); exit('You do not have permission to create packing lists.'); }
    $rid=(int)($_POST['request_id'] ?? 0);
    $cur=pr_req_status($pdo,$rid,$companyId);
    if ($cur!==null && pr_stage($cur)==='new') {
        $ur=$pdo->prepare("UPDATE sp_part_requests
                           SET packing_no=?, packing_note=?, status='packed', packed_by_user_id=?, packed_at=NOW()
                           WHERE id=? AND company_id=?");
        $ur->execute([trim($_POST['packing_no'] ?? ''), trim($_POST['packing_note'] ?? ''), $userId, $rid, $companyId]);
    }
    header('Location: sp_part_request_view.php?id='.$rid.'&msg=packed'); exit;
}

/* Stage 3 — Stock person takes parts -> status 'ready' (waiting for creator to pick up). */
if (isset($_POST['complete'])) {
    if (!$canStock) { http_response_code(403); exit('You do not have permission to complete requests.'); }
    $rid=(int)($_POST['request_id'] ?? 0);
    $cur=pr_req_status($pdo,$rid,$companyId);
    if ($cur!==null && pr_stage($cur)==='packed') {
        // mark which items were taken (optional checkboxes)
        $itq=$pdo->prepare("SELECT id FROM sp_part_request_items WHERE request_id=? AND company_id=?");
        $itq->execute([$rid,$companyId]);
        $ids=array_map('intval',$itq->fetchAll(PDO::FETCH_COLUMN));
        $doneMap=$_POST['done'] ?? [];
        $upd=$pdo->prepare("UPDATE sp_part_request_items SET done=? WHERE id=? AND request_id=? AND company_id=?");
        foreach ($ids as $iid) { $upd->execute([isset($doneMap[$iid])?1:0,$iid,$rid,$companyId]); }
        $ur=$pdo->prepare("UPDATE sp_part_requests
                           SET status='ready', ready_by_user_id=?, ready_at=NOW(), handled_by_user_id=?
                           WHERE id=? AND company_id=?");
        $ur->execute([$userId, $userId, $rid, $companyId]);
        // notify the creator that parts are ready to pick up
        $iq=$pdo->prepare("SELECT issued_by_user_id, req_no FROM sp_part_requests WHERE id=? AND company_id=? LIMIT 1");
        $iq->execute([$rid,$companyId]); $ir=$iq->fetch(PDO::FETCH_ASSOC);
        if ($ir && (int)$ir['issued_by_user_id']>0 && file_exists(__DIR__.'/../config/notify.php')) {
            require_once __DIR__.'/../config/notify.php';
            if (function_exists('notify_user')) notify_user($pdo,(int)$ir['issued_by_user_id'],"📦 Parts ready to pick up","Request ".$ir['req_no']." is ready — collect your parts and confirm receipt.","company/sp_part_requests.php");
        }
    }
    header('Location: sp_part_request_view.php?id='.$rid.'&msg=ready'); exit;
}

/* Stage 4 — Creator confirms they received the parts -> status 'completed'. */
if (isset($_POST['receive'])) {
    $rid=(int)($_POST['request_id'] ?? 0);
    $q=$pdo->prepare("SELECT status, issued_by_user_id FROM sp_part_requests WHERE id=? AND company_id=? LIMIT 1");
    $q->execute([$rid,$companyId]); $row=$q->fetch(PDO::FETCH_ASSOC);
    if ($row && pr_stage($row['status'])==='ready' && ((int)$row['issued_by_user_id']===$userId || $canHandle)) {
        $pdo->prepare("UPDATE sp_part_requests
                       SET status='completed', received_by_user_id=?, received_at=NOW(),
                           completed_by_user_id=COALESCE(completed_by_user_id,?), completed_at=COALESCE(completed_at,NOW())
                       WHERE id=? AND company_id=?")->execute([$userId,$userId,$rid,$companyId]);
    }
    header('Location: sp_part_request_view.php?id='.$rid.'&msg=received'); exit;
}

/* Send a request one stage back (manager/stock can bounce it). */
if (isset($_POST['reopen'])) {
    if (!$canHandle) { http_response_code(403); exit('No permission.'); }
    $rid=(int)($_POST['request_id'] ?? 0);
    $cur=pr_req_status($pdo,$rid,$companyId);
    if ($cur!==null && pr_stage($cur)!=='new') {
        $st=pr_stage($cur);
        $back = $st==='completed' ? 'ready' : ($st==='ready' ? 'packed' : 'open');
        $pdo->prepare("UPDATE sp_part_requests SET status=? WHERE id=? AND company_id=?")->execute([$back,$rid,$companyId]);
    }
    header('Location: sp_part_request_view.php?id='.$rid.'&msg=reopened'); exit;
}
$flash = $_GET['msg'] ?? '';

/* Load request */
$req=null;
if ($id>0) {
    $rq=$pdo->prepare("SELECT * FROM sp_part_requests WHERE id=? AND company_id=? LIMIT 1");
    $rq->execute([$id,$companyId]);
    $req=$rq->fetch(PDO::FETCH_ASSOC);
}
if (!$req) { http_response_code(404); exit('Request not found.'); }

$itq=$pdo->prepare("SELECT * FROM sp_part_request_items WHERE request_id=? AND company_id=? ORDER BY id ASC");
$itq->execute([$id,$companyId]);
$items=$itq->fetchAll(PDO::FETCH_ASSOC);

$stage=pr_stage($req['status']);
list($bLabel,$bFg,$bBg)=pr_status_badge($req['status']);
// who did what
$packedByName=''; $completedByName='';
try {
    if (!empty($req['packed_by_user_id'])) { $s=$pdo->prepare("SELECT name FROM users WHERE id=? LIMIT 1"); $s->execute([(int)$req['packed_by_user_id']]); $packedByName=(string)($s->fetchColumn()?:''); }
    if (!empty($req['completed_by_user_id'])) { $s=$pdo->prepare("SELECT name FROM users WHERE id=? LIMIT 1"); $s->execute([(int)$req['completed_by_user_id']]); $completedByName=(string)($s->fetchColumn()?:''); }
} catch (Throwable $e) {}
// who marked ready / who received
$readyByName=''; $receivedByName='';
try {
    if (!empty($req['ready_by_user_id']))    { $s=$pdo->prepare("SELECT name FROM users WHERE id=? LIMIT 1"); $s->execute([(int)$req['ready_by_user_id']]);    $readyByName=(string)($s->fetchColumn()?:''); }
    if (!empty($req['received_by_user_id'])) { $s=$pdo->prepare("SELECT name FROM users WHERE id=? LIMIT 1"); $s->execute([(int)$req['received_by_user_id']]); $receivedByName=(string)($s->fetchColumn()?:''); }
} catch (Throwable $e) {}
// can THIS user act on THIS request's current stage?
$isCreator = ((int)($req['issued_by_user_id'] ?? 0) === $userId);
$actPack    = $canPack  && $stage==='new';
$actStock   = $canStock && $stage==='packed';
$actReceive = ($isCreator || $canHandle) && $stage==='ready';   // creator confirms pickup
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Request <?= esc($req['req_no']) ?></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; display:flex; align-items:center; gap:12px; }
        .card { background:var(--card); border:1px solid var(--line); border-radius:14px; box-shadow:var(--shadow); padding:16px 18px; margin-bottom:14px; }
        .section-title { font-size:13px; font-weight:800; text-transform:uppercase; letter-spacing:.04em; color:var(--muted); margin:2px 0 12px; }
        .btn { background:var(--brand); color:#fff; border:none; padding:10px 16px; border-radius:10px; cursor:pointer; font-weight:700; text-decoration:none; display:inline-flex; align-items:center; gap:6px; font-size:14px; font-family:inherit; }
        .btn:hover { background:var(--brand2); }
        .btn-clear { background:#eef2f7; color:#475569; } .btn-clear:hover { background:#e2e8f0; }
        .badge { display:inline-block; padding:4px 12px; border-radius:999px; font-size:13px; font-weight:700; }
        .meta-grid { display:grid; grid-template-columns:repeat(3,1fr); gap:14px; }
        .meta .k { font-size:11px; color:var(--muted); font-weight:700; text-transform:uppercase; letter-spacing:.03em; }
        .meta .v { font-size:15px; font-weight:600; margin-top:3px; word-break:break-word; }
        .meta .v.empty { color:#cbd5e1; font-weight:500; }
        .table-scroll { overflow-x:auto; border-radius:12px; }
        table { width:100%; border-collapse:collapse; min-width:820px; }
        thead th { background:#f8fafc; color:var(--muted); text-transform:uppercase; font-size:11px; letter-spacing:.04em; font-weight:700; padding:10px 8px; text-align:left; border-bottom:1px solid var(--line); white-space:nowrap; }
        tbody td { padding:9px 8px; border-bottom:1px solid var(--line); font-size:13px; }
        .field label { display:block; font-size:12px; font-weight:700; color:var(--muted); text-transform:uppercase; letter-spacing:.03em; margin-bottom:5px; }
        .field input { padding:10px 12px; border:1px solid #e2e8f0; border-radius:10px; font-size:14px; font-family:inherit; background:#fff; }
        .chk { width:18px; height:18px; }
        .yes { color:#16a34a; font-weight:800; } .no { color:#dc2626; font-weight:800; }
        .muted { color:#94a3b8; }
        .flash { background:#ecfdf5; border:1px solid #a7f3d0; color:#047857; padding:12px 16px; border-radius:12px; font-weight:700; margin-bottom:14px; }
        .pack-note { background:#fff7ed; border:1px solid #fed7aa; color:#9a3412; padding:10px 14px; border-radius:10px; font-size:13px; margin-bottom:12px; }
        .flow { display:flex; align-items:flex-start; gap:6px; }
        .flow-step { flex:0 0 auto; width:120px; text-align:center; }
        .flow-step .fs-dot { width:42px; height:42px; margin:0 auto 6px; border-radius:50%; display:flex; align-items:center; justify-content:center; font-size:18px; font-weight:800; border:2px solid #e2e8f0; background:#f8fafc; color:#94a3b8; }
        .flow-step .fs-t { font-size:13px; font-weight:800; color:#94a3b8; }
        .flow-step .fs-s { font-size:11px; color:#cbd5e1; margin-top:2px; }
        .flow-step.done .fs-dot { background:#dcfce7; border-color:#16a34a; color:#16a34a; }
        .flow-step.done .fs-t { color:#166534; } .flow-step.done .fs-s { color:#4ade80; }
        .flow-step.cur .fs-dot { background:#2563eb; border-color:#2563eb; color:#fff; box-shadow:0 0 0 4px #dbeafe; }
        .flow-step.cur .fs-t { color:#1e40af; } .flow-step.cur .fs-s { color:#60a5fa; }
        .flow-line { flex:1; height:3px; background:#e2e8f0; margin-top:20px; border-radius:2px; min-width:24px; }
        .flow-line.done { background:#16a34a; }
        .flow-meta { display:flex; gap:18px; flex-wrap:wrap; margin-top:14px; font-size:12px; color:#475569; }
        @media (max-width:800px){ .meta-grid { grid-template-columns:1fr 1fr; } }
    </style>
</head>
<body>
    <div class="wrap">
        <?php $spActive = $canHandle ? 'queue' : 'create'; include 'sp_nav.php'; ?>

        <div class="page-head">
            <h1>
                <?= esc($req['req_no']) ?>
                <span class="badge" style="color:<?= $bFg ?>; background:<?= $bBg ?>;"><?= esc($bLabel) ?></span>
            </h1>
            <a href="<?= $canHandle ? 'sp_part_request_queue.php' : 'sp_part_requests.php' ?>" class="btn btn-clear">&larr; Back to <?= $canHandle ? 'queue' : 'list' ?></a>
        </div>

        <?php if ($flash): $fmap=['packed'=>'Packing list saved — sent to Stock.','ready'=>'Marked ready — the requester has been notified to pick up.','received'=>'Received confirmed. Request completed. 🎉','completed'=>'Request completed. 🎉','reopened'=>'Request moved back one stage.']; if(isset($fmap[$flash])): ?>
            <div class="flash"><?= esc($fmap[$flash]) ?></div>
        <?php endif; endif; ?>

        <div class="card">
            <div class="section-title">Request details</div>
            <div class="meta-grid">
                <div class="meta"><div class="k">Date</div><div class="v <?= $req['req_date']?'':'empty' ?>"><?= $req['req_date'] ? esc(date('d/m/Y', strtotime($req['req_date']))) : '—' ?></div></div>
                <div class="meta"><div class="k">Machine No</div><div class="v <?= !empty($req['machine_no'])?'':'empty' ?>"><?= !empty($req['machine_no']) ? esc($req['machine_no']) : '—' ?></div></div>
                <div class="meta"><div class="k">Machine Model</div><div class="v <?= !empty($req['machine_model'])?'':'empty' ?>"><?= !empty($req['machine_model']) ? esc($req['machine_model']) : '—' ?></div></div>
                <div class="meta"><div class="k">Serial No</div><div class="v <?= !empty($req['serial_no'])?'':'empty' ?>"><?= !empty($req['serial_no']) ? esc($req['serial_no']) : '—' ?></div></div>
                <div class="meta"><div class="k">Customer</div><div class="v <?= !empty($req['customer_name'])?'':'empty' ?>"><?= !empty($req['customer_name']) ? esc($req['customer_name']) : '—' ?></div></div>
                <div class="meta"><div class="k">SD No</div><div class="v <?= !empty($req['sd_no'])?'':'empty' ?>"><?= !empty($req['sd_no']) ? esc($req['sd_no']) : '—' ?></div></div>
                <div class="meta"><div class="k">Location</div><div class="v <?= !empty($req['location'])?'':'empty' ?>"><?= !empty($req['location']) ? esc($req['location']) : '—' ?></div></div>
                <div class="meta"><div class="k">Issued by</div><div class="v"><?= esc($req['issued_by_code']) ?><?= !empty($req['issued_by_code']) && !empty($req['issued_by_name']) ? ' — ' : '' ?><?= esc($req['issued_by_name']) ?></div></div>
                <div class="meta"><div class="k">Acknowledged by</div><div class="v <?= !empty($req['ack_manager'])?'':'empty' ?>"><?= !empty($req['ack_manager']) ? esc($req['ack_manager']) : '—' ?></div></div>
                <div class="meta"><div class="k">Packing No</div><div class="v <?= !empty($req['packing_no'])?'':'empty' ?>"><?= !empty($req['packing_no']) ? esc($req['packing_no']) : '—' ?></div></div>
                <div class="meta" style="grid-column:1 / -1;"><div class="k">Note</div><div class="v <?= !empty($req['note'])?'':'empty' ?>"><?= !empty($req['note']) ? nl2br(esc($req['note'])) : '—' ?></div></div>
            </div>
        </div>

        <!-- Workflow progress -->
        <?php $order=['new'=>0,'packed'=>1,'ready'=>2,'completed'=>3]; $ci=$order[$stage]; $lastStep=3; ?>
        <div class="card">
            <div class="section-title">Workflow status</div>
            <div class="flow">
                <?php
                $steps=[['🧾','Requested','Created by issuer'],['📦','Packed','Packing list made'],['🟢','Ready','Pick up your parts'],['✅','Received','Confirmed by requester']];
                foreach ($steps as $i=>$stp):
                    $cls = $i<$ci ? 'done' : ($i===$ci ? 'cur' : 'todo');
                ?>
                    <div class="flow-step <?= $cls ?>">
                        <div class="fs-dot"><?= $i<$ci ? '✓' : $stp[0] ?></div>
                        <div class="fs-t"><?= esc($stp[1]) ?></div>
                        <div class="fs-s"><?= esc($stp[2]) ?></div>
                    </div>
                    <?php if ($i<$lastStep): ?><div class="flow-line <?= $i<$ci ? 'done':'' ?>"></div><?php endif; ?>
                <?php endforeach; ?>
            </div>
            <div class="flow-meta">
                <?php if ($packedByName!=='' || !empty($req['packed_at'])): ?>
                    <span>📦 Packed by <strong><?= esc($packedByName ?: '—') ?></strong><?= !empty($req['packed_at']) ? ' · '.esc(date('d/m/Y H:i', strtotime($req['packed_at']))) : '' ?></span>
                <?php endif; ?>
                <?php if ($readyByName!=='' || !empty($req['ready_at'])): ?>
                    <span>🟢 Ready by <strong><?= esc($readyByName ?: '—') ?></strong><?= !empty($req['ready_at']) ? ' · '.esc(date('d/m/Y H:i', strtotime($req['ready_at']))) : '' ?></span>
                <?php endif; ?>
                <?php if ($receivedByName!=='' || !empty($req['received_at'])): ?>
                    <span>✅ Received by <strong><?= esc($receivedByName ?: '—') ?></strong><?= !empty($req['received_at']) ? ' · '.esc(date('d/m/Y H:i', strtotime($req['received_at']))) : '' ?></span>
                <?php endif; ?>
            </div>
        </div>

        <?php if ($actPack): ?>
        <!-- Stage 2: Packing person builds packing list -->
        <form method="POST">
            <input type="hidden" name="request_id" value="<?= (int)$req['id'] ?>">
            <div class="card">
                <div class="section-title">📦 Create packing list</div>
                <div class="table-scroll">
                    <table>
                        <thead><tr><th>Order Code</th><th>Part Details</th><th>Type</th><th>Color</th><th>Qty</th><th>Barcode</th><th>Note</th></tr></thead>
                        <tbody>
                            <?php if ($items): foreach ($items as $it): ?>
                                <tr>
                                    <td><strong><?= esc($it['order_code']) ?></strong></td>
                                    <td><?= esc($it['part_details']) ?></td>
                                    <td><?= esc($it['type'] ?? '') ?></td>
                                    <td><?= esc($it['color']) ?></td>
                                    <td><?= (int)$it['qty'] ?></td>
                                    <td><?= esc($it['barcode']) ?></td>
                                    <td><?= esc($it['note']) ?></td>
                                </tr>
                            <?php endforeach; else: ?>
                                <tr><td colspan="7" style="text-align:center; padding:20px;" class="muted">No items on this request.</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
                <div style="display:flex; gap:14px; align-items:flex-end; flex-wrap:wrap; margin-top:14px;">
                    <div class="field"><label>Packing No</label><input type="text" name="packing_no" value="<?= esc($req['packing_no']) ?>" placeholder="Packing no"></div>
                    <div class="field" style="flex:1; min-width:220px;"><label>Packing note (optional)</label><input type="text" name="packing_note" value="<?= esc($req['packing_note'] ?? '') ?>" placeholder="Anything the stock person should know" style="width:100%;"></div>
                    <button type="submit" name="pack" class="btn" style="background:#d97706;">✅ Save packing list → Send to Stock</button>
                </div>
                <div class="muted" style="font-size:12px; margin-top:8px;">This sends the request to the <strong>Stock</strong> person's queue.</div>
            </div>
        </form>

        <?php elseif ($actStock): ?>
        <!-- Stage 3: Stock person hands over & completes -->
        <form method="POST">
            <input type="hidden" name="request_id" value="<?= (int)$req['id'] ?>">
            <div class="card">
                <div class="section-title">📤 Take parts from stock &amp; hand over</div>
                <?php if (!empty($req['packing_no']) || !empty($req['packing_note'])): ?>
                    <div class="pack-note">Packing No: <strong><?= esc($req['packing_no'] ?: '—') ?></strong><?= !empty($req['packing_note']) ? ' · '.esc($req['packing_note']) : '' ?></div>
                <?php endif; ?>
                <div class="table-scroll">
                    <table>
                        <thead><tr><th>Order Code</th><th>Part Details</th><th>Type</th><th>Color</th><th>Qty</th><th>Barcode</th><th>Note</th><th style="text-align:center;">Taken</th></tr></thead>
                        <tbody>
                            <?php if ($items): foreach ($items as $it): ?>
                                <tr>
                                    <td><strong><?= esc($it['order_code']) ?></strong></td>
                                    <td><?= esc($it['part_details']) ?></td>
                                    <td><?= esc($it['type'] ?? '') ?></td>
                                    <td><?= esc($it['color']) ?></td>
                                    <td><?= (int)$it['qty'] ?></td>
                                    <td><?= esc($it['barcode']) ?></td>
                                    <td><?= esc($it['note']) ?></td>
                                    <td style="text-align:center;"><input class="chk" type="checkbox" name="done[<?= (int)$it['id'] ?>]" value="1" <?= (int)$it['done']===1 ? 'checked' : '' ?>></td>
                                </tr>
                            <?php endforeach; else: ?>
                                <tr><td colspan="8" style="text-align:center; padding:20px;" class="muted">No items on this request.</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
                <div style="display:flex; gap:10px; align-items:center; flex-wrap:wrap; margin-top:14px;">
                    <button type="submit" name="complete" class="btn" style="background:#16a34a;">🟢 Mark Ready for Pickup</button>
                    <button type="submit" name="reopen" class="btn btn-clear" onclick="return confirm('Send this request back to Packing?');">↩ Send back to Packing</button>
                </div>
                <div class="muted" style="font-size:12px; margin-top:8px;">Tick the parts you took, then mark ready. The requester is notified to pick up and confirm receipt. Stock quantities are managed in the Stock module.</div>
            </div>
        </form>

        <?php elseif ($actReceive): ?>
        <!-- Stage 4: Creator confirms they received the parts -->
        <form method="POST">
            <input type="hidden" name="request_id" value="<?= (int)$req['id'] ?>">
            <div class="card" style="border:1.5px solid #86efac; background:#f0fdf4;">
                <div class="section-title" style="color:#166534;">🟢 Ready to pick up</div>
                <div style="font-size:14px; color:#166534; margin-bottom:12px;">Your parts are ready. Collect them, then confirm you received them to complete this request.</div>
                <div class="table-scroll">
                    <table>
                        <thead><tr><th>Order Code</th><th>Part Details</th><th>Type</th><th>Color</th><th>Qty</th><th>Barcode</th><th>Note</th></tr></thead>
                        <tbody>
                            <?php if ($items): foreach ($items as $it): ?>
                                <tr>
                                    <td><strong><?= esc($it['order_code']) ?></strong></td>
                                    <td><?= esc($it['part_details']) ?></td>
                                    <td><?= esc($it['type'] ?? '') ?></td>
                                    <td><?= esc($it['color']) ?></td>
                                    <td><?= (int)$it['qty'] ?></td>
                                    <td><?= esc($it['barcode']) ?></td>
                                    <td><?= esc($it['note']) ?></td>
                                </tr>
                            <?php endforeach; else: ?>
                                <tr><td colspan="7" style="text-align:center; padding:20px;" class="muted">No items on this request.</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
                <div style="display:flex; gap:10px; align-items:center; flex-wrap:wrap; margin-top:14px;">
                    <button type="submit" name="receive" class="btn" style="background:#16a34a;" onclick="return confirm('Confirm you received these parts?');">✅ I received the parts</button>
                    <?php if ($canHandle): ?><button type="submit" name="reopen" class="btn btn-clear" onclick="return confirm('Send back to Stock?');">↩ Send back to Stock</button><?php endif; ?>
                </div>
            </div>
        </form>

        <?php else: ?>
        <!-- Read-only view -->
        <div class="card">
            <div class="section-title">Items</div>
            <div class="table-scroll">
                <table>
                    <thead><tr><th>Order Code</th><th>Part Details</th><th>Type</th><th>Color</th><th>Qty</th><th>Barcode</th><th>Note</th><th style="text-align:center;">Taken</th></tr></thead>
                    <tbody>
                        <?php if ($items): foreach ($items as $it): ?>
                            <tr>
                                <td><strong><?= esc($it['order_code']) ?></strong></td>
                                <td><?= esc($it['part_details']) ?></td>
                                <td><?= esc($it['type'] ?? '') ?></td>
                                <td><?= esc($it['color']) ?></td>
                                <td><?= (int)$it['qty'] ?></td>
                                <td><?= esc($it['barcode']) ?></td>
                                <td><?= esc($it['note']) ?></td>
                                <td style="text-align:center;"><?= (int)$it['done']===1 ? '<span class="yes">&#10003;</span>' : '<span class="no">&#10007;</span>' ?></td>
                            </tr>
                        <?php endforeach; else: ?>
                            <tr><td colspan="8" style="text-align:center; padding:20px;" class="muted">No items on this request.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
            <?php if ($canHandle && $stage==='completed'): ?>
                <form method="POST" style="margin-top:12px;">
                    <input type="hidden" name="request_id" value="<?= (int)$req['id'] ?>">
                    <button type="submit" name="reopen" class="btn btn-clear" onclick="return confirm('Re-open this completed request (back to Stock)?');">↩ Re-open</button>
                </form>
            <?php endif; ?>
        </div>
        <?php endif; ?>

        <a href="<?= $canHandle ? 'sp_part_request_queue.php' : 'sp_part_requests.php' ?>" class="btn btn-clear">&larr; Back to <?= $canHandle ? 'queue' : 'list' ?></a>
    </div>
</body>
</html>