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

// Redirect to login if the admin is not authenticated
if (!isset($_SESSION['admin_id'])) {
    header("Location: index.php");
    exit();
}

// Include Database Connection
require_once "../account/include/db.php";

// --- ACTION LOGIC (Approve / Decline / Delete / Edit) ---
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];
    $loan_id = (int)$_POST['loan_id'];

    // 1. DELETE ACTION
    if ($action === 'delete') {
        $del_q = "DELETE FROM `loan_applications` WHERE `id` = ?";
        if ($stmt = mysqli_prepare($conn, $del_q)) {
            mysqli_stmt_bind_param($stmt, "i", $loan_id);
            if (mysqli_stmt_execute($stmt)) {
                $_SESSION['swal_success'] = "Loan application record deleted.";
                $_SESSION['swal_title'] = "Deleted";
            }
            mysqli_stmt_close($stmt);
        }
    }

    // 2. APPROVE ACTION
    elseif ($action === 'approve') {
        // Fetch months to calculate due date
        $fetch_q = "SELECT duration_months FROM `loan_applications` WHERE id = ? LIMIT 1";
        $months = 0;
        if ($stmt = mysqli_prepare($conn, $fetch_q)) {
            mysqli_stmt_bind_param($stmt, "i", $loan_id);
            mysqli_stmt_execute($stmt);
            mysqli_stmt_bind_result($stmt, $m);
            if (mysqli_stmt_fetch($stmt)) { $months = $m; }
            mysqli_stmt_close($stmt);
        }

        $due_date = date('Y-m-d H:i:s', strtotime("+$months months"));
        $upd_q = "UPDATE `loan_applications` SET `status` = 'approved', `approved_at` = NOW(), `due_date` = ? WHERE `id` = ?";
        
        if ($stmt = mysqli_prepare($conn, $upd_q)) {
            mysqli_stmt_bind_param($stmt, "si", $due_date, $loan_id);
            if (mysqli_stmt_execute($stmt)) {
                $_SESSION['swal_success'] = "Loan approved. Repayment schedule activated.";
                $_SESSION['swal_title'] = "Authorized";
            }
            mysqli_stmt_close($stmt);
        }
    }

    // 3. DECLINE ACTION
    elseif ($action === 'decline') {
        $reason = mysqli_real_escape_string($conn, $_POST['admin_notes'] ?? 'Insufficient requirements');
        $upd_q = "UPDATE `loan_applications` SET `status` = 'rejected', `admin_notes` = ? WHERE `id` = ?";
        if ($stmt = mysqli_prepare($conn, $upd_q)) {
            mysqli_stmt_bind_param($stmt, "si", $reason, $loan_id);
            if (mysqli_stmt_execute($stmt)) {
                $_SESSION['swal_success'] = "The loan request has been rejected.";
                $_SESSION['swal_title'] = "Declined";
            }
            mysqli_stmt_close($stmt);
        }
    }

    // 4. EDIT ACTION
    elseif ($action === 'edit') {
        $amt      = (float)$_POST['amount'];
        $int_rate = (float)$_POST['interest_rate'];
        $dur      = (int)$_POST['duration_months'];
        $status   = mysqli_real_escape_string($conn, $_POST['status']);

        $upd_q = "UPDATE `loan_applications` SET `amount` = ?, `interest_rate` = ?, `duration_months` = ?, `status` = ? WHERE `id` = ?";
        if ($stmt = mysqli_prepare($conn, $upd_q)) {
            mysqli_stmt_bind_param($stmt, "ddisi", $amt, $int_rate, $dur, $status, $loan_id);
            if (mysqli_stmt_execute($stmt)) {
                $_SESSION['swal_success'] = "Loan parameters updated.";
                $_SESSION['swal_title'] = "Updated";
            }
            mysqli_stmt_close($stmt);
        }
    }

    header("Location: loan_requests.php?page=" . (isset($_GET['page']) ? (int)$_GET['page'] : 1));
    exit();
}

// --- PAGINATION & FETCH ---
$limit = 10;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $limit;

$total_res = mysqli_query($conn, "SELECT COUNT(*) as total FROM `loan_applications` ");
$total_data = mysqli_fetch_assoc($total_res);
$total_records = $total_data['total'] ?? 0;
$total_pages = ceil($total_records / $limit);

$query = "SELECT l.*, u.full_name, u.username 
          FROM `loan_applications` l 
          JOIN `users` u ON l.user_id = u.id 
          ORDER BY l.applied_at DESC 
          LIMIT $limit OFFSET $offset";
$result = mysqli_query($conn, $query);

include 'includes/header.php';
include 'includes/sidebar.php';
?>

