<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require '../config.php';

if (session_status() === PHP_SESSION_NONE && !headers_sent()) { session_start(); }
session_write_close();

// Restrict to Administrative infrastructure layers
if (!isset($_SESSION['role']) || !in_array(strtolower($_SESSION['role']), ['admin', 'superadmin'])) {
    header("Location: index.php?err=" . urlencode("Access Denied: Administrative Clearance Required."));
    exit;
}

$userRole = strtolower($_SESSION['role'] ?? 'Staff');
$username = $_SESSION['username'] ?? 'User';

// --------------------------------------------------------------------------
// DYNAMIC SCHEMA ENGINE: EXTRACT ROLES AND SYSTEM COLUMNS
// --------------------------------------------------------------------------
$availableRoles = [];
$roleQuery = $conn->query("SELECT DISTINCT role FROM users WHERE role IS NOT NULL AND role != ''");
if ($roleQuery) {
    while ($rRow = $roleQuery->fetch_assoc()) {
        $availableRoles[] = strtolower(trim($rRow['role']));
    }
}
foreach (['admin', 'superadmin', 'hr', 'manager', 'gm', 'opm'] as $defRole) {
    if (!in_array($defRole, $availableRoles)) { $availableRoles[] = $defRole; }
}

$statusColumns = [];
$columnQuery = $conn->query("SHOW COLUMNS FROM leave_requests");
if ($columnQuery) {
    while ($cRow = $columnQuery->fetch_assoc()) {
        $colName = strtolower($cRow['Field']);
        if (strpos($colName, 'status') !== false) {
            $statusColumns[] = $cRow['Field'];
        }
    }
}

// --------------------------------------------------------------------------
// PIPELINE CONTROLLER ACTIONS (INSERT, UPDATE, DELETE)
// --------------------------------------------------------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'save_stage') {
        $stageId = isset($_POST['stage_id']) ? intval($_POST['stage_id']) : 0;
        $stageOrder = intval($_POST['stage_order']);
        $roleAllowed = strtolower(trim($_POST['role_allowed']));
        $stageName = trim($_POST['stage_name']);
        $checkingCol = trim($_POST['checking_column']);
        $prereqCol = !empty($_POST['prerequisite_column']) ? trim($_POST['prerequisite_column']) : null;
        $prereqVal = !empty($_POST['prerequisite_value']) ? trim($_POST['prerequisite_value']) : null;

        if ($stageId > 0) {
            $stmt = $conn->prepare("UPDATE leave_approval_stages SET stage_order=?, role_allowed=?, stage_name=?, checking_column=?, prerequisite_column=?, prerequisite_value=? WHERE id=?");
            $stmt->bind_param("isssssi", $stageOrder, $roleAllowed, $stageName, $checkingCol, $prereqCol, $prereqVal, $stageId);
            $msg = "Approval stage configuration modified successfully.";
        } else {
            $stmt = $conn->prepare("INSERT INTO leave_approval_stages (stage_order, role_allowed, stage_name, checking_column, prerequisite_column, prerequisite_value) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("isssss", $stageOrder, $roleAllowed, $stageName, $checkingCol, $prereqCol, $prereqVal);
            $msg = "Approval stage protocol committed to operational engine.";
        }
        
        if ($stmt->execute()) {
            header("Location: leave_approval_config.php?success=" . urlencode($msg));
        } else {
            header("Location: leave_approval_config.php?err=" . urlencode("Database Fault: " . $stmt->error));
        }
        $stmt->close();
        exit;
    }
}

if (isset($_GET['delete_id'])) {
    $delId = intval($_GET['delete_id']);
    $stmt = $conn->prepare("DELETE FROM leave_approval_stages WHERE id = ?");
    $stmt->bind_param("i", $delId);
    if ($stmt->execute()) {
        header("Location: leave_approval_config.php?success=" . urlencode("Stage protocol removed from core workflow matrices."));
    } else {
        header("Location: leave_approval_config.php?err=" . urlencode("Error purging data entity: " . $conn->error));
    }
    $stmt->close();
    exit;
}

