<?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();

// 1. Authentication & Role Clearances
if (!isset($_SESSION['user_id'])) {
    header("Location: ../login.php");
    exit;
}
if (!isset($_SESSION['role']) || !in_array(strtolower(trim($_SESSION['role'])), ['admin', 'superadmin'])) {
    header("Location: loan_request.php?err=" . urlencode("Access Denied: Administrative Clearance Required."));
    exit;
}

// 2. Safely Extract Valid Infrastructure Roles
$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; }
}

// 3. Scan Schema Fields to Identify Existing Tracking Parameters
$statusColumns = [];
$columnQuery = $conn->query("SHOW COLUMNS FROM employee_loans");
if ($columnQuery) {
    while ($cRow = $columnQuery->fetch_assoc()) {
        $colName = strtolower($cRow['Field']);
        if (strpos($colName, 'status') !== false && $colName !== 'status') {
            $statusColumns[] = $cRow['Field'];
        }
    }
}

// 4. Secure Handling of Config State Updates (POST Operations)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_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 = preg_replace('/[^a-zA-Z0-9_]/', '', trim($_POST['checking_column']));
    $prereqCol = !empty($_POST['prerequisite_column']) ? preg_replace('/[^a-zA-Z0-9_]/', '', trim($_POST['prerequisite_column'])) : null;
    $prereqVal = !empty($_POST['prerequisite_value']) ? trim($_POST['prerequisite_value']) : null;

    if (empty($checkingCol)) {
        header("Location: loan_approval_config.php?err=" . urlencode("Target tracking schema column cannot be empty."));
        exit;
    }

    // Dynamic Database Column Provisions Check
    $physicalColumns = [];
    $physQuery = $conn->query("SHOW COLUMNS FROM employee_loans");
    if ($physQuery) {
        while ($pRow = $physQuery->fetch_assoc()) { $physicalColumns[] = strtolower($pRow['Field']); }
    }

    if (!in_array(strtolower($checkingCol), $physicalColumns)) {
        $alterSQL = "ALTER TABLE `employee_loans` ADD COLUMN `{$checkingCol}` VARCHAR(50) NULL DEFAULT 'Pending'";
        if (!$conn->query($alterSQL)) {
            header("Location: loan_approval_config.php?err=" . urlencode("DB Structure Error mapping column: " . $conn->error));
            exit;
        }
    }

    if (!empty($prereqCol) && !in_array(strtolower($prereqCol), $physicalColumns)) {
        $conn->query("ALTER TABLE `employee_loans` ADD COLUMN `{$prereqCol}` VARCHAR(50) NULL DEFAULT 'Pending'");
    }

    if ($stageId > 0) {
        $stmt = $conn->prepare("UPDATE loan_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);
    } else {
        $stmt = $conn->prepare("INSERT INTO loan_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);
    }
    
    $stmt->execute();
    $stmt->close();
    header("Location: loan_approval_config.php?success=" . urlencode("Pipeline architecture definitions successfully synchronized."));
    exit;
}

// 5. Secure Deletion Processing Layer
if (isset($_GET['delete_id'])) {
    $delId = intval($_GET['delete_id']);
    $stmt = $conn->prepare("DELETE FROM loan_approval_stages WHERE id = ?");
    $stmt->bind_param("i", $delId);
    $stmt->execute(); 
    $stmt->close();
    header("Location: loan_approval_config.php?success=" . urlencode("Stage deleted successfully from runtime pipeline."));
    exit;
}

// 6. Locate Target Dataset for Form Bindings
$editTarget = null;
if (isset($_GET['edit_id'])) {
    $editId = intval($_GET['edit_id']);
    $stmt = $conn->prepare("SELECT * FROM loan_approval_stages WHERE id = ? LIMIT 1");
    $stmt->bind_param("i", $editId);
    $stmt->execute();
    $editTarget = $stmt->get_result()->fetch_assoc();
    $stmt->close();
}

// 7. Extract Global Pipeline Layout Model
$stages = [];
$res = $conn->query("SELECT * FROM loan_approval_stages ORDER BY stage_order ASC");
while ($res && $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">
    <title>Loan Workflow Stage Matrix - System Configurations</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="../components/sidebar.css">
</head>
<body class="bg-stone-100 min-h-screen text-slate-800 antialiased 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">
            
            <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 uppercase">Workflow Engine</h1>
                        <p class="text-[10px] text-slate-500 font-bold uppercase tracking-wider">Architecture Setup</p>
                    </div>
                </div>
                <a href="loan_request.php" class="bg-white border border-slate-300 hover:bg-stone-50 text-slate-800 font-bold text-[10px] uppercase tracking-wider px-3 py-1.5 rounded-lg transition shadow-xs">
                    ‹ Exit Configuration
                </a>
            </header>

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

                <div class="bg-white border border-slate-300/80 p-5 rounded-xl shadow-xs flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                    <div>
                        <h2 class="text-sm font-black text-slate-950 uppercase tracking-tight">Loan Workflow Architecture Matrix</h2>
                        <p class="text-[11px] text-slate-500 font-medium mt-0.5">Configure real-time sequential authorization gates, systemic runtime requirements, and permission layers.</p>
                    </div>
                </div>

                <?php if (!empty($_GET['success'])): ?>
                    <div class="bg-emerald-50 border border-emerald-300 text-emerald-800 px-4 py-3 rounded-lg text-xs font-bold"><?= htmlspecialchars($_GET['success']) ?></div>
                <?php endif; ?>
                <?php if (!empty($_GET['err'])): ?>
                    <div class="bg-rose-50 border border-rose-300 text-rose-800 px-4 py-3 rounded-lg text-xs font-bold"><?= htmlspecialchars($_GET['err']) ?></div>
                <?php endif; ?>

                <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 items-start">
                    
                    <!-- Administration Mapping Controls Form Panel -->
                    <div class="bg-white border border-slate-300/80 rounded-xl p-4 shadow-xs space-y-4">
                        <div class="flex items-center justify-between border-b border-slate-200 pb-2.5">
                            <h3 class="text-[11px] font-black text-slate-950 uppercase tracking-wider"><?= $editTarget ? 'Modify Protocol Rule' : 'Append Protocol Stage' ?></h3>
                            <?php if ($editTarget): ?>
                                <a href="loan_approval_config.php" class="text-[10px] font-bold text-rose-600 hover:underline">Cancel Alteration</a>
                            <?php endif; ?>
                        </div>

                        <form action="loan_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 gap-1">
                                <label class="text-[10px] font-black text-slate-400 uppercase tracking-wider">Execution Sequence Order Index</label>
                                <input type="number" name="stage_order" required value="<?= $editTarget ? htmlspecialchars($editTarget['stage_order']) : '1' ?>" class="border border-slate-300 p-2 rounded-lg bg-stone-50 font-mono text-xs font-bold text-slate-800 focus:outline-none focus:border-slate-400 focus:bg-white transition">
                            </div>

                            <div class="flex flex-col gap-1">
                                <label class="text-[10px] font-black text-slate-400 uppercase tracking-wider">Stage Alias Descriptive Label</label>
                                <input type="text" name="stage_name" required value="<?= $editTarget ? htmlspecialchars($editTarget['stage_name']) : '' ?>" placeholder="e.g., General Manager Clearance" class="border border-slate-300 p-2 rounded-lg bg-stone-50 text-xs font-bold text-slate-800 placeholder:text-slate-400 focus:outline-none focus:border-slate-400 focus:bg-white transition">
                            </div>

                            <div class="flex flex-col gap-1">
                                <label class="text-[10px] font-black text-slate-400 uppercase tracking-wider">Authority Clearance Assignment Role</label>
                                <select name="role_allowed" required class="border border-slate-300 p-2 rounded-lg bg-stone-50 text-xs font-bold text-slate-800 focus:outline-none focus:border-slate-400 focus:bg-white transition">
                                    <option value="" class="text-slate-400">-- Choose Authorized Group Role --</option>
                                    <?php foreach ($availableRoles as $role): ?>
                                        <option value="<?= $role ?>" <?= ($editTarget && strtolower($editTarget['role_allowed']) === $role) ? 'selected' : '' ?>><?= htmlspecialchars(strtoupper($role)) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>

                            <div class="flex flex-col gap-1">
                                <label class="text-[10px] font-black text-slate-400 uppercase tracking-wider">Target Status Tracking Column</label>
                                <input type="text" id="checking_column" name="checking_column" required value="<?= $editTarget ? htmlspecialchars($editTarget['checking_column']) : '' ?>" placeholder="e.g., gm_status" class="border border-slate-300 p-2 rounded-lg bg-stone-50 text-xs font-mono font-bold text-slate-900 focus:outline-none focus:border-slate-400 focus:bg-white transition">
                                <p class="text-[9px] text-slate-400 font-medium">Or map configuration rules from validated database storage profiles:</p>
                                <select onchange="document.getElementById('checking_column').value=this.value" class="border border-slate-300 p-1.5 rounded-lg bg-white text-[11px] font-bold text-slate-700 focus:outline-none">
                                    <option value="">-- Structural Field Directory Matcher --</option>
                                    <?php foreach ($statusColumns as $col): ?>
                                        <option value="<?= $col ?>"><?= $col ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>

                            <div class="border-t border-slate-200/80 pt-3 mt-1 space-y-3">
                                <p class="text-[10px] font-black text-amber-700 uppercase tracking-wider">Gatekeeping System Prerequisites</p>
                                
                                <div class="flex flex-col gap-1">
                                    <label class="text-[9px] font-black text-slate-400 uppercase tracking-wider">Requires Prior Clearance At</label>
                                    <select name="prerequisite_column" class="border border-slate-300 p-1.5 rounded-lg bg-stone-50 text-[11px] font-bold text-slate-800 focus:outline-none">
                                        <option value="">None (Entry Level Initial Phase)</option>
                                        <?php foreach ($statusColumns as $col): ?>
                                            <option value="<?= $col ?>" <?= ($editTarget && $editTarget['prerequisite_column'] === $col) ? 'selected' : '' ?>><?= $col ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="flex flex-col gap-1">
                                    <label class="text-[9px] font-black text-slate-400 uppercase tracking-wider">Prerequisite Value Expected</label>
                                    <input type="text" name="prerequisite_value" value="<?= $editTarget ? htmlspecialchars($editTarget['prerequisite_value']) : 'Approved' ?>" class="border border-slate-300 p-1.5 rounded-lg bg-stone-50 text-xs font-mono font-bold text-slate-800 focus:outline-none focus:border-slate-400 focus:bg-white transition">
                                </div>
                            </div>

                            <button type="submit" class="w-full bg-slate-900 hover:bg-slate-800 text-white py-2.5 rounded-lg font-bold text-[11px] uppercase tracking-wider transition shadow-xs">
                                Commit Pipeline Stage
                            </button>
                        </form>
                    </div>

                    <!-- Workflow Stage Rules Realtime Grid -->
                    <div class="bg-white rounded-xl shadow-xs border border-slate-300/80 overflow-hidden lg:col-span-2">
                        <div class="overflow-x-auto w-full">
                            <table class="w-full text-xs text-left border-collapse min-w-[650px]">
                                <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 w-16 text-center">Index</th>
                                        <th class="p-3">Descriptor</th>
                                        <th class="p-3 w-32">Clearance Role</th>
                                        <th class="p-3">Update Target Column</th>
                                        <th class="p-3">Rule Dependencies</th>
                                        <th class="p-3 w-28 text-center">Actions</th>
                                    </tr>
                                </thead>
                                <tbody class="divide-y divide-slate-200 font-bold text-slate-800">
                                    <?php if (empty($stages)): ?>
                                        <tr>
                                            <td colspan="6" class="p-8 text-center text-slate-500 font-semibold bg-stone-50/50">
                                                No workflow tracking steps or structural sequence pipeline layers configured.
                                            </td>
                                        </tr>
                                    <?php else: foreach ($stages as $stg): ?>
                                        <tr class="hover:bg-stone-50/40 transition">
                                            <td class="p-3 text-center font-mono text-[11px] text-slate-400">
                                                <?= htmlspecialchars($stg['stage_order']) ?>
                                            </td>
                                            <td class="p-3 text-slate-950 font-extrabold whitespace-nowrap">
                                                <?= htmlspecialchars($stg['stage_name']) ?>
                                            </td>
                                            <td class="p-2 whitespace-nowrap">
                                                <span class="inline-block bg-slate-100 text-slate-800 px-2 py-0.5 border border-slate-300 text-[9px] font-black tracking-tight uppercase rounded">
                                                    <?= htmlspecialchars($stg['role_allowed']) ?>
                                                </span>
                                            </td>
                                            <td class="p-3 font-mono text-[11px] text-slate-500 whitespace-nowrap">
                                                <?= htmlspecialchars($stg['checking_column']) ?>
                                            </td>
                                            <td class="p-3 text-[11px] font-medium text-slate-600">
                                                <?php if (!empty($stg['prerequisite_column'])): ?>
                                                    Requires <span class="font-mono font-bold text-amber-700"><?= htmlspecialchars($stg['prerequisite_column']) ?></span> == <span class="font-mono text-slate-950 font-black">"<?= htmlspecialchars($stg['prerequisite_value']) ?>"</span>
                                                <?php else: ?>
                                                    <span class="text-emerald-700 font-bold uppercase text-[9px] tracking-wider">Initial Entry Point</span>
                                                <?php endif; ?>
                                            </td>
                                            <td class="p-2 text-center whitespace-nowrap">
                                                <div class="flex items-center justify-center gap-2">
                                                    <a href="loan_approval_config.php?edit_id=<?= $stg['id'] ?>" class="text-amber-700 hover:text-amber-800 text-[11px]">Modify</a>
                                                    <span class="text-slate-300">|</span>
                                                    <a href="loan_approval_config.php?delete_id=<?= $stg['id'] ?>" onclick="return confirm('Purge this step permanently from the rule processing pipelines?');" class="text-rose-700 hover:text-rose-800 text-[11px]">Purge</a>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endforeach; endif; ?>
                                </tbody>
                            </table>
                        </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>

    <script src="../components/sidebar.js"></script>
</body>
</html>