<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
session_write_close();
date_default_timezone_set('Africa/Lagos');
require 'config.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

$username = $_SESSION['username'];
$role = $_SESSION['role'];

if (!in_array(strtolower(trim($role)), ['hr', 'admin', 'superadmin'])) {
    die("Access Denied: Administrative Clearance Required.");
}

// Read-Only queries for list loading
$departments = [];
$deptRes = $conn->query("SELECT id, name FROM departments ORDER BY name ASC");
while ($deptRes && $row = $deptRes->fetch_assoc()) { $departments[] = $row; }

$usersList = [];
$usersRes = $conn->query("
    SELECT u.*, d.name AS department_name 
    FROM users u
    LEFT JOIN departments d ON d.id = u.department_id
    ORDER BY u.id DESC
");
while ($usersRes && $row = $usersRes->fetch_assoc()) { $usersList[] = $row; }
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Identity Management - Executive HR Boardroom</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=Mulish:ital,wght=0,200..1000;1,200..1000&display=swap" rel="stylesheet">
    
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    fontFamily: {
                        sans: ['Mulish', 'sans-serif'],
                    }
                }
            }
        }
    </script>
    <link rel="stylesheet" href="components/sidebar.css">
</head>
<body class="bg-stone-100/60 min-h-screen text-slate-800 antialiased selection:bg-indigo-600 selection:text-white font-sans flex flex-col md:flex-row">

<?php include 'components/sidebar.php'; ?>

<div id="sidebar-overlay" class="fixed inset-0 bg-slate-900/40 hidden z-40 transition-opacity duration-300" onclick="toggleSidebar()"></div>

