<?php 
require '../config.php';
if (session_status() === PHP_SESSION_NONE && !headers_sent()) { session_start(); }

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

$userId = intval($_SESSION['user_id']);
$userRole = strtolower(trim($_SESSION['role'] ?? ''));
$isAdmin = in_array($userRole, ['admin', 'superadmin', 'hr', 'manager', 'gm', 'opm']);

// 1. Gather dynamic status columns layout definitions safely from the database schema first
$statusColumns = [];
$allTableColumns = [];
$columnQuery = $conn->query("SHOW COLUMNS FROM employee_loans");
if ($columnQuery) {
    while ($cRow = $columnQuery->fetch_assoc()) {
        $fieldName = $cRow['Field'];
        $allTableColumns[] = strtolower($fieldName); // Used for dynamic insertion check
        if (strpos(strtolower($fieldName), 'status') !== false) {
            $statusColumns[] = $fieldName;
        }
    }
}

// ---- DYNAMIC NEW LOAN APPLICATION SUBMISSION ENGINE (PRG IMMUNIZED) ----
$formFeedback = null;

// Retrieve session-based feedback if redirected
if (isset($_SESSION['form_feedback'])) {
    $formFeedback = $_SESSION['form_feedback'];
    unset($_SESSION['form_feedback']); // Clear immediately so it only shows once
}

// Release the session lock on plain page views; the POST branch below still
// needs to write flash data, so it keeps the session open for itself.
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    session_write_close();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'submit_loan') {
    $amount = floatval($_POST['amount']);
    $months = intval($_POST['months']);
    $reason = trim($_POST['reason']);
    
    $empQuery = $conn->prepare("SELECT id FROM employees WHERE user_id = ? LIMIT 1");
    $empQuery->bind_param("i", $userId);
    $empQuery->execute();
    $empResult = $empQuery->get_result()->fetch_assoc();
    $empQuery->close();
    
    $employeeId = $empResult ? intval($empResult['id']) : 0;

    if ($employeeId <= 0) {
        $_SESSION['form_feedback'] = ['status' => 'error', 'message' => 'Profile Error: No employee profile mapped to this account log.'];
    } elseif ($amount <= 0 || $months <= 0 || empty($reason)) {
        $_SESSION['form_feedback'] = ['status' => 'error', 'message' => 'Validation Error: Please fill in all financial parameters properly.'];
    } else {
        $monthlyDeduction = $amount / $months;
        $balance = $amount;
        $requestDate = date('Y-m-d');
        
        // Base arrays for dynamic query building
        $insertFields = ['employee_id', 'amount', 'monthly_deduction', 'total_months', 'balance', 'reason', 'request_date'];
        $bindTypes = "iddidss";
        $bindValues = [$employeeId, $amount, $monthlyDeduction, $months, $balance, $reason, $requestDate];
        
        // Dynamically append status tracker columns ONLY if they actually exist in your database schema
        $possibleStatusFields = ['status', 'hr_status', 'manager_status', 'opm_status', 'gm_status'];
        foreach ($possibleStatusFields as $psf) {
            if (in_array($psf, $allTableColumns)) {
                $exactCaseKey = array_search($psf, array_map('strtolower', $allTableColumns));
                $exactCasedName = $columnQuery ? $allTableColumns[$exactCaseKey] : $psf;
                
                foreach ($statusColumns as $sc) {
                    if (strtolower($sc) === $psf) {
                        $exactCasedName = $sc;
                        break;
                    }
                }
                
                $insertFields[] = "`{$exactCasedName}`";
                $bindTypes .= "s";
                $bindValues[] = 'Pending';
            }
        }
        
        $fieldList = implode(', ', $insertFields);
        $placeholders = implode(', ', array_fill(0, count($insertFields), '?'));
        $sql = "INSERT INTO employee_loans ({$fieldList}) VALUES ({$placeholders})";
        
        $insertStmt = $conn->prepare($sql);
        
        $bindParams = array_merge([$bindTypes], $bindValues);
        $refs = [];
        foreach ($bindParams as $key => $value) {
            $refs[$key] = &$bindParams[$key];
        }
        call_user_func_array([$insertStmt, 'bind_param'], $refs);
        
        if ($insertStmt->execute()) {
            $_SESSION['form_feedback'] = ['status' => 'success', 'message' => 'Loan application submitted successfully to the verification pipeline!'];
        } else {
            $_SESSION['form_feedback'] = ['status' => 'error', 'message' => 'Database failure recording parameters layer template.'];
        }
        $insertStmt->close();
    }

    header("Location: loan_request.php");
    exit;
}

