<?php
/*
|--------------------------------------------------------------------------
| company/sp_part_requests.php — Part / Toner Request queue (list view)
|--------------------------------------------------------------------------
*/
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');
$canHandle=pr_can_queue($prole);
if(!$canView){http_response_code(403);exit('You do not have access to the Request Form. Ask your admin to assign you a role.');}
// 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
");

/* Status filter (stage based) */
$filter = strtolower(trim($_GET['status'] ?? 'all'));
$allowed = ['all','new','packed','ready','completed'];
if (!in_array($filter, $allowed, true)) { $filter = 'all'; }

$sql = "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=? AND r.issued_by_user_id=?";
$params=[$companyId,$userId];
if     ($filter === 'new')       { $sql .= " AND r.status NOT IN ('packed','ready','completed')"; }
elseif ($filter === 'packed')    { $sql .= " AND r.status='packed'"; }
elseif ($filter === 'ready')     { $sql .= " AND r.status='ready'"; }
elseif ($filter === 'completed') { $sql .= " AND r.status='completed'"; }
$sql .= " ORDER BY r.id DESC";
$st=$pdo->prepare($sql); $st->execute($params);
$requests=$st->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Request Form (Create)</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; }
        .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-add { background:#059669; } .btn-add:hover { background:#047857; }
        .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:820px; }
        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; }
    </style>
</head>
<body>
    <div class="wrap">
        <?php $spActive='create'; include 'sp_nav.php'; ?>

        <div class="page-head">
            <h1>Request Form (Create)</h1>
            <a href="sp_part_request_form.php" class="btn btn-add">+ New Form</a>
        </div>

        <p class="muted" style="margin:-4px 0 12px; font-size:13px;">Your own requests. Stock control handles them in the Queue.</p>

        <div class="card">
            <div class="filters">
                <?php
                    $tabs=['all'=>'All','new'=>'New','packed'=>'Packed','ready'=>'Ready to pick up','completed'=>'Completed'];
                    foreach($tabs as $k=>$label):
                ?>
                    <a class="<?= $filter===$k ? 'on' : '' ?>" href="sp_part_requests.php?status=<?= urlencode($k) ?>"><?= esc($label) ?></a>
                <?php endforeach; ?>
            </div>

            <div class="table-scroll">
                <table>
                    <thead>
                        <tr>
                            <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 ($requests): ?>
                            <?php foreach ($requests as $r):
                                list($bLabel,$bFg,$bBg)=pr_status_badge($r['status']);
                                $link='sp_part_request_view.php?id='.(int)$r['id'];
                                $isReady = pr_stage($r['status'])==='ready';
                            ?>
                                <tr onclick="location.href='<?= $link ?>'"<?= $isReady ? ' style="background:#effdf3;"' : '' ?>>
                                    <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>
                                        <?php if ($isReady): ?>
                                        <form method="POST" action="sp_part_request_view.php" style="display:inline;" onclick="event.stopPropagation();" onsubmit="return confirm('Confirm you received these parts?');">
                                            <input type="hidden" name="request_id" value="<?= (int)$r['id'] ?>">
                                            <button type="submit" name="receive" style="margin-left:6px;background:#16a34a;color:#fff;border:none;padding:5px 10px;border-radius:8px;font-weight:800;font-size:12px;cursor:pointer;">✅ Received</button>
                                        </form>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr><td colspan="7" style="text-align:center; padding:28px;" class="muted">No requests<?= $filter!=='all' ? ' with this status' : ' yet' ?>. Click <strong>+ New Form</strong> to create one.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</body>
</html>