<?php
include '../db.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Redirect if not authorized
if (!isset($_SESSION['mpid']) || $_SESSION['mpid'] !== 1) {
    header('Location: http://localhost/LoanApprovalPredction/admin.php');
    exit;
}

/**
 * Rule-Based Risk Scoring Algorithm
 * Calculates a programmatic risk tier based on loan metrics.
 */
function calculateRiskScore($amount, $reason) {
    $score = 0;

    // 1. Evaluate Amount Thresholds
    if ($amount > 100000) {
        $score += 50; 
    } elseif ($amount > 50000) {
        $score += 30;
    } else {
        $score += 10; 
    }

    // 2. Evaluate Loan Reason Categorization
    $reasonClean = strtolower(trim($reason));
    
    $lowRiskReasons = ['education', 'business', 'medical', 'agriculture', 'farming'];
    $medRiskReasons = ['home repair', 'renovation', 'car purchase', 'vehicle', 'investment'];
    
    $matched = false;
    foreach ($lowRiskReasons as $r) {
        if (strpos($reasonClean, $r) !== false) {
            $score += 10;
            $matched = true;
            break;
        }
    }
    if (!$matched) {
        foreach ($medRiskReasons as $r) {
            if (strpos($reasonClean, $r) !== false) {
                $score += 30;
                $matched = true;
                break;
            }
        }
    }
    if (!$matched) {
        // Unspecified, vague, or historically higher-risk reasons
        $score += 50;
    }

    // 3. Map final score to a display badge UI configuration
    if ($score >= 80) {
        return ['status' => 'High', 'color' => 'bg-red-100 text-red-800 border-red-300'];
    } elseif ($score >= 40) {
        return ['status' => 'Medium', 'color' => 'bg-yellow-100 text-yellow-800 border-yellow-300'];
    } else {
        return ['status' => 'Low', 'color' => 'bg-green-100 text-green-800 border-green-300'];
    }
}

// Show messages if any
$success_message = $_SESSION['success_message'] ?? '';
$error_message = $_SESSION['error_message'] ?? '';
unset($_SESSION['success_message'], $_SESSION['error_message']);

// Pagination settings
$limit = 5;
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$offset = ($page - 1) * $limit;
$reqPage = isset($_GET['reqPage']) ? max(1, (int)$_GET['reqPage']) : 1;
$reqOffset = ($reqPage - 1) * $limit;