$stages = [];
$stageRes = $conn->query("SELECT * FROM loan_approval_stages ORDER BY stage_order ASC");
while ($stageRes && $row = $stageRes->fetch_assoc()) {
    $stages[] = $row;
}

if ($isAdmin) {
    $query = "SELECT el.*, e.name AS employee_name FROM employee_loans el JOIN employees e ON el.employee_id = e.id ORDER BY el.id DESC";
    $stmt = $conn->prepare($query);
} else {
    $query = "SELECT el.*, e.name AS employee_name FROM employee_loans el JOIN employees e ON el.employee_id = e.id WHERE e.user_id = ? ORDER BY el.id DESC";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $userId);
}
$stmt->execute();
$loans = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Corporate Loan Registry Dashboard</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">Loan Registry</h1>
                        <p class="text-[10px] text-slate-500 font-bold uppercase tracking-wider">Operational Ledger</p>
                    </div>
                </div>
            </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 Matrix Dashboard</h2>
                        <p class="text-[11px] text-slate-500 font-medium mt-0.5">Review operational ledgers and update pending structural records securely.</p>
                    </div>
                    <div class="flex gap-2">
                        <?php if (in_array($userRole, ['admin', 'superadmin'])): ?>
                            <a href="loan_approval_config.php" class="bg-stone-50 text-slate-900 border border-slate-300 text-[10px] font-black uppercase tracking-tight px-3 py-2 rounded-lg shadow-xs hover:bg-stone-100 transition text-center flex items-center">Engine Config</a>
                        <?php endif; ?>
                        <button onclick="openModal()" class="bg-slate-950 hover:bg-slate-800 text-white text-[10px] font-black uppercase tracking-tight px-4 py-2 rounded-lg shadow-xs transition whitespace-nowrap">
                            + Apply for Loan
                        </button>
                    </div>
                </div>

                <?php if ($formFeedback !== null): ?>
                    <div class="<?= $formFeedback['status'] === 'success' ? 'bg-emerald-50 border-emerald-300 text-emerald-950' : 'bg-rose-50 border-rose-300 text-rose-950' ?> border p-3.5 rounded-xl font-bold text-xs shadow-xs">
                        <?= htmlspecialchars($formFeedback['message']) ?>
                    </div>
                <?php endif; ?>

                <div id="alert-zone" class="hidden"></div>

                <div class="bg-white rounded-xl shadow-xs border border-slate-300/80 overflow-hidden">
                    <div class="overflow-x-auto w-full">
                        <table class="w-full text-xs text-left border-collapse min-w-[800px]">
                            <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">Beneficiary</th>
                                    <th class="p-3">Principal</th>
                                    <th class="p-3">Terms</th>
                                    <th class="p-3">Monthly Deduction</th>
                                    <?php foreach($statusColumns as $col): ?>
                                        <th class="p-3 text-center w-36"><?= htmlspecialchars(str_replace('_', ' ', $col)) ?></th>
                                    <?php endforeach; ?>
                                    <th class="p-3 text-center w-48">Engine Actions</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-200 font-bold text-slate-800">
                                <?php if(empty($loans)): ?>
                                    <tr><td colspan="12" class="p-8 text-center text-slate-500 font-semibold bg-stone-50/50">No loan parameters recorded on current system tables.</td></tr>
                                <?php else: foreach($loans as $loan): 
                                    $loanRowKeys = array_change_key_case($loan, CASE_LOWER);
                                    $masterState = trim($loanRowKeys['status'] ?? 'Pending');
                                    $isPipelineFinished = in_array(strtolower($masterState), ['active', 'closed', 'rejected']);
                                    
                                    $userHasSignedOff = false;
                                    foreach ($stages as $stage) {
                                        if (strtolower(trim($stage['role_allowed'])) === $userRole) {
                                            $chkCol = strtolower(trim($stage['checking_column']));
                                            $currentStageValue = trim($loanRowKeys[$chkCol] ?? 'Pending');
                                            if (in_array($currentStageValue, ['Approved', 'Rejected'])) {
                                                $userHasSignedOff = true;
                                            }
                                        }
                                    }
                                ?>
                                    <tr id="loan-row-<?= $loan['id'] ?>" class="hover:bg-stone-50/40 transition">
                                        <td class="p-3 text-slate-950 font-extrabold whitespace-nowrap"><?= htmlspecialchars($loan['employee_name'] ?? 'Unknown Employee') ?></td>
                                        <td class="p-3 font-mono text-[11px] text-slate-950 font-black whitespace-nowrap">₦<?= number_format($loan['amount'], 2) ?></td>
                                        <td class="p-3 font-mono text-[11px] text-slate-600 whitespace-nowrap"><?= $loan['total_months'] ?> Months</td>
                                        <td class="p-3 font-mono text-[11px] text-slate-600 whitespace-nowrap">₦<?= number_format($loan['monthly_deduction'], 2) ?></td>
                                        
                                        <?php foreach($statusColumns as $col): 
                                            $val = !empty($loan[$col]) ? trim($loan[$col]) : 'Pending';
                                            $badgeClass = "bg-amber-50 text-amber-900 border-amber-200";
                                            if(in_array(strtolower($val), ['approved', 'active'])) $badgeClass = "bg-emerald-50 text-emerald-900 border-emerald-200";
                                            if(strtolower($val) === 'rejected') $badgeClass = "bg-rose-50 text-rose-900 border-rose-200";
                                            if(strtolower($val) === 'closed') $badgeClass = "bg-stone-100 text-slate-900 border-slate-300";
                                        ?>
                                            <td class="p-3 text-center whitespace-nowrap">
                                                <span class="inline-block border px-2 py-0.5 rounded text-[9px] font-black uppercase tracking-wider <?= $badgeClass ?>"><?= $val ?></span>
                                            </td>
                                        <?php endforeach; ?>

                                        <td class="p-2 text-center whitespace-nowrap">
                                            <div class="flex items-center justify-center gap-1.5">
                                                <?php if ($isPipelineFinished): ?>
                                                    <span class="text-[10px] font-bold tracking-tight text-slate-500 uppercase bg-stone-100 px-2 py-1 rounded border border-slate-200 select-none">
                                                        Closed (<?= htmlspecialchars($masterState) ?>)
                                                    </span>
                                                    <?php if(in_array($userRole, ['admin', 'superadmin', 'hr'])): ?>
                                                        <button onclick="triggerEngineAction(<?= $loan['id'] ?>, 'DELETE')" class="text-rose-700 hover:text-rose-900 font-extrabold text-[10px] tracking-tight uppercase p-1 hover:underline transition">Purge</button>
                                                    <?php endif; ?>

                                                <?php elseif ($userHasSignedOff): ?>
                                                    <span class="text-[10px] font-bold tracking-tight text-amber-800 bg-amber-50 border border-amber-200 px-2 py-1 rounded select-none">
                                                        Awaiting Stage
                                                    </span>
                                                    <?php if(in_array($userRole, ['admin', 'superadmin', 'hr'])): ?>
                                                        <button onclick="triggerEngineAction(<?= $loan['id'] ?>, 'DELETE')" class="text-rose-700 hover:text-rose-900 font-extrabold text-[10px] tracking-tight uppercase p-1 hover:underline transition">Purge</button>
                                                    <?php endif; ?>

                                                <?php else: ?>
                                                    <button onclick="triggerEngineAction(<?= $loan['id'] ?>, 'APPROVE')" class="bg-emerald-600 hover:bg-emerald-700 text-white font-bold text-[10px] tracking-tight uppercase px-2 py-1 rounded transition shadow-xs">Approve</button>
                                                    <button onclick="triggerEngineAction(<?= $loan['id'] ?>, 'REJECT')" class="bg-rose-600 hover:bg-rose-700 text-white font-bold text-[10px] tracking-tight uppercase px-2 py-1 rounded transition shadow-xs">Reject</button>
                                                    <?php if(in_array($userRole, ['admin', 'superadmin', 'hr'])): ?>
                                                        <button onclick="triggerEngineAction(<?= $loan['id'] ?>, 'DELETE')" class="text-rose-700 hover:text-rose-900 font-extrabold text-[10px] tracking-tight uppercase p-1 hover:underline transition">Purge</button>
                                                    <?php endif; ?>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; endif; ?>
                            </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>
    </div>

    <div id="loanModal" class="fixed inset-0 bg-slate-900/40 backdrop-blur-xs hidden items-center justify-center z-50 p-4">
        <div class="bg-white rounded-xl max-w-md w-full overflow-hidden shadow-xl border border-slate-300/80 flex flex-col max-h-[90vh]">
            
            <div class="px-5 py-3.5 bg-stone-50 border-b border-slate-300/80 flex justify-between items-center">
                <div>
                    <h3 class="text-xs font-black text-slate-950 uppercase tracking-tight">Apply for Corporate Loan</h3>
                    <p class="text-[10px] text-slate-500 font-medium mt-0.5">Specify parameters below to trigger workflow matrix loops.</p>
                </div>
                <button onclick="closeModal()" class="text-slate-500 hover:text-slate-800 font-black text-lg p-1 transition leading-none active:scale-95">✕</button>
            </div>

            <form action="loan_request.php" method="POST" class="p-5 space-y-4 overflow-y-auto" id="newLoanCreationForm">
                <input type="hidden" name="action" value="submit_loan">
                
                <div class="space-y-1">
                    <label class="block text-[9px] font-black text-slate-500 uppercase tracking-wider">Requested Capital Principal (₦)</label>
                    <div class="relative">
                        <span class="absolute left-3 top-2 text-slate-400 font-black font-mono text-xs">₦</span>
                        <input type="number" step="0.01" name="amount" required placeholder="0.00" class="w-full border border-slate-300 bg-white px-2.5 py-1.5 pl-7 rounded-lg text-xs font-black font-mono text-slate-950 outline-none focus:border-slate-950 transition shadow-xs">
                    </div>
                </div>

                <div class="space-y-1">
                    <label class="block text-[9px] font-black text-slate-500 uppercase tracking-wider">Repayment Window (Months)</label>
                    <input type="number" name="months" min="1" required placeholder="e.g., 12" class="w-full border border-slate-300 bg-white px-2.5 py-1.5 rounded-lg text-xs font-bold font-mono text-slate-950 outline-none focus:border-slate-950 transition shadow-xs">
                </div>

                <div class="space-y-1">
                    <label class="block text-[9px] font-black text-slate-500 uppercase tracking-wider">Justification Purpose Context</label>
                    <textarea name="reason" rows="3" required placeholder="Provide clear contextual details..." class="w-full border border-slate-300 bg-white px-2.5 py-1.5 rounded-lg text-xs font-medium text-slate-950 outline-none focus:border-slate-950 transition resize-none shadow-xs"></textarea>
                </div>

                <div class="pt-2 flex flex-col-reverse sm:flex-row justify-end gap-2">
                    <button type="button" onclick="closeModal()" class="border border-slate-300 bg-stone-50 hover:bg-stone-100 text-slate-800 rounded-lg font-bold px-3 py-1.5 text-[10px] tracking-tight uppercase transition">Cancel</button>
                    <button type="submit" class="bg-slate-900 hover:bg-slate-800 text-white rounded-lg font-bold px-3 py-1.5 text-[10px] tracking-tight uppercase transition border border-slate-950 shadow-xs">Submit Parameters</button>
                </div>
            </form>
        </div>
    </div>

    <script src="../components/sidebar.js"></script>
    <script>
    function openModal() {
        const el = document.getElementById('loanModal');
        el.classList.remove('hidden'); el.classList.add('flex');
    }
    function closeModal() {
        const el = document.getElementById('loanModal');
        el.classList.remove('flex'); el.classList.add('hidden');
    }

    function triggerEngineAction(reqId, type) {
        if(type === 'DELETE' && !confirm('Completely purge this record entry?')) return;
        
        const payload = {
            request_id: parseInt(reqId, 10),
            action_type: String(type).toUpperCase().trim()
        };

        const zone = document.getElementById('alert-zone');

        fetch('loan_request_script.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            body: JSON.stringify(payload)
        })
        .then(res => {
            if (!res.ok) throw new Error('Bad pipeline validation server context.');
            return res.json();
        })
        .then(data => {
            zone.classList.remove('hidden');
            
            if(data.status === 'success') {
                zone.className = "bg-emerald-50 border border-emerald-300 text-emerald-950 p-3.5 rounded-xl shadow-xs mb-4 font-bold text-xs";
                zone.innerText = data.message;
                if(type === 'DELETE') {
                    document.getElementById(`loan-row-${reqId}`).remove();
                } else {
                    setTimeout(() => { location.reload(); }, 600);
                }
            } else {
                zone.className = "bg-rose-50 border border-rose-300 text-rose-950 p-3.5 rounded-xl shadow-xs mb-4 font-bold text-xs";
                zone.innerText = data.message;
            }
            window.scrollTo({ top: 0, behavior: 'smooth' });
        })
        .catch(err => {
            console.error('Workflow Exception Failure:', err);
            zone.classList.remove('hidden');
            zone.className = "bg-rose-50 border border-rose-300 text-rose-950 p-3.5 rounded-xl shadow-xs mb-4 font-bold text-xs";
            zone.innerText = "Communication error connecting with processing engine.";
        });
    }
    </script>
</body>
</html>