<?php
/*
|--------------------------------------------------------------------------
| company/sp_map_staff.php
| Map each OLD service_portal staff -> a NEW Seven Credit user, and transfer
| that old staff's existing job assignments to the chosen new user.
| Matching of jobs is done by job_no (unique), so it works after the jobs
| import. Also records the mapping onto service_portal.staff.seven_staff_code
| so future imports remember it.
|--------------------------------------------------------------------------
*/
ob_start();
session_start();
require_once '../config/database.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'); } }

$SP = 'anousone_service_portal';
$message = '';
$error   = '';

/* New users of this company (dropdown target) */
$newUsers = [];
try {
    $st = $pdo->prepare("SELECT u.id, u.name, cs.staff_code
                         FROM company_staff cs JOIN users u ON u.id = cs.user_id
                         WHERE cs.company_id = ? ORDER BY u.name ASC");
    $st->execute([$companyId]);
    $newUsers = $st->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) { $error = 'Could not load company users: ' . $e->getMessage(); }
$userCode = [];
foreach ($newUsers as $u) { $userCode[(int)$u['id']] = $u['staff_code']; }

/* Apply mapping: transfer assignments */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_map'])) {
    try {
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $map = (array)($_POST['map'] ?? []);

        $jobsByStaff = $pdo->prepare("
            SELECT j.job_no
            FROM {$SP}.job_staff_assignments a
            JOIN {$SP}.jobs j ON j.id = a.job_id
            WHERE a.staff_id = ?
        ");
        $findJob   = $pdo->prepare("SELECT id FROM sp_jobs WHERE company_id=? AND job_no=? LIMIT 1");
        $existsAsg = $pdo->prepare("SELECT 1 FROM sp_job_staff WHERE company_id=? AND job_id=? AND user_id=? LIMIT 1");
        $insAsg    = $pdo->prepare("INSERT INTO sp_job_staff (company_id, job_id, user_id) VALUES (?,?,?)");
        $tagStaff  = $pdo->prepare("UPDATE {$SP}.staff SET seven_staff_code=? WHERE id=?");

        $transferred = 0; $mappedStaff = 0;
        foreach ($map as $oldStaffId => $newUserId) {
            $oldStaffId = (int)$oldStaffId; $newUserId = (int)$newUserId;
            if ($oldStaffId <= 0 || $newUserId <= 0) continue;
            $mappedStaff++;

            // remember the mapping on the old staff row (if the new user has a code)
            if (!empty($userCode[$newUserId])) {
                try { $tagStaff->execute([$userCode[$newUserId], $oldStaffId]); } catch (Throwable $e) {}
            }

            $jobsByStaff->execute([$oldStaffId]);
            foreach ($jobsByStaff->fetchAll(PDO::FETCH_COLUMN) as $jobNo) {
                $findJob->execute([$companyId, $jobNo]);
                $newJobId = (int)($findJob->fetchColumn() ?: 0);
                if (!$newJobId) continue;
                $existsAsg->execute([$companyId, $newJobId, $newUserId]);
                if ($existsAsg->fetchColumn()) continue;
                $insAsg->execute([$companyId, $newJobId, $newUserId]);
                $transferred++;
            }
        }
        $message = "Mapped {$mappedStaff} staff and transferred {$transferred} job assignment(s).";
    } catch (Throwable $e) {
        $error = $e->getMessage();
    }
}

/* Old service_portal staff + assignment counts + current mapping */
$oldStaff = [];
try {
    $oldStaff = $pdo->query("
        SELECT s.id, s.username, s.full_name, s.seven_staff_code,
               (SELECT COUNT(*) FROM {$SP}.job_staff_assignments a WHERE a.staff_id = s.id) AS job_count
        FROM {$SP}.staff s
        ORDER BY s.full_name ASC
    ")->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    if (!$error) $error = 'Could not read service_portal staff: ' . $e->getMessage();
}

/* Which new user currently owns a given code (to preselect) */
$codeToUser = [];
foreach ($newUsers as $u) { if (!empty($u['staff_code'])) $codeToUser[$u['staff_code']] = (int)$u['id']; }
?>
<!DOCTYPE html>
<html lang="en"><head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Map Staff → New Users</title>
    <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:920px; margin:24px auto; padding:0 16px; }
        h1 { font-size:24px; font-weight:800; margin:0 0 4px; }
        .sub { color:#64748b; margin:0 0 18px; }
        .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; }
        .error { background:#fef2f2; color:#b91c1c; padding:12px 15px; border-radius:12px; margin-bottom:14px; border:1px solid #fecaca; 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; }
        select { width:100%; padding:9px 11px; border:1px solid #e2e8f0; border-radius:10px; font-size:14px; font-family:inherit; background:#fff; }
        .pill { display:inline-block; background:#eef2ff; color:#2563eb; padding:3px 9px; border-radius:999px; font-size:12px; font-weight:700; }
        .muted { color:#94a3b8; }
        .btn { background:#0f766e; color:#fff; border:none; padding:12px 20px; border-radius:12px; cursor:pointer; font-weight:700; font-size:14px; margin-top:16px; }
        .btn:hover { background:#115e59; }
    </style>
</head><body>
    <div class="topbar"><a href="dashboard.php">&larr; Back to Dashboard</a><strong><?= esc($companyName) ?></strong></div>
    <div class="wrap">
        <h1>Map Staff → New Users</h1>
        <p class="sub">For each old Service Portal staff, choose the matching person in the new system. Their existing job assignments will be transferred to that user. You can do this a few at a time — unmapped rows are left untouched.</p>

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

        <div class="card">
            <form method="POST">
                <table>
                    <thead><tr><th>Old Staff (Service Portal)</th><th>Username</th><th>Jobs</th><th>Map to New User</th></tr></thead>
                    <tbody>
                        <?php if ($oldStaff): ?>
                            <?php foreach ($oldStaff as $s):
                                $sid = (int)$s['id'];
                                $preUser = !empty($s['seven_staff_code']) && isset($codeToUser[$s['seven_staff_code']]) ? $codeToUser[$s['seven_staff_code']] : 0;
                            ?>
                                <tr>
                                    <td><strong><?= esc($s['full_name'] ?: '(no name)') ?></strong></td>
                                    <td><?= esc($s['username']) ?></td>
                                    <td><?php if ((int)$s['job_count']>0): ?><span class="pill"><?= esc($s['job_count']) ?></span><?php else: ?><span class="muted">0</span><?php endif; ?></td>
                                    <td>
                                        <select name="map[<?= $sid ?>]">
                                            <option value="">&mdash; not mapped &mdash;</option>
                                            <?php foreach ($newUsers as $u): ?>
                                                <option value="<?= (int)$u['id'] ?>" <?= $preUser === (int)$u['id'] ? 'selected' : '' ?>>
                                                    <?= esc($u['name']) ?><?= $u['staff_code'] ? ' (' . esc($u['staff_code']) . ')' : '' ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr><td colspan="4" class="muted" style="text-align:center;">No Service Portal staff found.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
                <button type="submit" name="save_map" class="btn">Save &amp; Transfer Assignments</button>
            </form>
        </div>
    </div>
</body></html>