<?php
// Start PHP main block
include '../db.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
} // End session check

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

// Handle loan acceptance
$success_message = '';
$error_message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['accept'], $_POST['loan_id'], $_POST['rate'], $_POST['time'])) {
    // Start loan acceptance block
    $loan_id = (int)$_POST['loan_id'];
    $rate = (float)$_POST['rate'];
    $time = (int)$_POST['time'];

    // Validate inputs
    if ($rate <= 0 || $time <= 0) {
        $error_message = 'Rate and Time must be positive numbers.';
    } else {
        // Fetch loan details
        $query = 'SELECT LAmount, Mid FROM loan_amount WHERE LoanID = ?';
        $stmt = mysqli_prepare($conn, $query);
        if ($stmt) {
            // Start select statement block
            mysqli_stmt_bind_param($stmt, 'i', $loan_id);
            mysqli_stmt_execute($stmt);
            $result = mysqli_stmt_get_result($stmt);

            if ($row = mysqli_fetch_assoc($result)) {
                // Start loan found block
                $lamount = $row['LAmount']; // Principal amount, no interest
                $mid = $row['Mid'];
                $interest = ($lamount * $rate * $time) / 100;
                $total = $lamount + $interest; // Total for loan_amount table only

                // Update loan status and details
                $update_sql = 'UPDATE loan_amount 
                               SET LoanStatus = "Not_paid", Rate = ?, Time = ?, TotalAmount = ? 
                               WHERE LoanID = ?';
                $update_stmt = mysqli_prepare($conn, $update_sql);
                if ($update_stmt) {
                    // Start update statement block
                    mysqli_stmt_bind_param($update_stmt, 'didi', $rate, $time, $total, $loan_id);
                    if (mysqli_stmt_execute($update_stmt)) {
                        // Start balance insert block
                        // Insert only Mid and LAmount (principal, no interest) into balance
                        $insert_balance_sql = 'INSERT INTO balance (Mid, Amount) VALUES (?, ?)';
                        $insert_stmt = mysqli_prepare($conn, $insert_balance_sql);
                        if ($insert_stmt) {
                            // Start insert statement block
                            mysqli_stmt_bind_param($insert_stmt, 'id', $mid, $lamount);
                            if (mysqli_stmt_execute($insert_stmt)) {
                                $success_message = 'Loan request accepted successfully.';
                            } else {
                                $error_message = 'Failed to insert into balance table: ' . mysqli_error($conn);
                            }
                            mysqli_stmt_close($insert_stmt);
                        } else {
                            $error_message = 'Failed to prepare balance insert statement: ' . mysqli_error($conn);
                        } // End insert statement block
                    } else {
                        $error_message = 'Failed to update loan details: ' . mysqli_error($conn);
                    }
                    mysqli_stmt_close($update_stmt);
                } else {
                    $error_message = 'Failed to prepare update statement: ' . mysqli_error($conn);
                } // End update statement block
            } else {
                $error_message = 'Loan ID not found.';
            } // End loan found block
            mysqli_stmt_close($stmt);
        } else {
            $error_message = 'Failed to prepare select statement: ' . mysqli_error($conn);
        } // End select statement block
    } // End validation block
} // End loan acceptance block

// 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;
// End PHP main block
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Loan Management</title>
    <link rel="icon" href="../images/Icon.png">
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100">
    <!-- Start Header Section -->
    <header>
        <?php include '../includes/newnavbar.php'; ?>
    </header>
    <!-- End Header Section -->

    <!-- Start Messages Section -->
    <?php if ($success_message): ?>
        <p class="text-center text-green-600 font-semibold"><?php echo htmlspecialchars($success_message, ENT_QUOTES, 'UTF-8'); ?></p>
    <?php elseif ($error_message): ?>
        <p class="text-center text-red-600 font-semibold"><?php echo htmlspecialchars($error_message, ENT_QUOTES, 'UTF-8'); ?></p>
    <?php endif; ?>
    <!-- End Messages Section -->

    <!-- Start Loan Details Section -->
    <h1 id="details" class="text-2xl font-bold text-center p-4 bg-green-300">Loan Details</h1>
    <?php
    // Start PHP block for loan details
    $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) {
        // Start loan query block
        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) {
            // Start loan results block
            ?>
            <div class="flex justify-center">
                <table class="border border-collapse border-black bg-white">
                    <thead>
                        <tr class="bg-green-200">
                            <th class="border p-2">ID49</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">
                                <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>

            <!-- Start Pagination for Loan Details -->
            <div class="flex justify-center mt-4">
                <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>
            <!-- End Pagination for Loan Details -->
            <?php
        } else {
            // Start no loan results block
            ?>
            <p class="text-center text-red-500">No Loan Records Found</p>
            <?php
        } // End no loan results block
        mysqli_stmt_close($stmt);
    } else {
        // Start loan query error block
        ?>
        <p class="text-center text-red-500">Error preparing loan query: <?php echo mysqli_error($conn); ?></p>
        <?php
    } // End loan query block
    // End PHP block for loan details
    ?>

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

    <!-- Start Pending Requests Section -->
    <h1 id="pending" class="text-2xl font-bold text-center p-4 bg-yellow-300">New Requests (Pending)</h1>
    <?php
    // Start PHP block for pending requests
    $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) {
        // Start pending query block
        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) {
            // Start pending results block
            ?>
            <div class="flex justify-center">
                <table class="border border-collapse border-black bg-white">
                    <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">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)): ?>
                            <tr class="text-center">
                                <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'] ?? 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"><?php echo number_format($row['TotalAmount'] ?? 0, 2); ?></td>
                                <td class="border p-2">
                                    <button 
                                        onclick="openModal(<?php echo $row['LoanID']; ?>)"
                                        class="bg-green-500 text-white px-3 py-1 rounded hover:bg-green-700">
                                        Accept
                                    </button>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>

            <!-- Start Pagination for Pending Requests -->
            <div class="flex justify-center mt-4">
                <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>
            <!-- End Pagination for Pending Requests -->
            <?php
        } else {
            // Start no pending results block
            ?>
            <p class="text-center text-red-500">No Pending Requests Found</p>
            <?php
        } // End pending results block
        mysqli_stmt_close($stmt);
    } else {
        // Start pending query error block
        ?>
        <p class="text-center text-red-500">Error preparing pending query: <?php echo mysqli_error($conn); ?></p>
        <?php
    } // End pending query block
    // End PHP block for pending requests
    ?>

    <!-- Start Modal Section -->
    <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-md w-96 relative">
            <h2 class="text-xl font-bold mb-4">Accept Loan Request</h2>
            <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">Rate (%)</label>
                <input type="number" name="rate" value="3" step="0.01" min="0.01" class="border px-2 py-1 w-full mb-4" required>
                <label class="block mb-2 font-semibold">Time (Years)</label>
                <input type="number" name="time" value="1" step="1" min="1" class="border px-2 py-1 w-full mb-4" required>
                <div class="flex justify-end gap-2">
                    <button type="button" onclick="closeModal()" class="px-4 py-1 border border-gray-500 rounded">Cancel</button>
                    <button type="submit" name="accept" class="bg-green-600 text-white px-4 py-1 rounded hover:bg-green-800">Accept</button>
                </div>
            </form>
        </div>
    </div>
    <!-- End Modal Section -->

    <!-- Start JavaScript Section -->
    <script>
        function openModal(loanId) {
            document.getElementById('modalLoanId').value = loanId;
            document.getElementById('acceptModal').classList.remove('hidden');
        }

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