<?php
/*
|--------------------------------------------------------------------------
| company/module_access_form.php
| Company admin assigns, per staff, who can MANAGE (edit) a module vs
| VIEW only. Any company staff can view; ticking "Can edit" grants manage.
|--------------------------------------------------------------------------
*/
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']) || ($_SESSION['role'] ?? '') !== 'company_admin' || empty($_SESSION['company_id'])) {
    header('Location: ../auth/login.php');
    exit;
}
$companyId   = (int)$_SESSION['company_id'];
$companyName = $_SESSION['company_name'] ?? 'Company';

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

$modules   = available_modules();
$moduleKey = $_GET['m'] ?? 'customer';
if (!isset($modules[$moduleKey])) { $moduleKey = 'customer'; }
$moduleLabel = $modules[$moduleKey]['en'] ?? $moduleKey;

$message = '';

$isPipeline = ($moduleKey === 'part_request');

/* Save assignments */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_access'])) {
    $levels = (array)($_POST['access'] ?? []);
    $staff = $pdo->prepare("SELECT user_id FROM company_staff WHERE company_id=?");
    $staff->execute([$companyId]);
    foreach ($staff->fetchAll(PDO::FETCH_COLUMN) as $uid) {
        $uid = (int)$uid;
        $lvl = $levels[$uid] ?? 'none';
        if ($isPipeline) {
            if (!in_array($lvl, ['none','requester','packing','stock','manager'], true)) { $lvl = 'none'; }
            pr_set_role($pdo, $companyId, $uid, $lvl);
        } else {
            if (!in_array($lvl, ['none','view','edit','manage'], true)) { $lvl = 'none'; }
            mod_set_access($pdo, $companyId, $uid, $moduleKey, $lvl);
        }
    }
    $message = 'Access updated for ' . $moduleLabel . '.';
}

