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

// Check if the user is an admin. If not, redirect to the login page.
if (!isset($_SESSION["adminid"])) {
    header("Location: login.php");
    exit();
}

// Check for customer ID in session. This seems misplaced in an admin panel file,
// but the original code has it. We'll keep it for functionality but recommend
// a review of the session logic.
if (!isset($_SESSION['customerid'])) {
    header('Location: login.php?error=nologin');
    exit();
}

// Update last login timestamp for the customer.
// The original code used the insecure `mysql_query` and a raw session variable.
// This is updated to use the mysqli prepared statements for security.
$dts = date("Y-m-d H:i:s");
$stmt = $conn->prepare("UPDATE customers SET lastlogin = ? WHERE customerid = ?");
$stmt->bind_param("ss", $dts, $_SESSION['customerid']);
$stmt->execute();
$stmt->close();

// Fetch loan details for the customer.
// Again, the original code used a loan ID where a customer ID was expected, which is a logic error.
// The corrected code fetches the loan details based on the customer ID.
$results = mysqli_query($conn, "SELECT * FROM loan WHERE customerid = '$_SESSION[customerid]'");

// The original code was looping over the result to set variables, but this is a
// one-to-one relationship. It's more efficient to just fetch one row.
if ($arrow = mysqli_fetch_array($results)) {
    $acno = htmlspecialchars($arrow['accno']);
    $status = htmlspecialchars($arrow['accstatus']);
    $accopen = htmlspecialchars($arrow['accopendate']);
    $acctype = htmlspecialchars($arrow['accounttype']);
    $accbal = htmlspecialchars($arrow['accountbalance']);
    $email = htmlspecialchars($arrow['email']);
    $phone = htmlspecialchars($arrow['phone']);
}

// Fetch customer details.
$result = mysqli_query($conn, "SELECT * FROM customers WHERE customerid='$_SESSION[customerid]'");
$rowrec = mysqli_fetch_array($result);

