<?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;
}

$role = strtolower(trim((string)($_SESSION['role'] ?? 'staff')));
$activeTab = htmlspecialchars($_GET['tab'] ?? 'department');

// Fetch Organization Datasets
$departments = [];
$resDepts = $conn->query("SELECT * FROM departments ORDER BY name");
while ($row = $resDepts->fetch_assoc()) { $departments[] = $row; }

$positions = [];
$resPos = $conn->query("SELECT * FROM positions ORDER BY name");
while ($row = $resPos->fetch_assoc()) { $positions[] = $row; }

$designations = [];
$resDesg = $conn->query("SELECT * FROM designations ORDER BY name");
while ($row = $resDesg->fetch_assoc()) { $designations[] = $row; }
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Organization Architecture Framework - HR System</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">
    <style>
        .staff-name-col { position: sticky; left: 0; z-index: 20; }
        .no-scrollbar::-webkit-scrollbar { display: none; }
        .no-scrollbar { -ms-overflow-style: none; scrollbar-width: none; }

        @media print {
            .no-print, #sidebar-overlay, header { display: none !important; }
            body { background: white !important; }
            #main-content { padding: 0 !important; md-left: 0 !important; pl: 0 !important; }
            table { font-size: 10px; width: 100%; table-layout: fixed; }
            th, td { padding: 4px !important; }
        }
    </style>
