<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

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

$userId = intval($_SESSION['user_id']);

/*
|--------------------------------------------------------------------------
| FIND EMPLOYEE REFERENCE MATCH
|--------------------------------------------------------------------------
*/
$stmt = $conn->prepare("SELECT id FROM employees WHERE user_id = ? LIMIT 1");
$stmt->bind_param("i", $userId);
$stmt->execute();
$employee = $stmt->get_result()->fetch_assoc();

if (!$employee) {
    die("Employee record profile not linked to system database configuration.");
}

$employeeId = $employee['id'];

/*
|--------------------------------------------------------------------------
| PROCESS INCOMING LOAN REQUEST (FORM POST ROUTE)
|--------------------------------------------------------------------------
*/
$formFeedback = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'submit_loan') {
    $amount = floatval($_POST['amount'] ?? 0);
    $months = intval($_POST['months'] ?? 0);
    $reason = trim($_POST['reason'] ?? '');

    if ($amount <= 0 || $months <= 0 || empty($reason)) {
        $formFeedback = ['status' => 'error', 'message' => 'Please provide valid parameters for principal amount and month windows.'];
    } else {
        $monthlyDeduction = $amount / $months;
        
        // Insert with base default balance matching total principal capital 
        $insStmt = $conn->prepare("INSERT INTO employee_loans (employee_id, amount, balance, total_months, monthly_deduction, status, request_date) VALUES (?, ?, ?, ?, ?, 'Pending', NOW())");
        $insStmt->bind_param("ididd", $employeeId, $amount, $amount, $months, $monthlyDeduction);
        
        if ($insStmt->execute()) {
            header("Location: my_loans.php?saved=true");
            exit;
        } else {
            $formFeedback = ['status' => 'error', 'message' => 'Database exception saving structural parameters.'];
        }
        $insStmt->close();
    }
}

/*
|--------------------------------------------------------------------------
| RETRIEVE LOANS TRACKS DATASETS
|--------------------------------------------------------------------------
*/
$stmt = $conn->prepare("
    SELECT *, COALESCE(request_date, NOW()) as resolved_request_date
    FROM employee_loans
    WHERE employee_id = ?
    ORDER BY id DESC
");
$stmt->bind_param("i", $employeeId);
$stmt->execute();
$res = $stmt->get_result();

$rows = [];
while ($row = $res->fetch_assoc()) {
    $rows[] = $row;
}
$stmt->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Loans - Core Self Service</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="../components/sidebar.css">
    <style>
        .custom-scrollbar::-webkit-scrollbar { width: 6px; height: 6px; }
        .custom-scrollbar::-webkit-scrollbar-track { background: transparent; }
        .custom-scrollbar::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 99px; }
    </style>
