<?php
/* ============================================================================
 *  company/hr_dept_check.php — DIAGNOSTIC (admin only).
 *  Checks that staff department values match the department list, and that
 *  each department has a manager. Helps debug leave-approval routing.
 *  Safe to delete after use.
 * ==========================================================================*/
session_start();
if (!isset($_SESSION["user_id"]) || ($_SESSION["role"] ?? '') !== "company_admin" || empty($_SESSION["company_id"])) {
    header("Location: ../auth/login.php"); exit;
}
require_once '../config/database.php';
$companyId = (int)$_SESSION["company_id"];
function e($v){ return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }
function norm($v){ return mb_strtolower(trim((string)$v)); }

/* departments */
$departments = [];
try {
    $d = $pdo->prepare("SELECT id, name, manager_user_id FROM company_departments WHERE company_id=? ORDER BY name");
    $d->execute([$companyId]); $departments = $d->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $ex) {}
$deptNorm = [];           // normalized dept name => row
foreach ($departments as $d) { $deptNorm[norm($d['name'])] = $d; }

/* user names */
$uname = [];
try {
    $u = $pdo->prepare("SELECT u.id, u.name FROM users u JOIN company_staff cs ON cs.user_id=u.id WHERE cs.company_id=?");
    $u->execute([$companyId]);
    foreach ($u->fetchAll(PDO::FETCH_ASSOC) as $r) { $uname[(int)$r['id']] = $r['name']; }
} catch (Throwable $ex) {}

/* staff */
$staff = [];
try {
    $s = $pdo->prepare("SELECT u.id, u.name, cs.staff_code, cs.department
                        FROM company_staff cs JOIN users u ON u.id=cs.user_id
                        WHERE cs.company_id=? ORDER BY cs.staff_code");
    $s->execute([$companyId]); $staff = $s->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $ex) {}

/* pending leave rows (for the routing preview) */
$pending = [];
try {
    $p = $pdo->prepare("SELECT l.id, l.status, u.name AS staff_name, cs.staff_code, cs.department
                        FROM hr_leave l
                        JOIN users u ON u.id=l.staff_id
                        LEFT JOIN company_staff cs ON cs.user_id=l.staff_id AND cs.company_id=l.company_id
                        WHERE l.company_id=? AND l.status IN ('pending','dept_ok') ORDER BY l.id DESC");
    $p->execute([$companyId]); $pending = $p->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $ex) {}
?>
<!DOCTYPE html><html lang="en"><head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>Department check</title>
<style>
    body{font-family:Inter,Arial,sans-serif;background:#f0f4f8;color:#0f172a;margin:0;padding:20px;}
    .wrap{max-width:900px;margin:auto;}
    h1{font-size:20px;} h2{font-size:15px;margin:22px 0 8px;}
    a.back{color:#2563eb;text-decoration:none;font-weight:700;}
    table{width:100%;border-collapse:collapse;background:#fff;border:1px solid #e2e8f0;border-radius:10px;overflow:hidden;font-size:13px;margin-bottom:8px;}
    th{background:#f8fafc;text-align:left;padding:8px 10px;font-size:11px;text-transform:uppercase;color:#64748b;border-bottom:1px solid #e2e8f0;}
    td{padding:8px 10px;border-bottom:1px solid #eef2f7;}
    .ok{color:#16a34a;font-weight:700;} .bad{color:#dc2626;font-weight:800;} .warn{color:#d97706;font-weight:700;}
    code{background:#eef2f7;padding:1px 6px;border-radius:5px;}
    .pill{display:inline-block;background:#dcfce7;color:#166534;padding:1px 8px;border-radius:999px;font-size:11px;font-weight:700;}
    .pill.no{background:#fee2e2;color:#b91c1c;}
</style></head><body>
<div class="wrap">
<p><a class="back" href="dashboard.php">&larr; Back</a></p>
<h1>🔍 Department &amp; approval routing check</h1>

<h2>1) Departments &amp; their managers</h2>
<table>
    <thead><tr><th>Department (exact)</th><th>Manager set?</th><th>Manager</th></tr></thead>
    <tbody>
    <?php if(!$departments): ?><tr><td colspan="3" class="bad">No departments defined.</td></tr><?php endif; ?>
    <?php foreach($departments as $d): $mid=(int)$d['manager_user_id']; ?>
        <tr>
            <td><code><?= e($d['name']) ?></code></td>
            <td><?= $mid>0 ? '<span class="pill">yes</span>' : '<span class="pill no">NO MANAGER</span>' ?></td>
            <td><?= $mid>0 ? e($uname[$mid] ?? ('user #'.$mid)) : '—' ?></td>
        </tr>
    <?php endforeach; ?>
    </tbody>
</table>

<h2>2) Each staff → does their department match a defined department?</h2>
<table>
    <thead><tr><th>Code</th><th>Name</th><th>Staff department value</th><th>Matches list?</th></tr></thead>
    <tbody>
    <?php foreach($staff as $s):
        $dep = (string)$s['department'];
        $exact = false; $normMatch = false;
        foreach($departments as $d){ if($d['name']===$dep) $exact=true; }
        $normMatch = isset($deptNorm[norm($dep)]);
        if ($dep==='') { $status='<span class="warn">no department</span>'; }
        elseif ($exact) { $status='<span class="ok">✔ exact match</span>'; }
        elseif ($normMatch) { $status='<span class="warn">⚠ matches only after trim/case — fix spelling</span>'; }
        else { $status='<span class="bad">✗ NO MATCH in department list</span>'; }
    ?>
        <tr>
            <td><?= e($s['staff_code']) ?></td>
            <td><?= e($s['name']) ?></td>
            <td><?= $dep==='' ? '<em>(empty)</em>' : '<code>'.e($dep).'</code>' ?></td>
            <td><?= $status ?></td>
        </tr>
    <?php endforeach; ?>
    </tbody>
</table>

<h2>3) Pending leave requests → who will be asked to approve?</h2>
<table>
    <thead><tr><th>Req</th><th>Staff</th><th>Department</th><th>Routed to (department manager)</th></tr></thead>
    <tbody>
    <?php if(!$pending): ?><tr><td colspan="4">No pending requests.</td></tr><?php endif; ?>
    <?php foreach($pending as $p):
        $dep=(string)$p['department'];
        $row = $deptNorm[norm($dep)] ?? null;
        if ($dep==='') { $route='<span class="warn">no department → only admin / Operation Manager</span>'; }
        elseif (!$row) { $route='<span class="bad">department not in list → nobody (stuck)</span>'; }
        elseif ((int)$row['manager_user_id']<=0) { $route='<span class="bad">no manager set for '.e($row['name']).'</span>'; }
        else { $route='<span class="ok">'.e($uname[(int)$row['manager_user_id']] ?? ('user #'.$row['manager_user_id'])).'</span>'; }
    ?>
        <tr>
            <td>#<?= (int)$p['id'] ?></td>
            <td><?= e($p['staff_name']) ?> <?= $p['staff_code']?'('.e($p['staff_code']).')':'' ?></td>
            <td><?= $dep==='' ? '<em>(empty)</em>' : '<code>'.e($dep).'</code>' ?></td>
            <td><?= $route ?></td>
        </tr>
    <?php endforeach; ?>
    </tbody>
</table>

<p style="color:#64748b;font-size:12px;margin-top:20px;">Delete this file (<code>company/hr_dept_check.php</code>) after checking.</p>
</div>
</body></html>