?>
<div class="dt-content-wrapper">

    <div class="dt-content">

        <div class="dt-page__header">
            <h1 class="dt-page__title">
                <?php echo "Disburse Loan"; ?>
            </h1>
        </div>

        <?php
        if (isset($_POST['pay'])) {
            // Sanitize the input to prevent SQL injection.
            $loan_id = mysqli_real_escape_string($conn, $_POST['payto']);
            $customer_id = mysqli_real_escape_string($conn, $_POST['custid']);

            // Fetch loan details.
            $result3 = mysqli_query($conn, "SELECT * FROM loan WHERE loanid = '$loan_id'");
            $arrpayment3 = mysqli_fetch_array($result3);

            // Fetch transaction amounts for this loan.
            $x = mysqli_query($conn, "SELECT amount FROM transactions WHERE loanid = '$loan_id'");
            $aamt = 0;
            if ($x) {
                while ($arrpayment2 = mysqli_fetch_array($x)) {
                    $aamt += $arrpayment2['amount'];
                }
            }

            // Calculate remaining balance and interest.
            $balance = $arrpayment3['loanamt'] + ($arrpayment3['interest'] * $arrpayment3['loanamt'] / 100) - $aamt;
            $int = $balance - $arrpayment3['loanamt'];

            // Fetch customer details.
            $result3 = mysqli_query($conn, "SELECT * FROM customers WHERE customerid = '$customer_id'");
            $arrpayment4 = mysqli_fetch_array($result3);
        }
        ?>

        <div class="profile">
            <div class="profile-content">
                <div class="row">
                    <div class="col-xl-4 order-xl-2">
                        <div class="row">
                            <div class="col-xl-12 col-md-6 col-12 order-xl-2">
                                </div>
                            </div>
                        </div>
                    <div class="col-xl-12 order-xl-1">
                        <div class="card">
                            <div class="card-header card-nav bg-transparent d-sm-flex justify-content-sm-between">
                                <h3 class="mb-2 mb-sm-n5">Loan Status</h3>
                                <ul class="card-header-links nav nav-underline" role="tablist">
                                    <li class="nav-item">
                                        <a class="nav-link active" data-toggle="tab" href="#tab-pane1" role="tab" aria-controls="tab-pane1" aria-selected="true">Loan Overview</a>
                                    </li>
                                </ul>
                            </div>
                            <div class="card-body pb-2">
                                <div class="tab-content mt-5">
                                    <div id="tab-pane1" class="tab-pane active">
                                        <ul class="dt-list dt-list-col-4">
                                            <li class="dt-list__item">
                                                <div class="media">
                                                    <i class="icon icon-user icon-4x mr-5 align-self-center text-yellow"></i>
                                                    <div class="media-body">
                                                        <span class="d-block text-light-gray f-12 mb-1">Loan Number</span>
                                                        <p class="h5 mb-0">
                                                            <?php echo htmlspecialchars($arrpayment3['loannumber']); ?>
                                                        </p>
                                                    </div>
                                                    </div>
                                                </li>
                                            <li class="dt-list__item">
                                                <div class="media">
                                                    <i class="icon icon-calendar icon-4x mr-5 align-self-center text-yellow"></i>
                                                    <div class="media-body">
                                                        <span class="d-block text-light-gray f-12 mb-1">Application Date</span>
                                                        <p class="h5 mb-0">
                                                            <?php echo htmlspecialchars($arrpayment3['startdate']); ?>
                                                        </p>
                                                    </div>
                                                    </div>
                                                </li>
                                            <li class="dt-list__item">
                                                <div class="media">
                                                    <i class="icon icon-dollar-circle icon-4x mr-5 align-self-center text-yellow"></i>
                                                    <div class="media-body">
                                                        <span class="d-block text-light-gray f-12 mb-1">Loan Amount</span>
                                                        <p class="h5 mb-0">
                                                            <?php echo htmlspecialchars($arrpayment3['loanamt']); ?>
                                                        </p>
                                                    </div>
                                                    </div>
                                                </li>
                                            <li class="dt-list__item">
                                                <div class="media">
                                                    <i class="icon icon-chart-bar icon-4x mr-5 align-self-center text-yellow"></i>
                                                    <div class="media-body">
                                                        <span class="d-block text-light-gray f-12 mb-1">Interest Rate</span>
                                                        <p class="h5 mb-0">
                                                            <?php echo htmlspecialchars($arrpayment3['interest']); ?>%
                                                        </p>
                                                    </div>
                                                    </div>
                                                </li>
                                            <li class="dt-list__item">
                                                <div class="media">
                                                    <i class="icon icon-chart-pie icon-4x mr-5 align-self-center text-yellow"></i>
                                                    <div class="media-body">
                                                        <span class="d-block text-light-gray f-12 mb-1">Interest</span>
                                                        <p class="h5 mb-0">
                                                            <?php echo htmlspecialchars($int); ?>
                                                        </p>
                                                    </div>
                                                    </div>
                                                </li>
                                            <li class="dt-list__item">
                                                <div class="media">
                                                    <i class="icon icon-calculator icon-4x mr-5 align-self-center text-yellow"></i>
                                                    <div class="media-body">
                                                        <span class="d-block text-light-gray f-12 mb-1">Total</span>
                                                        <p class="h5 mb-0">
                                                            <?php echo htmlspecialchars($balance); ?>
                                                        </p>
                                                    </div>
                                                    </div>
                                                </li>
                                            <li class="dt-list__item">
                                                <div class="media">
                                                    <i class="icon icon-diamond icon-4x mr-5 align-self-center text-yellow"></i>
                                                    <div class="media-body">
                                                        <span class="d-block text-light-gray f-12 mb-1">Loan Status</span>
                                                        <p class="h5 mb-0">
                                                            <?php
                                                            if ($arrpayment3['status'] == '0') {
                                                                echo '<span class="badge badge-pill badge-danger mb-1 mr-1">Loan Is Unapproved</span>';
                                                            } elseif ($arrpayment3['status'] == '1') {
                                                                echo '<span class="badge badge-pill badge-info mb-1 mr-1">Loan Approved And Awaiting Fund Disbursement</span>';
                                                            } elseif ($arrpayment3['status'] == '2') {
                                                                echo '<span class="badge badge-pill badge-success mb-1 mr-1">Fund Disbursed And Is Loan Is Active</span>';
                                                            }
                                                            ?>
                                                        </p>
                                                    </div>
                                                    </div>
                                                </li>
                                            </ul>

                                        <br><br>

                                    </div>
                                    <form method='post' action='disburse.php'>
                                        <input type="hidden" value='<?php echo htmlspecialchars($arrpayment3['loanid']); ?>' name='payto'>
                                        <input type="hidden" value='<?php echo htmlspecialchars($arrpayment3['interest']); ?>' name='inti'>
                                        <?php if ($arrpayment3['status'] == '1') { ?>
                                            <label>User Applied For $<?php echo htmlspecialchars($arrpayment3['loanamt']); ?>. Please Enter Amount To Disburse To User</label>
                                            <input placeholder='Enter Amount To Disburse' class='form-control' name='amt'><br>
                                            <input type='submit' class='btn btn-secondary' name='disburse' value='Disburse Fund' />
                                        <?php } ?>
                                    </form>

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