<style>
    body { font-family: 'Inter', sans-serif !important; }
    .status-pill { padding: 2px 8px; border-radius: 4px; font-size: 10px; font-weight: 700; text-transform: uppercase; }
    .pagination-btn { transition: all 0.2s; border: 1px solid #1e293b; color: #94a3b8; }
    .pagination-btn.active { background: #3b82f6; border-color: #3b82f6; color: white; }
</style>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<main class="md:ml-64 p-4 md:p-6 min-h-[calc(100vh-65px)] bg-slate-950 relative z-10">
    
    <div class="mb-8">
        <div class="text-[10px] font-bold text-blue-500 tracking-widest uppercase mb-1">Credit Facilities</div>
        <h1 class="text-3xl font-bold text-white tracking-tight">Loan Applications</h1>
        <p class="text-slate-400 mt-1 text-sm">Review and manage financial assistance requests</p>
    </div>

    <div class="bg-slate-900 border border-slate-800 rounded-xl overflow-hidden shadow-2xl flex flex-col">
        <div class="overflow-x-auto">
            <table class="w-full text-left border-collapse min-w-[1100px]">
                <thead>
                    <tr class="border-b border-slate-800 bg-slate-950 text-xs text-slate-400 uppercase tracking-widest">
                        <th class="p-4">Applicant</th>
                        <th class="p-4 text-center">Loan Terms</th>
                        <th class="p-4 text-center">Repayment Details</th>
                        <th class="p-4">Employment / Income</th>
                        <th class="p-4 text-center">Status</th>
                        <th class="p-4 text-right">Actions</th>
                    </tr>
                </thead>
                <tbody class="text-sm text-slate-300 divide-y divide-slate-800/50">
                    <?php if($result && mysqli_num_rows($result) > 0): ?>
                        <?php while ($row = mysqli_fetch_assoc($result)): ?>
                        <tr class="hover:bg-slate-800/30 transition-colors">
                            <td class="p-4">
                                <div class="font-bold text-slate-100"><?php echo htmlspecialchars($row['full_name'] ?? ''); ?></div>
                                <div class="text-[10px] text-slate-500">@<?php echo htmlspecialchars($row['username'] ?? ''); ?> • <?php echo date('M d, Y', strtotime($row['applied_at'])); ?></div>
                            </td>
                            <td class="p-4 text-center">
                                <div class="text-emerald-400 font-bold">$<?php echo number_format($row['amount'] ?? 0, 2); ?></div>
                                <div class="text-[10px] text-slate-400"><?php echo ($row['duration_months'] ?? 0); ?> Months @ <?php echo ($row['interest_rate'] ?? 0); ?>%</div>
                            </td>
                            <td class="p-4 text-center">
                                <div class="text-white font-semibold">$<?php echo number_format($row['monthly_payment'] ?? 0, 2); ?>/mo</div>
                                <div class="text-[10px] text-slate-500 italic">Total: $<?php echo number_format($row['total_repayment'] ?? 0, 2); ?></div>
                            </td>
                            <td class="p-4">
                                <div class="text-slate-200 font-medium"><?php echo htmlspecialchars($row['employment_status'] ?? 'N/A'); ?></div>
                                <div class="text-[11px] text-emerald-500">Income: $<?php echo number_format($row['monthly_income'] ?? 0, 2); ?></div>
                            </td>
                            <td class="p-4 text-center">
                                <?php if(($row['status'] ?? '') == 'pending'): ?>
                                    <span class="status-pill bg-amber-500/10 text-amber-500 border border-amber-500/20">Review</span>
                                <?php elseif(($row['status'] ?? '') == 'approved'): ?>
                                    <span class="status-pill bg-emerald-500/10 text-emerald-500 border border-emerald-500/20">Active</span>
                                <?php else: ?>
                                    <span class="status-pill bg-red-500/10 text-red-400 border border-red-500/20"><?php echo htmlspecialchars($row['status'] ?? 'N/A'); ?></span>
                                <?php endif; ?>
                            </td>
                            <td class="p-4 text-right">
                                <div class="flex justify-end gap-3 items-center">
                                    <?php if(($row['status'] ?? '') == 'pending'): ?>
                                        <button onclick='loanModal("approve", <?php echo json_encode($row); ?>)' class="text-emerald-500 text-[10px] font-bold uppercase hover:underline">Approve</button>
                                        <button onclick='loanModal("decline", <?php echo json_encode($row); ?>)' class="text-orange-500 text-[10px] font-bold uppercase hover:underline">Decline</button>
                                    <?php endif; ?>
                                    <button onclick='loanModal("edit", <?php echo json_encode($row); ?>)' class="text-blue-500 text-[10px] font-bold uppercase hover:underline">Edit</button>
                                    <form method="POST" class="inline" onsubmit="return confirm('Archive this request?');">
                                        <input type="hidden" name="loan_id" value="<?php echo $row['id']; ?>">
                                        <input type="hidden" name="action" value="delete">
                                        <button type="submit" class="text-red-500 text-[10px] font-bold uppercase hover:underline">Delete</button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr><td colspan="6" class="p-12 text-center text-slate-500 italic">No loan applications currently on record.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        <?php if($total_pages > 1): ?>
        <div class="p-4 border-t border-slate-800 bg-slate-900/50 flex items-center justify-between">
            <div class="text-xs text-slate-500">Page <?php echo $page; ?> of <?php echo $total_pages; ?></div>
            <div class="flex gap-1">
                <?php if($page > 1): ?>
                    <a href="?page=<?php echo $page - 1; ?>" class="pagination-btn px-3 py-1.5 rounded text-xs">Prev</a>
                <?php endif; ?>
                <?php for($i = max(1, $page-1); $i <= min($total_pages, $page+1); $i++): ?>
                    <a href="?page=<?php echo $i; ?>" class="pagination-btn px-3 py-1.5 rounded text-xs <?php echo ($i == $page) ? 'active' : ''; ?>"><?php echo $i; ?></a>
                <?php endfor; ?>
                <?php if($page < $total_pages): ?>
                    <a href="?page=<?php echo $page + 1; ?>" class="pagination-btn px-3 py-1.5 rounded text-xs">Next</a>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>
    </div>
</main>

<script>
function loanModal(mode, data = null) {
    let title = 'Loan Control';
    let btnText = 'Proceed';
    let btnColor = '#3b82f6';
    let html = '';

    if (mode === 'approve') {
        title = 'Approve Loan Application?';
        btnText = 'Confirm Approval';
        btnColor = '#10b981';
        html = `
            <form id="loanForm" method="POST">
                <input type="hidden" name="action" value="approve">
                <input type="hidden" name="loan_id" value="${data.id}">
                <p class="text-slate-400 text-sm">Authorizing <b>$${data.amount}</b> for ${data.full_name}. Due date will be calculated automatically.</p>
            </form>
        `;
    } else if (mode === 'decline') {
        title = 'Decline Loan Request';
        btnText = 'Confirm Rejection';
        btnColor = '#f59e0b';
        html = `
            <form id="loanForm" method="POST" class="text-left">
                <input type="hidden" name="action" value="decline">
                <input type="hidden" name="loan_id" value="${data.id}">
                <label class="text-[10px] uppercase font-bold text-slate-500">Reason for Rejection</label>
                <textarea name="admin_notes" class="w-full bg-slate-950 border border-slate-800 p-2.5 rounded text-white mt-1 h-24" placeholder="e.g. Monthly income does not meet minimum requirements."></textarea>
            </form>
        `;
    } else if (mode === 'edit') {
        title = 'Modify Loan Terms';
        btnText = 'Save Changes';
        html = `
            <form id="loanForm" method="POST" class="text-left grid grid-cols-2 gap-4 mt-2">
                <input type="hidden" name="action" value="edit">
                <input type="hidden" name="loan_id" value="${data.id}">
                <div>
                    <label class="text-[10px] uppercase font-bold text-slate-500">Principal ($)</label>
                    <input type="number" name="amount" value="${data.amount}" step="0.01" required class="w-full bg-slate-950 border border-slate-800 p-2.5 rounded text-white mt-1">
                </div>
                <div>
                    <label class="text-[10px] uppercase font-bold text-slate-500">Interest Rate (%)</label>
                    <input type="number" name="interest_rate" value="${data.interest_rate}" step="0.01" required class="w-full bg-slate-950 border border-slate-800 p-2.5 rounded text-white mt-1">
                </div>
                <div>
                    <label class="text-[10px] uppercase font-bold text-slate-500">Duration (Months)</label>
                    <input type="number" name="duration_months" value="${data.duration_months}" required class="w-full bg-slate-950 border border-slate-800 p-2.5 rounded text-white mt-1">
                </div>
                <div>
                    <label class="text-[10px] uppercase font-bold text-slate-500">Status</label>
                    <select name="status" class="w-full bg-slate-950 border border-slate-800 p-2.5 rounded text-white mt-1">
                        <option value="pending" ${data.status === 'pending' ? 'selected' : ''}>Pending</option>
                        <option value="approved" ${data.status === 'approved' ? 'selected' : ''}>Approved</option>
                        <option value="rejected" ${data.status === 'rejected' ? 'selected' : ''}>Rejected</option>
                        <option value="repaid" ${data.status === 'repaid' ? 'selected' : ''}>Fully Repaid</option>
                    </select>
                </div>
            </form>
        `;
    }

    Swal.fire({
        title: title,
        background: '#0f172a',
        color: '#f1f5f9',
        html: html,
        showCancelButton: true,
        confirmButtonText: btnText,
        confirmButtonColor: btnColor,
        cancelButtonColor: '#1e293b',
        preConfirm: () => { document.getElementById('loanForm').submit(); }
    });
}

<?php if (isset($_SESSION['swal_success'])): ?>
    Swal.fire({ title: '<?php echo $_SESSION['swal_title']; ?>', text: '<?php echo $_SESSION['swal_success']; ?>', icon: 'success', background: '#0f172a', color: '#f1f5f9', confirmButtonColor: '#3b82f6' });
    <?php unset($_SESSION['swal_success'], $_SESSION['swal_title']); ?>
<?php endif; ?>
</script>

<?php include 'includes/footer.php'; ?>