<div id="main-content" class="flex-1 min-w-0 md:pl-60 transition-all duration-300 min-h-screen flex flex-col">
    
    <!-- Context Header Panel Component -->
    <header class="sticky top-0 bg-white/90 backdrop-blur-md border-b border-slate-300/80 h-14 flex items-center justify-between px-4 sm:px-6 z-30 shadow-xs">
        <div class="flex items-center gap-3">
            <button onclick="toggleSidebar()" class="p-1.5 rounded-lg text-slate-600 hover:bg-slate-200/80 transition active:scale-95 md:hidden" aria-label="Toggle Navigation">
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M4 6h16M4 12h16M4 18h16"></path>
                </svg>
            </button>
            <div>
                <h1 class="text-sm font-black tracking-tight text-slate-950">Identity Control Panel</h1>
                <p class="text-[10px] text-indigo-700 font-bold uppercase tracking-wider">Logged in as: <?= htmlspecialchars($username); ?></p>
            </div>
        </div>
        
        <div class="flex items-center gap-2">
            <span class="inline-block px-2 py-0.5 rounded border border-indigo-200 bg-indigo-50 text-indigo-800 text-[10px] font-black uppercase tracking-wider">
                Context: <?= htmlspecialchars($role) ?>
            </span>
        </div>
    </header>

    <!-- Operational Alert Infrastructure -->
    <div class="px-4 pt-4 sm:px-6 max-w-7xl w-full mx-auto space-y-3">
        <?php if (isset($_GET['msg'])): ?>
            <div class="bg-emerald-50 border border-emerald-300 text-emerald-800 p-3 rounded text-xs font-bold">
                ✓ Profile successfully actioned: <strong class="font-black"><?= htmlspecialchars($_GET['msg']) ?></strong>.
            </div>
        <?php endif; ?>
        <?php if (isset($_GET['err'])): ?>
            <div class="bg-rose-50 border border-rose-300 text-rose-800 p-3 rounded text-xs font-bold">
                ❌ Operational Error: <?= htmlspecialchars($_GET['err']) ?>
            </div>
        <?php endif; ?>
    </div>

    <main class="flex-1 p-4 sm:p-6 max-w-7xl w-full mx-auto space-y-6">

        <!-- Form Registry Framework Component -->
        <div class="bg-white border border-slate-300/80 rounded-xl shadow-sm overflow-hidden">
            <div class="px-4 py-3 bg-stone-50/50 border-b border-slate-300/80">
                <h3 id="form-panel-title" class="text-xs font-black text-slate-950 uppercase tracking-tight">Provision Corporate User Access</h3>
            </div>
            
            <form id="profile-submission-form" action="user_controller.php" method="POST" class="p-4 sm:p-5 space-y-4">
                <input type="hidden" name="action" id="form-action-mode" value="create">
                <input type="hidden" name="user_id" id="form-target-id" value="">

                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                    <div class="space-y-1.5">
                        <label class="block text-[9px] font-black text-slate-500 uppercase tracking-wider px-0.5">Username Handle</label>
                        <input type="text" name="username" id="input-username" required placeholder="e.g j.doe" class="w-full bg-stone-50/40 border border-slate-300 p-2 rounded text-xs font-bold text-slate-950 focus:outline-none focus:border-indigo-700 focus:bg-white transition">
                    </div>
                    <div class="space-y-1.5">
                        <label class="block text-[9px] font-black text-slate-500 uppercase tracking-wider px-0.5">Password</label>
                        <input type="password" name="password" id="input-password" placeholder="••••••••" required class="w-full bg-stone-50/40 border border-slate-300 p-2 rounded text-xs font-black font-mono text-slate-950 focus:outline-none focus:border-indigo-700 focus:bg-white transition">
                        <span id="password-hint" class="block text-[10px] text-slate-500 font-semibold mt-1 hidden">Leave blank to retain password context.</span>
                    </div>
                    <div class="space-y-1.5">
                        <label class="block text-[9px] font-black text-slate-500 uppercase tracking-wider px-0.5">Functional Role</label>
                        <select name="role" id="input-role" required class="w-full bg-stone-50/40 border border-slate-300 p-2 rounded text-xs font-bold text-slate-950 focus:outline-none focus:border-indigo-700 focus:bg-white transition">
                            <option value="staff">Staff</option>
                            <option value="supervisor">Supervisor</option>
                            <option value="manager">Manager</option>
                            <option value="hr">HR</option>
                            <option value="accounts">Accounts</option>
                            <option value="audit">Audit</option>
                            <option value="gm">General Manager (GM)</option>
                            <option value="opm">Operations Manager (OPM)</option>
                            <option value="admin">Admin</option>
                            <option value="superadmin">Superadmin</option>
                        </select>
                    </div>
                    <div class="space-y-1.5">
                        <label class="block text-[9px] font-black text-slate-500 uppercase tracking-wider px-0.5">Department Bound</label>
                        <select name="department_id" id="input-dept" class="w-full bg-stone-50/40 border border-slate-300 p-2 rounded text-xs font-bold text-slate-950 focus:outline-none focus:border-indigo-700 focus:bg-white transition">
                            <option value="">No Department Boundary</option>
                            <?php foreach ($departments as $dept): ?>
                                <option value="<?= $dept['id'] ?>"><?= htmlspecialchars($dept['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>

                <div class="flex flex-wrap items-center gap-6 pt-1">
                    <label class="inline-flex items-center gap-2 text-xs font-bold text-slate-700 select-none cursor-pointer">
                        <input type="checkbox" name="must_change_password" id="input-must-change" value="1" checked class="w-3.5 h-3.5 rounded border-slate-300 text-indigo-700 focus:ring-indigo-700"> Enforce Password Reset
                    </label>
                    <label class="inline-flex items-center gap-2 text-xs font-bold text-slate-700 select-none cursor-pointer">
                        <input type="checkbox" name="can_add_staff" id="input-can-add" value="1" class="w-3.5 h-3.5 rounded border-slate-300 text-indigo-700 focus:ring-indigo-700"> Management Rights
                    </label>
                </div>

                <div class="pt-3 border-t border-slate-200/80 flex justify-between items-center">
                    <button type="button" id="cancel-edit-btn" onclick="resetFormState()" class="hidden px-4 py-1.5 rounded border border-slate-300 bg-white hover:bg-stone-100 text-slate-700 font-black text-[10px] transition uppercase tracking-wider">Cancel Modification</button>
                    <button type="submit" id="submit-action-btn" class="bg-slate-950 hover:bg-indigo-700 text-white font-black text-[10px] px-4 py-1.5 rounded shadow-xs transition uppercase tracking-wider ml-auto">Create User Directory Profile</button>
                </div>
            </form>
        </div>

        <!-- Master Data Registry Table -->
        <div class="bg-white border border-slate-300/80 rounded-xl shadow-sm overflow-hidden">
            <div class="overflow-x-auto w-full">
                <table class="w-full text-left border-collapse whitespace-nowrap">
                    <thead>
                        <tr class="bg-stone-50 border-b border-slate-300/80 text-slate-500 text-[9px] font-black uppercase tracking-wider">
                            <th class="p-3 pl-6">Username Handle</th>
                            <th class="p-3 w-40">Functional Role</th>
                            <th class="p-3">Department Scope</th>
                            <th class="p-3 text-center w-44">Enforcement</th>
                            <th class="p-3 text-center w-36 pr-6">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-200/80 text-xs font-bold">
                        <?php foreach ($usersList as $row): ?>
                            <tr class="hover:bg-stone-50/50 transition-colors text-slate-800">
                                <td class="p-3 pl-6 font-black text-slate-950 tracking-tight">@<?= htmlspecialchars($row['username']) ?></td>
                                <td class="p-3">
                                    <span class="inline-block px-2 py-0.5 rounded border border-slate-300 bg-stone-50 text-slate-700 text-[10px] font-black uppercase tracking-wider">
                                        <?= htmlspecialchars($row['role']) ?>
                                    </span>
                                </td>
                                <td class="p-3 font-semibold text-slate-600">
                                    <?= $row['department_name'] ? htmlspecialchars($row['department_name']) : '<span class="italic text-slate-400 font-normal">Global</span>' ?>
                                </td>
                                <td class="p-3 text-center">
                                    <?php if ($row['must_change_password']): ?>
                                        <span class="inline-block px-2 py-0.5 rounded border border-amber-300 bg-amber-50 text-amber-900 text-[10px] font-black uppercase tracking-wider">⚠️ Reset Required</span>
                                    <?php else: ?>
                                        <span class="inline-block px-2 py-0.5 rounded border border-emerald-300 bg-emerald-50 text-emerald-800 text-[10px] font-black uppercase tracking-wider">✓ Ready</span>
                                    <?php endif; ?>
                                </td>
                                <td class="p-3 text-center pr-6 flex justify-center items-center gap-3">
                                    <button type="button" 
                                            data-id="<?= $row['id'] ?>"
                                            data-username="<?= htmlspecialchars($row['username']) ?>"
                                            data-role="<?= htmlspecialchars($row['role']) ?>"
                                            data-dept="<?= $row['department_id'] ?>"
                                            data-mustchange="<?= $row['must_change_password'] ?>"
                                            data-canadd="<?= $row['can_add_staff'] ?>"
                                            onclick="initiateFormModification(this)"
                                            class="text-indigo-700 hover:text-indigo-900 hover:underline font-black uppercase tracking-wider text-[10px]">Edit</button>
                                    
                                    <form action="user_controller.php" method="POST" onsubmit="return confirm('Confirm permanent removal of account directory entry?');" class="inline">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="user_id" value="<?= $row['id'] ?>">
                                        <button type="submit" class="text-rose-600 hover:text-rose-800 hover:underline font-black uppercase tracking-wider text-[10px]">Delete</button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

    </main>

    <footer class="mt-auto border-t border-slate-300 bg-white px-6 py-4 text-center">
        <p class="text-[9px] text-slate-500 font-mono tracking-wider">&copy; 2026 Core HR Engine System Platform • Dynamic Secure Architecture Protocol.</p>
    </footer>
</div>

<script src="components/sidebar.js"></script>
<script>
function initiateFormModification(btn) {
    const data = btn.dataset;

    document.getElementById('form-panel-title').innerText = "Modify Operational Security Parameters: @" + data.username;
    document.getElementById('form-action-mode').value = "update";
    document.getElementById('form-target-id').value = data.id;

    document.getElementById('input-username').value = data.username;
    document.getElementById('input-role').value = data.role;
    document.getElementById('input-dept').value = data.dept || "";
    
    document.getElementById('input-must-change').checked = parseInt(data.mustchange) === 1;
    document.getElementById('input-can-add').checked = parseInt(data.canadd) === 1;

    // Adjusting password input constraints for update flow
    const pwdInput = document.getElementById('input-password');
    pwdInput.required = false;
    pwdInput.placeholder = "Overwrite Password (Optional)";
    document.getElementById('password-hint').classList.remove('hidden');

    document.getElementById('cancel-edit-btn').classList.remove('hidden');
    
    const submitBtn = document.getElementById('submit-action-btn');
    submitBtn.innerText = "Commit Account Modification";
    
    window.scrollTo({ top: 0, behavior: 'smooth' });
}

function resetFormState() {
    document.getElementById('form-panel-title').innerText = "Provision Corporate User Access";
    document.getElementById('form-action-mode').value = "create";
    document.getElementById('form-target-id').value = "";
    document.getElementById('profile-submission-form').reset();

    const pwdInput = document.getElementById('input-password');
    pwdInput.required = true;
    pwdInput.placeholder = "••••••••";
    document.getElementById('password-hint').classList.add('hidden');

    document.getElementById('cancel-edit-btn').classList.add('hidden');
    document.getElementById('submit-action-btn').innerText = "Create User Directory Profile";
}
</script>
</body>
</html>