<?php
session_start();
error_reporting(E_ALL);

include("header.php");
include("../config/theconfig.php");

if (!isset($_SESSION["adminid"]) && !isset($_SESSION['customerid'])) {
    header("Location: login.php?error=nologin");
    exit();
}

$dts = date("Y-m-d h:i:s");
$customerid = $_SESSION['customerid'];

// Update last login time
$stmt_login = mysqli_prepare($conn, "UPDATE customers SET lastlogin=? WHERE customerid=?");
mysqli_stmt_bind_param($stmt_login, "si", $dts, $customerid);
mysqli_stmt_execute($stmt_login);
mysqli_stmt_close($stmt_login);

// Fetch loan details
$stmt_loan = mysqli_prepare($conn, "SELECT * FROM loan WHERE customerid=?");
mysqli_stmt_bind_param($stmt_loan, "i", $customerid);
mysqli_stmt_execute($stmt_loan);
$result_loan = mysqli_stmt_get_result($stmt_loan);
$arrpayment3 = mysqli_fetch_assoc($result_loan);
mysqli_stmt_close($stmt_loan);

// Check if loan data was fetched
if ($arrpayment3) {
    // Fetch total payments for the loan
    $stmt_payments = mysqli_prepare($conn, "SELECT SUM(amount) AS total_payments FROM payments WHERE loanid=?");
    mysqli_stmt_bind_param($stmt_payments, "i", $arrpayment3['loanid']);
    mysqli_stmt_execute($stmt_payments);
    $result_payments = mysqli_stmt_get_result($stmt_payments);
    $payments_row = mysqli_fetch_assoc($result_payments);
    mysqli_stmt_close($stmt_payments);

    // Use isset() to avoid PHP 7+ parse error
    if (isset($payments_row['total_payments'])) {
        $total_payments = $payments_row['total_payments'];
    } else {
        $total_payments = 0;
    }

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

    // Fetch customer details
    $stmt_customer = mysqli_prepare($conn, "SELECT * FROM customers WHERE customerid=?");
    mysqli_stmt_bind_param($stmt_customer, "i", $customerid);
    mysqli_stmt_execute($stmt_customer);
    $result_customer = mysqli_stmt_get_result($stmt_customer);
    $arrpayment4 = mysqli_fetch_assoc($result_customer);
    mysqli_stmt_close($stmt_customer);
} else {
    // Handle case where no loan is found for the customer
    $arrpayment3 = [];
    $arrpayment4 = [];
    $balance = 0;
    $int = 0;
}

// Function to safely echo a value with a fallback
function safe_echo($array, $key, $fallback = '') {
    if (isset($array[$key])) {
        echo htmlspecialchars($array[$key]);
    } else {
        echo htmlspecialchars($fallback);
    }
}
?>

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

    <div class="dt-content">

        <div class="dt-page__header">
            <h1 class="dt-page__title">Loan Details</h1>
        </div>

        <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-1">
                                <div class="dt-card dt-card__full-height">
                                    <div class="dt-card__header pt-6">
                                        <div class="dt-card__heading">
                                            <h3 class="dt-card__title">Account Holder</h3>
                                        </div>
                                        </div>
                                    <div class="dt-card__body">
                                        <div class="media mb-5">
                                            <i class="icon icon-user icon-xl mr-5"></i>
                                            <div class="media-body">
                                                <span class="d-block text-light-gray f-12 mb-1">Customer's Name</span>
                                                <a href="javascript:void(0)"><?php safe_echo($arrpayment4, 'firstname'); ?> <?php safe_echo($arrpayment4, 'lastname'); ?></a>
                                            </div>
                                            </div>
                                        <div class="media mb-5">
                                            <i class="icon icon-phone-o icon-xl mr-5"></i>
                                            <div class="media-body">
                                                <span class="d-block text-light-gray f-12 mb-1">Phone</span>
                                                <a href="javascript:void(0)"><?php safe_echo($arrpayment4, 'phone'); ?></a>
                                            </div>
                                            </div>
                                        <div class="media">
                                            <i class="icon icon-mail icon-xl mr-5"></i>
                                            <div class="media-body">
                                                <span class="d-block text-light-gray f-12 mb-1">Email</span>
                                                <a href="javascript:void(0)"><span class="h5"><?php safe_echo($arrpayment4, 'email'); ?></span></a>
                                            </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <div class="col-xl-8 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</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 safe_echo($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 safe_echo($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 safe_echo($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 safe_echo($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 (isset($arrpayment3['status'])) {
                                                                $status = $arrpayment3['status'];
                                                                if ($status == '0') {
                                                                    echo '<span class="badge badge-pill badge-danger mb-1 mr-1">Loan Is Unapproved</span>';
                                                                } else if ($status == '1') {
                                                                    echo '<span class="badge badge-pill badge-info mb-1 mr-1">Awaiting Fund Disbursement</span>';
                                                                } else if ($status == '2') {
                                                                    echo '<span class="badge badge-pill badge-success mb-1 mr-1">Loan Is Active</span>';
                                                                }
                                                            }
                                                            ?>
                                                        </p>
                                                    </div>
                                                    </div>
                                                </li>
                                            <?php if (isset($arrpayment3['status']) && $arrpayment3['status'] == '2') : ?>
                                                <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'>Unpaid Balance</span>
                                                            <p class='h5 mb-0'>
                                                                <span class='badge badge-pill badge-success mb-1 mr-1'><?php echo htmlspecialchars($balance); ?></span>
                                                            </p>
                                                        </div>
                                                        </div>
                                                    </li>
                                                <?php endif; ?>
                                        </ul>
                                    </div>
                                    <form method='post' action='loanapplications.php'>
                                        <input hidden value='<?php safe_echo($arrpayment3, 'loanid'); ?>' name='payto'>
                                        <input hidden value='<?php echo htmlspecialchars($balance); ?>' name='bal'>
                                        <?php if (isset($arrpayment3['status']) && $arrpayment3['status'] == '0') : ?>
                                            <input type='submit' class='btn btn-primary' name='approve' value='Approve' />
                                        <?php endif; ?>
                                    </form>
                                </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
</div>
<?php
include 'footer.php';
mysqli_close($conn);
?>