</head>
<body class="bg-stone-100/60 min-h-screen text-slate-800 antialiased selection:bg-indigo-600 selection:text-white font-sans">

    <div class="flex">
        
        <?php include '../components/sidebar.php'; ?>

        <div id="sidebar-overlay" class="fixed inset-0 bg-slate-900/40 hidden z-40 transition-opacity duration-300 no-print" 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">
            
            <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 no-print">
                <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" aria-label="Toggle Side Area Menu">
                        <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">Organization Architecture</h1>
                        <p class="text-[10px] text-indigo-700 font-bold uppercase tracking-wider">Structure Engine</p>
                    </div>
                </div>
                
                <div class="flex items-center gap-4">
                    <div class="hidden sm:flex flex-col text-right">
                        <span class="text-[11px] font-extrabold text-slate-950 leading-tight"><?= htmlspecialchars($_SESSION['username'] ?? 'User'); ?></span>
                        <span class="text-[9px] text-indigo-700 uppercase font-black tracking-wider leading-none mt-0.5"><?= htmlspecialchars($role ?: 'Staff'); ?></span>
                    </div>
                    <div class="w-7 h-7 bg-slate-200 border border-slate-300 rounded-lg flex items-center justify-center font-black text-xs text-slate-700 select-none uppercase">
                        <?= strtoupper(substr($_SESSION['username'] ?? 'U', 0, 1)); ?>
                    </div>
                </div>
            </header>

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

                <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 no-print">
                    <div>
                        <h2 class="text-xl font-black text-slate-950 tracking-tight">Corporate Architecture</h2>
                        <p class="text-[11px] text-slate-600 font-semibold">Configure operational metrics, structural divisions, and corporate tiers.</p>
                    </div>
                </div>

                <?php if (isset($_GET['error']) && $_GET['error'] === 'in_use'): ?>
                    <div class="bg-red-600 border border-slate-950 text-white px-4 py-3 rounded-xl font-extrabold text-xs shadow-sm">
                        ❌ Security Constraint: The requested structural element cannot be dropped because it is linked to active employee records.
                    </div>
                <?php elseif (isset($_GET['saved'])): ?>
                    <div class="bg-emerald-600 border border-slate-950 text-white px-4 py-3 rounded-xl font-extrabold text-xs shadow-sm">
                        ✅ New structural signature label logged to active organization directory profile successfully.
                    </div>
                <?php elseif (isset($_GET['updated'])): ?>
                    <div class="bg-blue-600 border border-slate-950 text-white px-4 py-3 rounded-xl font-extrabold text-xs shadow-sm">
                        ✅ Targeted data element updated successfully across all matching downstream modules.
                    </div>
                <?php elseif (isset($_GET['deleted'])): ?>
                    <div class="bg-amber-600 border border-slate-950 text-white px-4 py-3 rounded-xl font-extrabold text-xs shadow-sm">
                        ⚠️ Structural resource component deleted from current organization directory baseline layout.
                    </div>
                <?php endif; ?>

                <div class="flex border-b border-slate-300 gap-2 overflow-x-auto pb-0.5 no-print no-scrollbar">
                    <button onclick="switchTab('department')" id="tab-btn-department" class="px-4 py-2 text-xs font-black uppercase tracking-wider rounded-t-xl border-t border-x transition shrink-0 <?= $activeTab === 'department' ? 'border-slate-300 bg-white text-slate-950' : 'border-transparent text-slate-500 hover:text-slate-800' ?>">Departments</button>
                    <button onclick="switchTab('position')" id="tab-btn-position" class="px-4 py-2 text-xs font-black uppercase tracking-wider rounded-t-xl border-t border-x transition shrink-0 <?= $activeTab === 'position' ? 'border-slate-300 bg-white text-slate-950' : 'border-transparent text-slate-500 hover:text-slate-800' ?>">Positions</button>
                    <button onclick="switchTab('designation')" id="tab-btn-designation" class="px-4 py-2 text-xs font-black uppercase tracking-wider rounded-t-xl border-t border-x transition shrink-0 <?= $activeTab === 'designation' ? 'border-slate-300 bg-white text-slate-950' : 'border-transparent text-slate-500 hover:text-slate-800' ?>">Designations</button>
                </div>

                <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 items-start">
                    
                    <?php if($role === 'superadmin' || $role === 'admin'): ?>
                    <div class="bg-white rounded-xl shadow-sm border border-slate-300/80 p-4 space-y-3 no-print">
                        <div class="flex items-center justify-between border-b border-slate-200 pb-2">
                            <h3 id="form-title" class="text-[10px] font-black text-slate-500 uppercase tracking-wider">Initialize Component</h3>
                            <span class="text-[9px] font-bold text-indigo-700 uppercase">Directory Mapping</span>
                        </div>
                        
                        <form method="POST" action="departments_script.php" class="space-y-4">
                            <input type="hidden" name="action" value="create">
                            <input type="hidden" name="type" id="form-type-input" value="<?= $activeTab ?>">

                            <div class="flex flex-col gap-1.5">
                                <label id="label-name" class="text-[10px] font-black text-slate-500 uppercase tracking-wider">Name Label</label>
                                <input type="text" name="name" required placeholder="e.g. Account Services" class="w-full border border-slate-300 bg-stone-50 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-100 focus:border-indigo-500 outline-none text-xs font-bold text-slate-800">
                            </div>

                            <div class="flex flex-col gap-1.5">
                                <label class="text-[10px] font-black text-slate-500 uppercase tracking-wider">Tracking Code</label>
                                <input type="text" name="code" placeholder="e.g. FIN-08" class="w-full border border-slate-300 bg-stone-50 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-100 focus:border-indigo-500 outline-none text-xs text-slate-800 font-mono font-bold">
                            </div>

                            <button type="submit" class="w-full bg-slate-900 hover:bg-slate-800 active:scale-[0.99] transition text-white rounded-lg font-bold py-2 text-xs shadow-sm border border-slate-950">
                                Commit to Organizational Map
                            </button>
                        </form>
                    </div>
                    <?php endif; ?>

                    <div class="<?= ($role === 'superadmin' || $role === 'admin') ? 'lg:col-span-2' : 'lg:col-span-3' ?> bg-white rounded-xl shadow-sm border border-slate-300/80 p-4">
                        
                        <div id="view-tab-department" class="tab-content-panel <?= $activeTab === 'department' ? '' : 'hidden' ?>">
                            <div class="bg-stone-50 border-b border-slate-300/80 px-3 py-2 text-slate-950 text-[10px] font-black uppercase tracking-wider mb-4">
                                📂 Active Functional Divisions
                            </div>
                            <?php renderStructureTable($departments, 'department', $role); ?>
                        </div>

                        <div id="view-tab-position" class="tab-content-panel <?= $activeTab === 'position' ? '' : 'hidden' ?>">
                            <div class="bg-stone-50 border-b border-slate-300/80 px-3 py-2 text-slate-950 text-[10px] font-black uppercase tracking-wider mb-4">
                                🛠️ Active Systems Positions
                            </div>
                            <?php renderStructureTable($positions, 'position', $role); ?>
                        </div>

                        <div id="view-tab-designation" class="tab-content-panel <?= $activeTab === 'designation' ? '' : 'hidden' ?>">
                            <div class="bg-stone-50 border-b border-slate-300/80 px-3 py-2 text-slate-950 text-[10px] font-black uppercase tracking-wider mb-4">
                                🏷️ Active Assignment Designations
                            </div>
                            <?php renderStructureTable($designations, 'designation', $role); ?>
                        </div>

                    </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>
    </div>

    <!-- Edit Configuration Modal Container -->
    <div id="edit-modal-backdrop" class="fixed inset-0 bg-slate-900/40 backdrop-blur-xs hidden z-50 flex items-center justify-center p-4">
        <div class="bg-white rounded-xl p-4 shadow-sm w-full max-w-md border border-slate-300 space-y-3">
            <div class="flex items-center justify-between border-b border-slate-200 pb-2">
                <h3 class="text-[10px] font-black text-slate-500 uppercase tracking-wider">Edit Configuration Node</h3>
                <span class="text-[9px] font-bold text-indigo-700 uppercase font-mono">Mod Protocol</span>
            </div>
            <form method="POST" action="departments_script.php" class="space-y-4">
                <input type="hidden" name="action" value="update">
                <input type="hidden" name="type" id="modal-type-input">
                <input type="hidden" name="id" id="modal-id-input">

                <div class="flex flex-col gap-1.5">
                    <label class="text-[10px] font-black text-slate-500 uppercase tracking-wider">Ident Label Name</label>
                    <input type="text" name="name" id="modal-name-input" required class="w-full border border-slate-300 bg-stone-50 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-100 focus:border-indigo-500 outline-none text-xs font-bold text-slate-800">
                </div>

                <div class="flex flex-col gap-1.5">
                    <label class="text-[10px] font-black text-slate-500 uppercase tracking-wider">Tracking Code Mapping</label>
                    <input type="text" name="code" id="modal-code-input" class="w-full border border-slate-300 bg-stone-50 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-100 focus:border-indigo-500 outline-none text-xs font-bold text-slate-800 font-mono">
                </div>

                <div class="flex justify-end gap-2 pt-2 border-t border-slate-200">
                    <button type="button" onclick="closeEditModal()" class="bg-slate-200 border border-slate-300 text-slate-700 font-bold px-3 py-1.5 rounded-lg text-xs hover:bg-slate-300 transition">Discard</button>
                    <button type="submit" class="bg-slate-900 hover:bg-slate-800 border border-slate-950 text-white font-bold px-3 py-1.5 rounded-lg text-xs transition">Update Component</button>
                </div>
            </form>
        </div>
    </div>