$editTarget = null;
if (isset($_GET['edit_id'])) {
    $editId = intval($_GET['edit_id']);
    $eRes = $conn->query("SELECT * FROM leave_approval_stages WHERE id = $editId LIMIT 1");
    if ($eRes && $eRes->num_rows > 0) { $editTarget = $eRes->fetch_assoc(); }
}

$stages = [];
$res = $conn->query("SELECT * FROM leave_approval_stages ORDER BY stage_order ASC");
if ($res) {
    while ($row = $res->fetch_assoc()) { $stages[] = $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>Workflow Architecture Matrix - 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">
</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" 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">
            
            <!-- Structural Top Header Anchor Module -->
            <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" 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">Workflow Stage Architecture Matrix</h1>
                        <p class="text-[10px] text-indigo-700 font-bold uppercase tracking-wider">Dynamic Routing Control</p>
                    </div>
                </div>
                
                <div class="flex items-center gap-4">
                    <a href="index.php" class="hidden sm:inline-block text-[10px] border border-slate-300 bg-white px-3 py-1.5 rounded-lg shadow-xs hover:bg-stone-50 text-slate-700 font-black uppercase tracking-wider transition">
                        ‹ Return to Registry
                    </a>
                    <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($username, 0, 1)); ?>
                    </div>
                </div>
            </header>

            <!-- Main Workspace Canvas Area -->
            <main class="flex-1 p-4 sm:p-6 max-w-7xl w-full mx-auto space-y-4">
                
                <?php if (!empty($_GET['success'])): ?>
                    <div class="bg-emerald-50 border border-emerald-200 text-emerald-800 p-3 rounded-lg text-xs font-bold shadow-xs">
                        <?= htmlspecialchars($_GET['success']) ?>
                    </div>
                <?php endif; ?>
                <?php if (!empty($_GET['err'])): ?>
                    <div class="bg-rose-50 border border-rose-200 text-rose-800 p-3 rounded-lg text-xs font-bold shadow-xs">
                        <?= htmlspecialchars($_GET['err']) ?>
                    </div>
                <?php endif; ?>

                <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 items-start">
                    
                    <!-- Settings Input/Modification Matrix Card -->
                    <div class="bg-white border border-slate-300/80 rounded-xl p-4 shadow-sm space-y-4 lg:sticky lg:top-20">
                        <div class="border-b border-slate-100 pb-2 flex items-center justify-between">
                            <div>
                                <p class="text-[9px] font-black text-indigo-700 uppercase tracking-widest">Protocol Setup</p>
                                <h3 class="text-xs font-black text-slate-950 uppercase tracking-tight mt-0.5">
                                    <?= $editTarget ? 'Modify Stage Protocol' : 'Append Stage Protocol' ?>
                                </h3>
                            </div>
                            <?php if($editTarget): ?>
                                <a href="leave_approval_config.php" class="text-[10px] font-black text-rose-600 hover:underline uppercase tracking-wide">Clear Edit</a>
                            <?php endif; ?>
                        </div>

                        <form action="leave_approval_config.php" method="POST" class="space-y-3.5">
                            <input type="hidden" name="action" value="save_stage">
                            <input type="hidden" name="stage_id" value="<?= $editTarget ? $editTarget['id'] : 0 ?>">
                            
                            <div class="flex flex-col">
                                <label class="text-[10px] font-black text-slate-400 uppercase tracking-wide mb-1">Execution Index Order (Sorting)</label>
                                <input type="number" name="stage_order" required value="<?= $editTarget ? htmlspecialchars($editTarget['stage_order']) : '' ?>" placeholder="e.g. 1" class="w-full border border-slate-300 bg-stone-50 rounded-lg px-3 py-1.5 focus:ring-2 focus:ring-indigo-100 focus:border-indigo-500 outline-none text-xs text-slate-800 font-bold placeholder:text-slate-400">
                            </div>

                            <div class="flex flex-col">
                                <label class="text-[10px] font-black text-slate-400 uppercase tracking-wide mb-1">Stage Alias Label</label>
                                <input type="text" name="stage_name" required value="<?= $editTarget ? htmlspecialchars($editTarget['stage_name']) : '' ?>" placeholder="e.g. Operations Review" class="w-full border border-slate-300 bg-stone-50 rounded-lg px-3 py-1.5 focus:ring-2 focus:ring-indigo-100 focus:border-indigo-500 outline-none text-xs text-slate-800 font-bold placeholder:text-slate-400">
                            </div>

                            <div class="flex flex-col">
                                <label class="text-[10px] font-black text-slate-400 uppercase tracking-wide mb-1">Authority Group Assignment (Role)</label>
                                <div class="relative">
                                    <select name="role_allowed" required class="w-full border border-slate-300 bg-stone-50 rounded-lg px-3 py-1.5 focus:ring-2 focus:ring-indigo-100 focus:border-indigo-500 outline-none text-xs text-slate-800 font-bold appearance-none cursor-pointer capitalize">
                                        <option value="">-- Choose Role Engine Access --</option>
                                        <?php foreach ($availableRoles as $role): ?>
                                            <option value="<?= $role ?>" <?= ($editTarget && strtolower($editTarget['role_allowed']) === $role) ? 'selected' : '' ?>>
                                                <?= htmlspecialchars(ucwords($role)) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>

                            <div class="flex flex-col">
                                <label class="text-[10px] font-black text-slate-400 uppercase tracking-wide mb-1">Target Tracking DB Column</label>
                                <div class="relative">
                                    <select name="checking_column" required class="w-full border border-slate-300 bg-stone-50 rounded-lg px-3 py-1.5 focus:ring-2 focus:ring-indigo-100 focus:border-indigo-500 outline-none text-xs text-slate-800 font-bold appearance-none cursor-pointer">
                                        <option value="">-- Select Active Database Field --</option>
                                        <?php foreach ($statusColumns as $col): ?>
                                            <option value="<?= $col ?>" <?= ($editTarget && $editTarget['checking_column'] === $col) ? 'selected' : '' ?>><?= $col ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>

                            <div class="border-t border-slate-100 pt-3 mt-1 space-y-3">
                                <p class="text-[10px] font-black text-indigo-700 uppercase tracking-wider">Gatekeeping Prerequisites</p>
                                
                                <div class="flex flex-col">
                                    <label class="text-[9px] font-black text-slate-400 uppercase mb-1">Requires Prior Column Approval</label>
                                    <div class="relative">
                                        <select name="prerequisite_column" class="w-full border border-slate-300 bg-stone-50 rounded-lg px-2.5 py-1 focus:ring-2 focus:ring-indigo-100 focus:border-indigo-500 outline-none text-[11px] text-slate-800 font-bold appearance-none cursor-pointer">
                                            <option value="">None (Entry Point)</option>
                                            <?php foreach ($statusColumns as $col): ?>
                                                <option value="<?= $col ?>" <?= ($editTarget && $editTarget['prerequisite_column'] === $col) ? 'selected' : '' ?>><?= $col ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </div>
                                <div class="flex flex-col">
                                    <label class="text-[9px] font-black text-slate-400 uppercase mb-1">Prerequisite Expected Value</label>
                                    <input type="text" name="prerequisite_value" value="<?= $editTarget ? htmlspecialchars($editTarget['prerequisite_value']) : '' ?>" placeholder="e.g. Approved" class="w-full border border-slate-300 bg-stone-50 rounded-lg px-2.5 py-1 focus:ring-2 focus:ring-indigo-100 focus:border-indigo-500 outline-none text-[11px] text-slate-800 font-bold placeholder:text-slate-400">
                                </div>
                            </div>

                            <button type="submit" class="w-full bg-slate-900 border border-slate-950 text-white py-2 rounded-lg font-black text-xs shadow-xs hover:bg-slate-800 active:scale-[0.99] transition uppercase tracking-wider">
                                <?= $editTarget ? 'Commit Changes' : 'Commit Stage to Engine' ?>
                            </button>
                        </form>
                    </div>

                    <!-- Balanced Ledger Metrics Grid Table Portfolio -->
                    <div class="bg-white border border-slate-300/80 rounded-xl shadow-sm overflow-hidden lg:col-span-2">
                        <div class="overflow-x-auto">
                            <table class="w-full border-collapse text-left text-xs">
                                <thead>
                                    <tr class="bg-slate-50/70 border-b border-slate-200 text-[10px] font-black text-slate-400 uppercase tracking-wider">
                                        <th class="p-4 w-16 text-center">Index</th>
                                        <th class="p-4">Descriptor</th>
                                        <th class="p-4">Clearance</th>
                                        <th class="p-4">DB Column</th>
                                        <th class="p-4">Dependency Matrix</th>
                                        <th class="p-4 text-right">Actions</th>
                                    </tr>
                                </thead>
                                <tbody class="divide-y divide-slate-200/80 text-slate-700">
                                    <?php if(empty($stages)): ?>
                                        <tr><td colspan="6" class="p-8 text-center text-xs text-slate-400 font-bold uppercase tracking-wider bg-white">No workflow runtime rules provisioned.</td></tr>
                                    <?php else: foreach($stages as $stg): ?>
                                        <tr class="hover:bg-stone-50/60 transition duration-150">
                                            <td class="p-4 text-center font-mono text-slate-400 font-bold"><?= htmlspecialchars($stg['stage_order']) ?></td>
                                            <td class="p-4 text-slate-900 font-black"><?= htmlspecialchars($stg['stage_name']) ?></td>
                                            <td class="p-4">
                                                <span class="bg-indigo-50 border border-indigo-100 text-indigo-800 px-2 py-0.5 rounded font-black text-[10px] uppercase tracking-wide">
                                                    <?= htmlspecialchars($stg['role_allowed']) ?>
                                                </span>
                                            </td>
                                            <td class="p-4 font-mono text-[11px] text-slate-500 font-bold"><?= htmlspecialchars($stg['checking_column']) ?></td>
                                            <td class="p-4 text-[11px]">
                                                <?php if(!empty($stg['prerequisite_column'])): ?>
                                                    <span class="text-slate-500">Wait for</span> <span class="font-mono text-amber-700 font-black"><?= htmlspecialchars($stg['prerequisite_column']) ?></span> <span class="text-slate-500">→</span> <span class="underline font-black text-slate-900">"<?= htmlspecialchars($stg['prerequisite_value']) ?>"</span>
                                                <?php else: ?>
                                                    <span class="inline-block px-1.5 py-0.5 rounded font-black text-[9px] uppercase border bg-emerald-50 text-emerald-800 border-emerald-200 tracking-wide">Initial Entry Point</span>
                                                <?php endif; ?>
                                            </td>
                                            <td class="p-4 text-right space-x-1 whitespace-nowrap">
                                                <a href="leave_approval_config.php?edit_id=<?= $stg['id'] ?>" class="inline-block text-[10px] bg-white hover:bg-amber-50 text-amber-700 font-extrabold px-2.5 py-1 rounded border border-slate-200 hover:border-amber-300 transition uppercase tracking-wider">
                                                    Modify
                                                </a>
                                                <a href="leave_approval_config.php?delete_id=<?= $stg['id'] ?>" onclick="return confirm('Completely clear this workflow step calculation rule?');" class="inline-block text-[10px] bg-white hover:bg-rose-50 text-rose-700 font-extrabold px-2.5 py-1 rounded border border-slate-200 hover:border-rose-300 transition uppercase tracking-wider">
                                                    Purge
                                                </a>
                                            </td>
                                        </tr>
                                    <?php endforeach; endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </main>

            <!-- Footer Module Architecture -->
            <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>

    <!-- Interface Controller Engine Blocks -->
    <script src="../components/sidebar.js"></script>
    <script>
    if (typeof toggleSidebar === 'undefined') {
        window.toggleSidebar = function() {
            const sidebar = document.getElementById('sidebar');
            const overlay = document.getElementById('sidebar-overlay');
            if (sidebar && overlay) {
                sidebar.classList.toggle('-translate-x-full');
                overlay.classList.toggle('hidden');
            }
        };
    }
    </script>
</body>
</html>