<?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 Check
if (!isset($_SESSION['user_id'])) {
    header("Location: ../login.php");
    exit;
}

// 2. Authorization Check
if (!isset($_SESSION['role']) || strtolower(trim($_SESSION['role'])) !== 'manager') {
    die("Unauthorized access. You must be a manager to view this page.");
}

// 3. Handle Approval Action Securely
if (isset($_GET['approve'])) {
    $id = intval($_GET['approve']);

    $stmt = $conn->prepare("UPDATE employee_loans SET manager_status = 'Approved' WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $stmt->close();

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

// 4. Handle Rejection Action Securely
if (isset($_GET['reject'])) {
    $id = intval($_GET['reject']);

    $stmt = $conn->prepare("UPDATE employee_loans SET manager_status = 'Rejected', status = 'Rejected' WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $stmt->close();

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

// 5. Fetch Pending Records Safely
$stmt = $conn->prepare("
    SELECT l.*, e.name 
    FROM employee_loans l 
    LEFT JOIN employees e ON e.id = l.employee_id 
    WHERE l.manager_status = 'Pending' 
    ORDER BY l.id DESC
");
$stmt->execute();
$res = $stmt->get_result();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manager Loan Approvals - Departmental Verification</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">Manager Approvals</h1>
                        <p class="text-[10px] text-slate-500 font-bold uppercase tracking-wider">Departmental Verification</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">Manager Loan Approval Panel</h2>
                        <p class="text-[11px] text-slate-500 font-medium mt-0.5">Evaluate baseline department requests prior to forwarding parameters down to human resources for payout clearance.</p>
                    </div>
                </div>

                <div class="space-y-2">
                    <h3 class="text-[10px] font-black text-slate-500 uppercase tracking-wider px-1">Awaiting Initial Line Manager Review</h3>
                    <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">Applicant Employee</th>
                                        <th class="p-3 text-right">Requested Principal</th>
                                        <th class="p-3 text-right">Cycle Repayment</th>
                                        <th class="p-3 text-center w-36">Tenure Limit</th>
                                        <th class="p-3 text-center w-64">Authorization Controls</th>
                                    </tr>
                                </thead>
                                <tbody class="divide-y divide-slate-200 font-bold text-slate-800">
                                    <?php if($res->num_rows == 0): ?>
                                    <tr>
                                        <td colspan="5" class="p-8 text-center text-slate-500 font-semibold bg-stone-50/50">
                                            No operational loan requests currently awaiting initial manager evaluations.
                                        </td>
                                    </tr>
                                    <?php else: ?>
                                        <?php while($row = $res->fetch_assoc()): ?>
                                        <tr class="hover:bg-stone-50/40 transition">
                                            <td class="p-3 text-slate-950 font-extrabold whitespace-nowrap">
                                                <?= htmlspecialchars($row['name'] ?? 'Unknown Employee') ?>
                                            </td>
                                            <td class="p-3 text-right font-mono text-[11px] text-slate-950 font-black whitespace-nowrap">
                                                ₦<?= number_format($row['amount'], 2) ?>
                                            </td>
                                            <td class="p-3 text-right font-mono text-[11px] text-slate-600 whitespace-nowrap">
                                                ₦<?= number_format($row['monthly_deduction'], 2) ?>
                                            </td>
                                            <td class="p-3 text-center font-mono text-[11px] text-slate-600 whitespace-nowrap">
                                                <?= intval($row['total_months']) ?> Months
                                            </td>
                                            <td class="p-2 text-center whitespace-nowrap">
                                                <div class="flex items-center justify-center gap-1.5">
                                                    <a href="?approve=<?= $row['id'] ?>" 
                                                       onclick="return confirm('Endorse this request? It will be systematically escalated to Human Resources for final approval.')"
                                                       class="bg-emerald-600 hover:bg-emerald-700 text-white font-bold text-[10px] tracking-tight uppercase px-3 py-1 rounded transition shadow-xs">
                                                        Endorse Request
                                                    </a>
                                                    <a href="?reject=<?= $row['id'] ?>" 
                                                       onclick="return confirm('Confirm permanent rejection? This file will be archived instantly under a rejected status.')"
                                                       class="bg-rose-600 hover:bg-rose-700 text-white font-bold text-[10px] tracking-tight uppercase px-3 py-1 rounded transition shadow-xs">
                                                        Reject
                                                    </a>
                                                </div>
                                            </td>
                                        </tr>
                                        <?php endwhile; ?>
                                    <?php 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>
<?php 
$stmt->close();
$conn->close();
?>