</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">Finances Desk</h1>
                        <p class="text-[10px] text-slate-500 font-bold uppercase tracking-wider">Advances & Amortization Accounts</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">Corporate Advances Summary</h2>
                        <p class="text-[11px] text-slate-500 font-medium mt-0.5">Manage advance profiles, track computational baseline metrics, outstanding liabilities, and active lifecycle offsets.</p>
                    </div>
                    <div>
                        <button onclick="openLoanModal()" class="inline-flex items-center justify-center bg-slate-900 hover:bg-slate-800 text-white font-bold text-[10px] uppercase tracking-wider px-4 py-2.5 rounded-lg transition shadow-xs active:scale-95 w-full sm:w-auto">
                            Request Advance
                        </button>
                    </div>
                </div>

                <!-- Structural Feedback Notification Blocks -->
                <?php if ($formFeedback !== null): ?>
                    <div class="p-4 bg-white border <?= $formFeedback['status'] === 'success' ? 'border-slate-300' : 'border-slate-300' ?> rounded-xl text-xs font-semibold flex items-center gap-3 shadow-xs">
                        <span class="w-2 h-2 rounded-full <?= $formFeedback['status'] === 'success' ? 'bg-slate-950' : 'bg-stone-400' ?>"></span>
                        <div class="text-slate-700"><?= htmlspecialchars($formFeedback['message']) ?></div>
                    </div>
                <?php endif; ?>

                <div id="alert-toast" class="hidden p-4 bg-white border border-slate-300 rounded-xl items-center gap-3 shadow-xs">
                    <span class="w-2 h-2 rounded-full bg-slate-950"></span>
                    <div id="alert-text" class="text-xs font-semibold text-slate-700"></div>
                </div>

                <!-- Master Workspace Datatable Grid Area Container -->
                <div class="bg-white rounded-xl shadow-xs border border-slate-300/80 overflow-hidden">
                    
                    <div class="p-4 sm:p-5 border-b border-slate-200/80 flex items-center justify-between bg-stone-50/50">
                        <div>
                            <h3 class="text-xs font-black text-slate-950 uppercase tracking-wider">Loan Amortization Ledger</h3>
                            <p class="text-[10px] text-slate-500 font-medium">Outstanding structural balances and matching active calculations parameters.</p>
                        </div>
                        <span class="inline-block text-[9px] bg-stone-100 text-slate-700 border border-slate-300/80 px-2.5 py-1 rounded font-black font-mono uppercase tracking-wider">ACTIVE FEED</span>
                    </div>

                    <?php if (empty($rows)): ?>
                        <!-- Native Vector Blank Empty State Canvas Screen Block -->
                        <div class="p-8 sm:p-16 flex flex-col items-center justify-center text-center max-w-md mx-auto">
                            <div class="w-14 h-14 bg-stone-100 text-slate-700 border border-slate-300 rounded-xl flex items-center justify-center shadow-inner mb-4 relative">
                                <span class="absolute inline-flex h-full w-full rounded-xl bg-slate-400 opacity-10 animate-pulse"></span>
                                <svg class="w-6 h-6" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" viewBox="0 0 24 24">
                                    <line x1="12" y1="1" x2="12" y2="23"></line>
                                    <path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"></path>
                                </svg>
                            </div>
                            <h3 class="text-xs font-black text-slate-950 uppercase tracking-wider">No Active Loan Accounts</h3>
                            <p class="text-[11px] text-slate-500 font-medium mt-1 leading-relaxed">
                                You currently have no open cash advances, corporate ledger loans, or active financial relief requests registered inside this identity module.
                            </p>
                            <button onclick="openLoanModal()" class="mt-4 inline-flex items-center justify-center bg-white hover:bg-stone-50 text-slate-900 border border-slate-300 hover:border-slate-400 px-3 py-2 rounded-lg text-[10px] font-black uppercase tracking-wider transition shadow-xs">
                                Apply For Loan
                            </button>
                        </div>

                    <?php else: ?>
                        <!-- Mobile Responsive Fragment Panel Blocks (< md) -->
                        <div class="block md:hidden divide-y divide-slate-200/80 overflow-y-auto max-h-[600px] custom-scrollbar">
                            <?php foreach($rows as $row): 
                                $status = $row['status'] ?? 'Pending';
                                $reqDate = strtotime($row['resolved_request_date']);
                                $daysOld = round((time() - $reqDate) / 86400);
                                
                                $isExpired = (strtolower($status) === 'pending' && $daysOld > 30);
                                if ($isExpired) {
                                    $displayStatus = "Expired";
                                    $badge = "bg-stone-100 text-slate-400 border-slate-300 line-through";
                                } elseif (strtolower($status) === 'active' || strtolower($status) === 'approved') {
                                    $displayStatus = "Active";
                                    $badge = "bg-stone-100 text-slate-900 border-slate-400";
                                } elseif (strtolower($status) === 'closed' || strtolower($status) === 'paid') {
                                    $displayStatus = "Closed";
                                    $badge = "bg-stone-50 text-slate-400 border-slate-200";
                                } elseif (strtolower($status) === 'rejected') {
                                    $displayStatus = "Rejected";
                                    $badge = "bg-stone-100 text-slate-400 border-slate-300 line-through";
                                } else {
                                    $displayStatus = "Pending";
                                    $badge = "bg-stone-50 text-slate-600 border-slate-300";
                                }
                            ?>
                                <div class="p-4 flex flex-col gap-3 hover:bg-stone-50/50 transition">
                                    <div class="flex items-start justify-between">
                                        <div>
                                            <span class="text-[9px] font-black uppercase tracking-wider text-slate-400 block">Principal Balance</span>
                                            <h3 class="text-sm font-black text-slate-950 tracking-tight font-mono">
                                                ₦<?= number_format($row['amount'], 2) ?>
                                            </h3>
                                            <p class="text-[10px] font-mono font-bold text-slate-400 mt-0.5">
                                                Issued: <?= date('d M Y', $reqDate) ?>
                                            </p>
                                        </div>
                                        <span class="px-2 py-0.5 text-[9px] font-black uppercase rounded border tracking-wide <?= $badge ?>">
                                            <?= $displayStatus ?>
                                        </span>
                                    </div>
                                    <div class="grid grid-cols-3 gap-2 pt-2.5 border-t border-dashed border-slate-200 bg-stone-50/50 p-2 rounded-lg text-center">
                                        <div>
                                            <span class="block text-[8px] font-black uppercase tracking-wider text-slate-400 mb-0.5">Remaining</span>
                                            <span class="block text-xs font-mono font-black text-slate-900">₦<?= number_format($row['balance'] ?? $row['amount'], 2) ?></span>
                                        </div>
                                        <div>
                                            <span class="block text-[8px] font-black uppercase tracking-wider text-slate-400 mb-0.5">Deduction</span>
                                            <span class="block text-xs font-mono font-bold text-slate-600">₦<?= number_format($row['monthly_deduction'], 2) ?></span>
                                        </div>
                                        <div>
                                            <span class="block text-[8px] font-black uppercase tracking-wider text-slate-400 mb-0.5">Term</span>
                                            <span class="block text-xs font-mono font-bold text-slate-600"><?= $row['total_months'] ?> Mos</span>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>

                        <!-- Full Enterprise Grid Matrix Container Viewport (>= md) -->
                        <div class="hidden md:block overflow-x-auto w-full custom-scrollbar">
                            <table class="w-full border-collapse text-left">
                                <thead>
                                    <tr class="bg-stone-50 border-b border-slate-300/80 text-[10px] font-black uppercase tracking-wider text-slate-400">
                                        <th class="p-3.5 pl-6">Principal Value</th>
                                        <th class="p-3.5 text-right">Outstanding Balance</th>
                                        <th class="p-3.5 text-right">Monthly Deduction</th>
                                        <th class="p-3.5 text-center">Tenure Limit</th>
                                        <th class="p-3.5 text-center">Workflow Account State</th>
                                        <th class="p-3.5 pr-6 text-center">Origination Framework</th>
                                    </tr>
                                </thead>
                                <tbody class="divide-y divide-slate-200/80 text-xs font-medium text-slate-700">
                                    <?php foreach($rows as $row): 
                                        $status = $row['status'] ?? 'Pending';
                                        $reqDate = strtotime($row['resolved_request_date']);
                                        $daysOld = round((time() - $reqDate) / 86400);

                                        $isExpired = (strtolower($status) === 'pending' && $daysOld > 30);
                                        if ($isExpired) {
                                            $displayStatus = "Expired";
                                            $badge = "bg-stone-100 text-slate-400 border-slate-300 line-through";
                                        } elseif (strtolower($status) === 'active' || strtolower($status) === 'approved') {
                                            $displayStatus = "Active";
                                            $badge = "bg-stone-100 text-slate-900 border-slate-400";
                                        } elseif (strtolower($status) === 'closed' || strtolower($status) === 'paid') {
                                            $displayStatus = "Closed";
                                            $badge = "bg-stone-50 text-slate-400 border-slate-200";
                                        } elseif (strtolower($status) === 'rejected') {
                                            $displayStatus = "Rejected";
                                            $badge = "bg-stone-100 text-slate-400 border-slate-300 line-through";
                                        } else {
                                            $displayStatus = "Pending";
                                            $badge = "bg-stone-50 text-slate-600 border-slate-300";
                                        }
                                    ?>
                                        <tr class="hover:bg-stone-50/50 transition">
                                            <td class="p-3.5 pl-6 font-black text-slate-950 font-mono whitespace-nowrap">
                                                ₦<?= number_format($row['amount'], 2) ?>
                                            </td>
                                            <td class="p-3.5 text-right font-mono font-black text-slate-900 whitespace-nowrap">
                                                ₦<?= number_format($row['balance'] ?? $row['amount'], 2) ?>
                                            </td>
                                            <td class="p-3.5 text-right font-mono font-bold text-slate-500 whitespace-nowrap">
                                                ₦<?= number_format($row['monthly_deduction'], 2) ?>
                                            </td>
                                            <td class="p-3.5 text-center whitespace-nowrap">
                                                <span class="bg-stone-100 text-slate-900 px-2.5 py-1 border border-slate-300 rounded font-black font-mono">
                                                    <?= $row['total_months'] ?> Months
                                                </span>
                                            </td>
                                            <td class="p-3.5 text-center whitespace-nowrap">
                                                <span class="px-2.5 py-1 inline-flex text-[10px] font-black tracking-wide uppercase rounded border <?= $badge ?>">
                                                    <?= $displayStatus ?>
                                                </span>
                                            </td>
                                            <td class="p-3.5 pr-6 text-center font-mono font-bold text-slate-400 whitespace-nowrap">
                                                <?= date('d M Y', $reqDate) ?>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </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>

    <?php include 'loan_modal.php'; ?>

    <script src="../components/sidebar.js"></script>
    <script>
    function toggleSidebar() {
        const sidebar = document.getElementById('sidebar');
        const overlay = document.getElementById('sidebar-overlay');
        if(sidebar && overlay) {
            sidebar.classList.toggle('-translate-x-full');
            overlay.classList.toggle('hidden');
        }
    }

    function openLoanModal() {
        const modal = document.getElementById('loan-request-modal');
        if(modal) {
            modal.classList.remove('hidden');
            modal.classList.add('flex');
            document.body.classList.add('overflow-hidden');
        }
    }

    function closeLoanModal() {
        const modal = document.getElementById('loan-request-modal');
        if(modal) {
            modal.classList.add('hidden');
            modal.classList.remove('flex');
            document.body.classList.remove('overflow-hidden');
        }
    }

    // Run immediately rather than waiting for DOMContentLoaded -- this script
    // tag only ever executes once the surrounding markup already exists,
    // whether that's on a normal page load or after an AJAX navigation swap
    // (DOMContentLoaded only ever fires once per real browser page load).
    (() => {
        const urlParams = new URLSearchParams(window.location.search);
        if(urlParams.has('saved')) {
            const toast = document.getElementById('alert-toast');
            const text = document.getElementById('alert-text');
            if(toast && text) {
                text.innerText = "Loan application has been successfully filed and appended to organizational queues.";
                toast.classList.remove('hidden');
                toast.classList.add('flex');
            }
            window.history.replaceState({}, document.title, window.location.pathname);
        }
    })();
    </script>
</body>
</html>