<script>
    function switchTab(tabKey) {
        document.querySelectorAll('.tab-content-panel').forEach(panel => panel.classList.add('hidden'));
        document.querySelectorAll('[id^="tab-btn-"]').forEach(btn => {
            btn.classList.remove('border-slate-300', 'bg-white', 'text-slate-950');
            btn.classList.add('border-transparent', 'text-slate-500');
        });

        const targetPanel = document.getElementById('view-tab-' + tabKey);
        const targetBtn = document.getElementById('tab-btn-' + tabKey);
        
        if(targetPanel && targetBtn) {
            targetPanel.classList.remove('hidden');
            targetBtn.classList.remove('border-transparent', 'text-slate-500');
            targetBtn.classList.add('border-slate-300', 'bg-white', 'text-slate-950');
        }

        const typeInput = document.getElementById('form-type-input');
        if (typeInput) typeInput.value = tabKey;

        const formTitle = document.getElementById('form-title');
        const labelName = document.getElementById('label-name');
        if (formTitle && labelName) {
            const labelStr = tabKey.charAt(0).toUpperCase() + tabKey.slice(1);
            formTitle.textContent = "Create New " + labelStr;
            labelName.textContent = labelStr + " Label Title Name";
        }
    }

    function openEditModal(type, id, name, code) {
        document.getElementById('modal-type-input').value = type;
        document.getElementById('modal-id-input').value = id;
        document.getElementById('modal-name-input').value = name;
        document.getElementById('modal-code-input').value = code;
        document.getElementById('edit-modal-backdrop').classList.remove('hidden');
    }

    function closeEditModal() {
        document.getElementById('edit-modal-backdrop').classList.add('hidden');
    }
