<?php
session_start();
error_reporting(0);
include("../config/theconfig.php");
include("header.php");

// Check for admin session, if not set, redirect to login page.
if (!isset($_SESSION["adminid"])) {
    header("Location: login.php");
    exit();
}

// Assuming the included file 'theconfig.php' establishes a database connection
// using mysqli. If it's using the old mysql_* functions, we need to adapt.
// This example assumes it's updated to use mysqli.
if (!isset($conn)) {
    die("Connection variable \$conn not set. Please check theconfig.php.");
}

// Retrieve loans with status 1 or 2 (e.g., pending or active loans).
$loan = mysqli_query($conn, "SELECT * FROM loan WHERE status=1 OR status=2");
?>
<div class="dt-content-wrapper">

    <div class="dt-content">

        <div class="dt-page__header">
            <h1 class="dt-page__title">My Loan</h1>
        </div>
        <div class="row">
            <?php
            // The original code calculates balance from POST data, which is not sanitized
            // and is a major security risk. It also uses the deprecated mysql_* functions.
            // This is a more secure, modern, and robust implementation.
            if (isset($_POST["disburse"])) {
                // Sanitize POST data to prevent SQL Injection
                $loanid = mysqli_real_escape_string($conn, $_POST['payto']);
                $amount = mysqli_real_escape_string($conn, $_POST['amt']);
                $interest_rate = mysqli_real_escape_string($conn, $_POST['inti']);
                
                // Calculate balance. Ensure proper numeric conversion.
                $balance = $amount * ($interest_rate / 100) + $amount;
                
                // SQL statement to update loan status and balance.
                $sql = "UPDATE loan SET status = 2, loanamt = '$amount', balance = '$balance' WHERE loanid = '$loanid'";
                
                if (mysqli_query($conn, $sql)) {
                    // Check if a row was actually affected
                    if (mysqli_affected_rows($conn) == 1) {
                        echo "<script>swal('Successful!', 'Fund Has Been Disbursed And Loan Is Active And Running Now', 'success');</script>";
                    } else {
                        echo "<script>swal('Failed!', 'Failed to update loan. No changes were made.', 'error');</script>";
                    }
                } else {
                    echo "<script>swal('Error!', 'An error occurred: " . mysqli_error($conn) . "', 'error');</script>";
                }
            }
            ?>

            <div class="col-xl-12">

                <div class="dt-entry__header">

                    <div class="dt-entry__heading">
                        <h3 class="dt-entry__title">View Loan</h3>
                    </div>
                    </div>
                <div class="dt-card">

                    <div class="dt-card__body">

                        <div class="table-responsive">

                            <table id="data-table" class="table table-striped table-bordered table-hover">
                                <thead>
                                    <tr>
                                        <th>Loan Type</th>
                                        <th>Loan Account</th>
                                        <th>Loan Amount</th>
                                        <th>Loan Interest</th>
                                        <th>Application Date</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    // Loop through the results and display each loan.
                                    while ($arrvar = mysqli_fetch_array($loan)) {
                                        echo "<tr>";
                                        echo "<td>" . htmlspecialchars($arrvar['loantype']) . "</td>";
                                        echo "<td>" . htmlspecialchars($arrvar['loannumber']) . "</td>";
                                        echo "<td>" . htmlspecialchars($arrvar['loanamt']) . "</td>";
                                        echo "<td>" . htmlspecialchars($arrvar['interest']) . " %</td>";
                                        echo "<td>" . htmlspecialchars($arrvar['startdate']) . "</td>";
                                        echo "<td>";
                                        echo "<form method='post' action='disburseloan.php'>";
                                        echo "<input type='hidden' value='" . htmlspecialchars($arrvar['loanid']) . "' name='payto'>";
                                        echo "<input type='hidden' value='" . htmlspecialchars($arrvar['customerid']) . "' name='custid'>";
                                        echo "<input type='submit' class='btn btn-secondary' name='pay' value='Disburse' />";
                                        echo "</form>";
                                        echo "</td>";
                                        echo "</tr>";
                                    }
                                    ?>
                                </tbody>
                                <tfoot>
                                    <tr>
                                        <th>Loan Type</th>
                                        <th>Loan Account</th>
                                        <th>Loan Amount</th>
                                        <th>Loan Interest</th>
                                        <th>Application Date</th>
                                        <th>Action</th>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

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

<script src="../assets/node_modules/datatables.net/js/jquery.dataTables.js"></script>
<script src="../assets/node_modules/datatables.net-bs4/js/dataTables.bootstrap4.js"></script>
<script src="../assets/js/custom/data-table.js"></script>