/* Staff of this company + current edit map */
$st = $pdo->prepare("
    SELECT u.id, u.name, cs.staff_code, cs.staff_role
    FROM company_staff cs
    JOIN users u ON u.id = cs.user_id
    WHERE cs.company_id = ?
    ORDER BY (cs.staff_code IS NULL OR cs.staff_code='') ASC, cs.staff_code ASC, u.name ASC
");
$st->execute([$companyId]);
$staffList = $st->fetchAll(PDO::FETCH_ASSOC);
$accessMap = $isPipeline ? pr_role_map($pdo, $companyId) : mod_access_map($pdo, $companyId, $moduleKey);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Assign Access - <?= esc($moduleLabel) ?></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>
        * { box-sizing: border-box; }
        body { margin:0; font-family:'Noto Sans Lao','Inter',Arial,sans-serif; background:#eef2f9; color:#0f172a; }
        .topbar { background:#0f172a; color:#fff; padding:14px 20px; display:flex; align-items:center; gap:16px; }
        .topbar a { color:#93c5fd; text-decoration:none; font-weight:600; }
        .wrap { max-width:820px; margin:24px auto; padding:0 16px; }
        h1 { font-size:24px; font-weight:800; margin:0 0 4px; }
        .sub { color:#64748b; margin:0 0 18px; }
        .tabs { display:flex; gap:8px; margin-bottom:16px; }
        .tabs a { padding:8px 14px; border-radius:999px; border:1px solid #dbe3ee; background:#fff; text-decoration:none; color:#475569; font-weight:700; font-size:14px; }
        .tabs a.active { background:#2563eb; color:#fff; border-color:#2563eb; }
        .card { background:#fff; border:1px solid #e6eaf2; border-radius:18px; box-shadow:0 12px 30px rgba(30,41,59,.08); padding:22px; }
        .message { background:#ecfdf5; color:#047857; padding:12px 15px; border-radius:12px; margin-bottom:14px; border:1px solid #a7f3d0; font-weight:600; }
        table { width:100%; border-collapse:collapse; }
        thead th { text-align:left; font-size:11px; text-transform:uppercase; letter-spacing:.04em; color:#64748b; padding:10px; border-bottom:1px solid #e6eaf2; }
        tbody td { padding:12px 10px; border-bottom:1px solid #eef2f7; font-size:14px; }
        .pill { display:inline-block; background:#dcfce7; color:#166534; padding:3px 9px; border-radius:6px; font-weight:700; font-size:12px; }
        .role-admin { background:#eff6ff; color:#1e40af; }
        .muted { color:#94a3b8; }
        input[type=checkbox] { width:20px; height:20px; }
        .btn { background:#2563eb; color:#fff; border:none; padding:12px 20px; border-radius:12px; cursor:pointer; font-weight:700; font-size:14px; margin-top:16px; }
        .btn:hover { background:#1d4ed8; }
        .legend { font-size:13px; color:#64748b; margin-top:6px; }
    </style>
</head>
<body>
    <div class="topbar">
        <a href="dashboard.php">&larr; Back to Dashboard</a>
        <strong><?= esc($companyName) ?></strong>
    </div>

    <div class="wrap">
        <h1>Assign Access</h1>
        <?php if ($isPipeline): ?>
        <p class="sub">Set each staff member's <strong>role in the Request Form workflow</strong>. The request flows <strong>Requester → Packing → Stock</strong>, and each person gets a notification when work reaches their stage.<br>
        <strong>Requester</strong>: create requests only. &nbsp; <strong>Packing</strong>: see new requests &amp; build the packing list. &nbsp; <strong>Stock</strong>: see packed requests, hand over &amp; complete. &nbsp; <strong>Manager</strong>: do every stage.</p>
        <?php else: ?>
        <p class="sub">Choose each staff member's access to <strong><?= esc($moduleLabel) ?></strong> only. <strong>No access</strong> hides the module from them; <strong>View</strong> is read-only; <strong>Manage</strong> allows add/edit/delete. This is set per module, so Customer and Stock are independent.</p>
        <?php endif; ?>

        <div class="tabs">
            <?php foreach (['customer','stock','jobs','part_request'] as $k): if (!isset($modules[$k])) continue; ?>
                <a href="module_access_form.php?m=<?= $k ?>" class="<?= $k === $moduleKey ? 'active' : '' ?>"><?= esc($modules[$k]['en']) ?></a>
            <?php endforeach; ?>
        </div>

        <?php if ($message): ?><div class="message"><?= esc($message) ?></div><?php endif; ?>

        <div class="card">
            <form method="POST">
                <table>
                    <thead>
                        <tr><th>Staff</th><th>Code</th><th>Role</th><th style="text-align:center;">Access to <?= esc($moduleLabel) ?></th></tr>
                    </thead>
                    <tbody>
                        <?php if ($staffList): ?>
                            <?php foreach ($staffList as $s): $uid=(int)$s['id']; $isAdmin=($s['staff_role']==='admin'); $cur=$accessMap[$uid] ?? 'none'; ?>
                                <tr>
                                    <td><strong><?= esc($s['name']) ?></strong></td>
                                    <td><?= $s['staff_code'] ? esc($s['staff_code']) : '<span class="muted">&mdash;</span>' ?></td>
                                    <td><?php if ($isAdmin): ?><span class="pill role-admin">admin</span><?php else: ?><span class="muted">staff</span><?php endif; ?></td>
                                    <td style="text-align:center;">
                                        <?php if ($isAdmin): ?>
                                            <span class="pill">full (admin)</span>
                                        <?php else: ?>
                                            <select name="access[<?= $uid ?>]" class="lvl">
                                                <option value="none" <?= $cur==='none' ? 'selected' : '' ?>>No access</option>
                                                <?php if ($isPipeline): ?>
                                                    <option value="requester" <?= $cur==='requester' ? 'selected' : '' ?>>Requester — create only</option>
                                                    <option value="packing" <?= $cur==='packing' ? 'selected' : '' ?>>Packing — make packing list</option>
                                                    <option value="stock" <?= $cur==='stock' ? 'selected' : '' ?>>Stock — hand over &amp; complete</option>
                                                    <option value="manager" <?= $cur==='manager' ? 'selected' : '' ?>>Manager — all stages</option>
                                                <?php elseif ($moduleKey === 'jobs'): ?>
                                                    <option value="edit" <?= $cur==='edit' ? 'selected' : '' ?>>Staff — see &amp; edit own jobs</option>
                                                    <option value="manage" <?= $cur==='manage' ? 'selected' : '' ?>>Manage — admin (all jobs)</option>
                                                <?php else: ?>
                                                    <option value="view" <?= $cur==='view' ? 'selected' : '' ?>>View only</option>
                                                    <option value="manage" <?= ($cur==='manage'||$cur==='edit') ? 'selected' : '' ?>>Manage (add/edit/delete)</option>
                                                <?php endif; ?>
                                            </select>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr><td colspan="4" class="muted" style="text-align:center;">No staff in this company yet.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
                <button type="submit" name="save_access" class="btn">Save Access</button>
                <div class="legend">Company admins can always manage every module.</div>
            </form>
        </div>
    </div>
</body>
</html>