// Loan acceptance handling
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['accept'], $_POST['loan_id'], $_POST['rate'], $_POST['time'])) {
    $loan_id = (int)$_POST['loan_id'];
    $rate = (float)$_POST['rate'];
    $time = (int)$_POST['time'];

    if ($rate <= 0 || $time <= 0) {
        $_SESSION['error_message'] = 'Rate and Time must be positive numbers.';
    } else {
        $query = 'SELECT LAmount, Mid, LoanStatus FROM loan_amount WHERE LoanID = ?';
        $stmt = mysqli_prepare($conn, $query);
        if ($stmt) {
            mysqli_stmt_bind_param($stmt, 'i', $loan_id);
            mysqli_stmt_execute($stmt);
            $result = mysqli_stmt_get_result($stmt);

            if ($row = mysqli_fetch_assoc($result)) {
                if ($row['LoanStatus'] !== 'Pending') {
                    $_SESSION['error_message'] = 'Loan already processed.';
                } else {
                    $lamount = $row['LAmount'];
                    $mid = $row['Mid'];
                    $interest = ($lamount * $rate * $time) / 100;
                    $total = $lamount + $interest;

                    $update_sql = 'UPDATE loan_amount SET LoanStatus = "Not_paid", Rate = ?, Time = ?, TotalAmount = ? WHERE LoanID = ?';
                    $update_stmt = mysqli_prepare($conn, $update_sql);
                    if ($update_stmt) {
                        mysqli_stmt_bind_param($update_stmt, 'didi', $rate, $time, $total, $loan_id);
                        if (mysqli_stmt_execute($update_stmt)) {
                            $insert_balance_sql = 'INSERT INTO balance (Mid, Amount) VALUES (?, ?)';
                            $insert_stmt = mysqli_prepare($conn, $insert_balance_sql);
                            if ($insert_stmt) {
                                mysqli_stmt_bind_param($insert_stmt, 'id', $mid, $lamount);
                                if (mysqli_stmt_execute($insert_stmt)) {
                                    $_SESSION['success_message'] = 'Loan request accepted successfully.';
                                } else {
                                    $_SESSION['error_message'] = 'Failed to insert into balance table: ' . mysqli_error($conn);
                                }
                                mysqli_stmt_close($insert_stmt);
                            } else {
                                $_SESSION['error_message'] = 'Failed to prepare balance insert statement: ' . mysqli_error($conn);
                            }
                        } else {
                            $_SESSION['error_message'] = 'Failed to update loan details: ' . mysqli_error($conn);
                        }
                        mysqli_stmt_close($update_stmt);
                    } else {
                        $_SESSION['error_message'] = 'Failed to prepare update statement: ' . mysqli_error($conn);
                    }
                }
            } else {
                $_SESSION['error_message'] = 'Loan ID not found.';
            }
            mysqli_stmt_close($stmt);
        } else {
            $_SESSION['error_message'] = 'Failed to prepare select statement: ' . mysqli_error($conn);
        }
    }

    header("Location: ?page=$page&reqPage=$reqPage#pending");
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Loan Management</title>
    <link rel="icon" href="../images/Icon.png">
    <script src="../CSS/tailwindcss.css"></script>
</head>
<body class="bg-gray-100">
    <header class="sticky top-0 z-50">
        <?php include '../includes/newnavbar.php'; ?>
    </header>
    <?php if ($success_message): ?>
        <p class="text-center text-green-600 font-semibold p-2"><?php echo htmlspecialchars($success_message, ENT_QUOTES, 'UTF-8'); ?></p>
    <?php elseif ($error_message): ?>
        <p class="text-center text-red-600 font-semibold p-2"><?php echo htmlspecialchars($error_message, ENT_QUOTES, 'UTF-8'); ?></p>
    <?php endif; ?>
    <h1 id="details" class="text-2xl font-bold text-center p-4 bg-green-300">Loan Details</h1>
    <?php
    $loan_query = 'SELECT la.*, m.MembersName 
                   FROM loan_amount la 
                   LEFT JOIN members m ON la.Mid = m.Mid 
                   WHERE la.LoanStatus != "Pending" 
                   LIMIT ?, ?';
    $stmt = mysqli_prepare($conn, $loan_query);
    if ($stmt) {
        mysqli_stmt_bind_param($stmt, 'ii', $offset, $limit);
        mysqli_stmt_execute($stmt);
        $loan_result = mysqli_stmt_get_result($stmt);

        if (mysqli_num_rows($loan_result) > 0) {
            ?>
            <div class="flex justify-center p-4 overflow-x-auto">
                <table class="border border-collapse border-black bg-white shadow-sm">
                    <thead>
                        <tr class="bg-green-200">
                            <th class="border p-2">ID</th>
                            <th class="border p-2">Name</th>
                            <th class="border p-2">Amount</th>
                            <th class="border p-2">Date</th>
                            <th class="border p-2">Return Date</th>
                            <th class="border p-2">Status</th>
                            <th class="border p-2">Reason</th>
                            <th class="border p-2">Rate</th>
                            <th class="border p-2">Time</th>
                            <th class="border p-2">Total</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php while ($row = mysqli_fetch_assoc($loan_result)): ?>
                            <tr class="text-center hover:bg-gray-50">
                                <td class="border p-2"><?php echo htmlspecialchars($row['LoanID'], ENT_QUOTES, 'UTF-8'); ?></td>
                                <td class="border p-2"><?php echo htmlspecialchars($row['MembersName'] ?? 'N/A', ENT_QUOTES, 'UTF-8'); ?></td>
                                <td class="border p-2"><?php echo number_format($row['LAmount'], 2); ?></td>
                                <td class="border p-2"><?php echo htmlspecialchars($row['LDate'], ENT_QUOTES, 'UTF-8'); ?></td>
                                <td class="border p-2"><?php echo htmlspecialchars($row['ReturnDate'] ?? 'N/A', ENT_QUOTES, 'UTF-8'); ?></td>
                                <td class="border p-2"><?php echo htmlspecialchars($row['LoanStatus'], ENT_QUOTES, 'UTF-8'); ?></td>
                                <td class="border p-2"><?php echo htmlspecialchars($row['LoanReason'], ENT_QUOTES, 'UTF-8'); ?></td>
                                <td class="border p-2"><?php echo number_format($row['Rate'], 2); ?></td>
                                <td class="border p-2"><?php echo htmlspecialchars($row['Time'], ENT_QUOTES, 'UTF-8'); ?></td>
                                <td class="border p-2"><?php echo number_format($row['TotalAmount'], 2); ?></td>
                            </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>

            <div class="flex justify-center mt-2 mb-6">
                <ul class="flex gap-2">
                    <?php
                    $total_q = 'SELECT COUNT(*) AS total FROM loan_amount WHERE LoanStatus != "Pending"';
                    $total_res = mysqli_query($conn, $total_q);
                    $total_row = mysqli_fetch_assoc($total_res);
                    $total_pages = ceil($total_row['total'] / $limit);

                    for ($i = 1; $i <= $total_pages; $i++):
                        $active = ($i === $page) ? 'bg-blue-800' : 'bg-blue-600';
                    ?>
                        <li class="text-white px-3 py-1 rounded <?php echo $active; ?>">
                            <a href="?page=<?php echo $i; ?>&reqPage=<?php echo $reqPage; ?>#details"><?php echo $i; ?></a>
                        </li>
                    <?php endfor; ?>
                </ul>
            </div>
            <?php
        } else {
            ?>
            <p class="text-center text-red-500 my-4">No Loan Records Found</p>
            <?php
        }
        mysqli_stmt_close($stmt);
    } else {
        ?>
        <p class="text-center text-red-500 my-4">Error preparing loan query: <?php echo mysqli_error($conn); ?></p>
        <?php
    }
    ?>

    <hr class="my-10 border-t-4 border-teal-400">

    <h1 id="pending" class="text-2xl font-bold text-center p-4 bg-yellow-300">New Requests (Pending)</h1>
    <?php
    $pending_query = 'SELECT la.*, m.MembersName 
                      FROM loan_amount la 
                      LEFT JOIN members m ON la.Mid = m.Mid 
                      WHERE la.LoanStatus = "Pending" 
                      LIMIT ?, ?';
                      
    $stmt = mysqli_prepare($conn, $pending_query);
    if ($stmt) {
        mysqli_stmt_bind_param($stmt, 'ii', $reqOffset, $limit);
        mysqli_stmt_execute($stmt);
        $pending_result = mysqli_stmt_get_result($stmt);

        if (mysqli_num_rows($pending_result) > 0) {
            ?>
            <div class="flex justify-center p-4 overflow-x-auto">
                <table class="border border-collapse border-black bg-white shadow-sm">
                    <thead>
                        <tr class="bg-yellow-200">
                            <th class="border p-2">ID</th>
                            <th class="border p-2">Name</th>
                            <th class="border p-2">Amount</th>
                            <th class="border p-2">Date</th>
                            <th class="border p-2">Return Date</th>
                            <th class="border p-2">Status</th>
                            <th class="border p-2">Reason</th>
                            <th class="border p-2">Risk Rule Assessment</th>
                            <th class="border p-2">Rate</th>
                            <th class="border p-2">Time</th>
                            <th class="border p-2">Total</th>
                            <th class="border p-2">Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        while ($row = mysqli_fetch_assoc($pending_result)): 
                            // Compute operational risk profile at runtime
                            $riskProfile = calculateRiskScore($row['LAmount'], $row['LoanReason']);
                        ?>
                            <tr class="text-center hover:bg-gray-50">
                                <td class="border p-2"><?php echo htmlspecialchars($row['LoanID'], ENT_QUOTES, 'UTF-8'); ?></td>
                                <td class="border p-2"><?php echo htmlspecialchars($row['MembersName'] ?? 'N/A', ENT_QUOTES, 'UTF-8'); ?></td>
                                <td class="border p-2"><?php echo number_format($row['LAmount'], 2); ?></td>
                                <td class="border p-2"><?php echo htmlspecialchars($row['LDate'], ENT_QUOTES, 'UTF-8'); ?></td>
                                <td class="border p-2"><?php echo htmlspecialchars($row['ReturnDate'] ?? 'N/A', ENT_QUOTES, 'UTF-8'); ?></td>
                                <td class="border p-2"><?php echo htmlspecialchars($row['LoanStatus'], ENT_QUOTES, 'UTF-8'); ?></td>
                                <td class="border p-2"><?php echo htmlspecialchars($row['LoanReason'], ENT_QUOTES, 'UTF-8'); ?></td>
                                <td class="border p-2 font-bold">
                                    <span class="px-2.5 py-1 rounded-full border text-xs font-semibold <?php echo $riskProfile['color']; ?>">
                                        <?php echo $riskProfile['status']; ?> Risk
                                    </span>
                                </td>
                                <td class="border p-2"><?php echo number_format($row['Rate'] ?? 0, 2); ?></td>
                                <td class="border p-2"><?php echo htmlspecialchars($row['Time'] ?? 'N/A', ENT_QUOTES, 'UTF-8'); ?></td>
                                <td class="border p-2 openings_count"><?php echo number_format($row['TotalAmount'] ?? 0, 2); ?></td>
                                <td class="border p-2">
                                    <button 
                                        onclick="openModal(<?php echo $row['LoanID']; ?>, '<?php echo $riskProfile['status']; ?>')"
                                        class="bg-green-500 text-white px-3 py-1 rounded hover:bg-green-700 transition-colors">
                                        Accept
                                    </button>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>

            <div class="flex justify-center mt-2 mb-6">
                <ul class="flex gap-2">
                    <?php
                    $req_total_q = 'SELECT COUNT(*) AS total FROM loan_amount WHERE LoanStatus = "Pending"';
                    $req_total_res = mysqli_query($conn, $req_total_q);
                    $req_total_row = mysqli_fetch_assoc($req_total_res);
                    $req_total_pages = ceil($req_total_row['total'] / $limit);

                    for ($i = 1; $i <= $req_total_pages; $i++):
                        $active = ($i === $reqPage) ? 'bg-yellow-600' : 'bg-yellow-500';
                    ?>
                        <li class="text-white px-3 py-1 rounded <?php echo $active; ?>">
                            <a href="?page=<?php echo $page; ?>&reqPage=<?php echo $i; ?>#pending"><?php echo $i; ?></a>
                        </li>
                    <?php endfor; ?>
                </ul>
            </div>
            <?php
        } else {
            ?>
            <p class="text-center text-red-500 my-4">No Pending Requests Found</p>
            <?php
        }
        mysqli_stmt_close($stmt);
    } else {
        ?>
        <p class="text-center text-red-500 my-4">Error preparing pending query: <?php echo mysqli_error($conn); ?></p>
        <?php
    }
    ?>

    <div id="acceptModal" class="fixed inset-0 bg-gray-900 bg-opacity-50 flex items-center justify-center hidden z-50">
        <div class="bg-white rounded-lg p-6 shadow-xl w-96 relative mx-4">
            <h2 class="text-xl font-bold mb-2">Accept Loan Request</h2>
            <p class="text-xs text-gray-500 mb-4">The system has automatically modified the suggested baseline rate according to computed risk metrics.</p>
            
            <form method="POST" id="modalForm" action="?page=<?php echo $page; ?>&reqPage=<?php echo $reqPage; ?>#pending">
                <input type="hidden" name="loan_id" id="modalLoanId">
                
                <label class="block mb-2 font-semibold text-sm text-gray-700">Rate (%)</label>
                <input type="number" name="rate" id="modalRate" step="0.01" min="0.01" class="border rounded px-3 py-1.5 w-full mb-4 focus:outline-none focus:ring-2 focus:ring-green-400" required>
                
                <label class="block mb-2 font-semibold text-sm text-gray-700">Time (Years)</label>
                <input type="number" name="time" value="1" step="1" min="1" class="border rounded px-3 py-1.5 w-full mb-4 focus:outline-none focus:ring-2 focus:ring-green-400" required>
                
                <div class="flex justify-end gap-2 mt-2">
                    <button type="button" onclick="closeModal()" class="px-4 py-1.5 border border-gray-400 rounded hover:bg-gray-100 transition-colors">Cancel</button>
                    <button type="submit" name="accept" class="bg-green-600 text-white px-4 py-1.5 rounded hover:bg-green-800 transition-colors">Accept</button>
                </div>
            </form>
        </div>
    </div>
    <script>
        function openModal(loanId, riskStatus) {
            document.getElementById('modalLoanId').value = loanId;
            
            // Explicit rate calibration based on structural algorithmic evaluation
            const rateField = document.getElementById('modalRate');
            if (riskStatus === 'High') {
                rateField.value = "7.50";
            } else if (riskStatus === 'Medium') {
                rateField.value = "5.00";
            } else {
                rateField.value = "3.00";
            }

            document.getElementById('acceptModal').classList.remove('hidden');
        }

        function closeModal() {
            document.getElementById('acceptModal').classList.add('hidden');
        }
    </script>
    </body>
</html>