</script>
<script src="../components/sidebar.js"></script>
</body>
</html>

<?php
/**
 * Layout helper to print out functional structural tables cleanly
 */
function renderStructureTable($dataset, $typeKey, $role) {
    ?>
    <div class="w-full overflow-x-auto rounded-xl border border-slate-300 shadow-xs no-scrollbar">
        <table class="w-full min-w-[550px] border-collapse text-left text-xs">
            <thead>
                <tr class="bg-stone-50 text-slate-500 uppercase text-[9px] font-black tracking-wider border-b border-slate-300/80">
                    <th class="p-3">Structural Name</th>
                    <th class="p-3">Tracking Code Mapping</th>
                    <th class="p-3 text-center w-48">Administrative Configuration</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-slate-200/80 text-slate-800 font-bold">
                <?php if (empty($dataset)): ?>
                <tr>
                    <td colspan="3" class="p-8 text-center text-slate-400 font-black uppercase tracking-wider text-[10px]">
                        📂 No active elements mapped within this structural group framework pool.
                    </td>
                </tr>
                <?php else: ?>
                    <?php foreach ($dataset as $row): ?>
                    <tr class="hover:bg-stone-50/50 transition-colors group">
                        <td class="p-3 font-extrabold text-slate-900 whitespace-nowrap">
                            <div class="flex items-center gap-2">
                                <div class="w-1.5 h-1.5 rounded-full bg-slate-900 transition-transform group-hover:scale-125"></div>
                                <?= htmlspecialchars($row['name']) ?>
                            </div>
                        </td>
                        <td class="p-3 whitespace-nowrap">
                            <span class="font-mono bg-slate-200 text-slate-800 px-2 py-0.5 rounded text-[10px] border border-slate-300 font-extrabold tracking-wide">
                                <?= htmlspecialchars($row['code'] ?? '—') ?>
                            </span>
                        </td>
                        <td class="p-2 text-center whitespace-nowrap">
                            <div class="flex items-center justify-center gap-1.5">
                                <?php if($role === 'superadmin' || $role === 'admin'): ?>
                                <button type="button" 
                                        onclick="openEditModal('<?= $typeKey ?>', '<?= $row['id'] ?>', '<?= htmlspecialchars(addslashes($row['name'])) ?>', '<?= htmlspecialchars(addslashes($row['code'] ?? '')) ?>')" 
                                        class="bg-white hover:bg-slate-900 border border-slate-300 hover:border-slate-950 text-slate-700 hover:text-white px-2.5 py-1 rounded-md text-[10px] font-extrabold tracking-wide uppercase shadow-xs transition active:scale-95">
                                    📝 Edit
                                </button>
                                <form method="POST" action="departments_script.php" 
                                      onsubmit="return confirm('Drop this structural data node component permanently? This updates downstream indexing rules.')"
                                      class="inline-block">
                                    <input type="hidden" name="action" value="delete">
                                    <input type="hidden" name="type" value="<?= $typeKey ?>">
                                    <input type="hidden" name="id" value="<?= $row['id'] ?>">
                                    <button type="submit" class="bg-red-600 hover:bg-red-700 border border-slate-950 text-white px-2.5 py-1 rounded-md text-[10px] font-extrabold tracking-wide uppercase shadow-xs transition active:scale-95">
                                        🗑️ Drop
                                    </button>
                                </form>
                                <?php else: ?>
                                <span class="text-[10px] text-slate-400 font-black uppercase tracking-wider italic">Read-Only</span>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    <?php
}
?>