<?php
require_once 'functions.php';
checkLogin();
$db_link = connect();

if (!isset($_GET['lid'])) { die("Error: Loan ID missing."); }
$loan_id = sanitize($db_link, $_GET['lid']);

// 1. FETCH LOAN & CUSTOMER DETAILS
$sql = "SELECT l.*, c.cust_name, c.cust_no, c.cust_address, c.cust_phone, c.cust_occup 
        FROM loans l 
        JOIN customer c ON l.cust_id = c.cust_id 
        WHERE l.loan_id = '$loan_id'";
$query = mysqli_query($db_link, $sql);
$loan = mysqli_fetch_assoc($query);

// 2. FETCH SECURITIES
$sql_sec = "SELECT * FROM securities WHERE loan_id = '$loan_id'";
$query_sec = mysqli_query($db_link, $sql_sec);
$securities = [];
while ($row = mysqli_fetch_assoc($query_sec)) { $securities[] = $row['sec_name']; }

// 3. NUMBER TO WORDS FUNCTION
function numberToWords($number) {
    if (!is_numeric($number)) return "................................................";
    if (class_exists('NumberFormatter')) {
        $f = new NumberFormatter("en", NumberFormatter::SPELLOUT);
        return strtoupper($f->format($number));
    }
    return "................................................";
}

// 4. HELPER FOR DOTTED LINES
function showVal($val, $width="150px") {
    if(!empty($val)) return "<b>".strtoupper($val)."</b>";
    return "<span style='border-bottom:1px dotted #000; display:inline-block; width:$width;'>&nbsp;</span>";
}
function dottedLine($width="100%") {
    return "<span style='border-bottom:1px dotted #000; display:inline-block; width:$width;'>&nbsp;</span>";
}

// 5. LOGO DETECTION
$logo_base64 = "";
$logo_file = "uploads/photos/image_9c4217.png"; // Your specific logo file
if (file_exists($logo_file)) {
    $data = file_get_contents($logo_file);
    $logo_base64 = 'data:image/png;base64,' . base64_encode($data);
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Loan Agreement - <?php echo $loan['loan_no']; ?></title>
    <style>
        body { font-family: 'Times New Roman', serif; font-size: 11pt; line-height: 1.2; color: #000; max-width: 800px; margin: 0 auto; padding: 20px; }
        .header { text-align: center; font-weight: bold; margin-bottom: 5px; font-size: 10pt; }
        .header img { height: 70px; margin-bottom: 5px; }
        h3 { text-align: center; text-decoration: underline; margin: 10px 0; font-size: 14pt; text-transform: uppercase; }
        p { margin: 3px 0; text-align: justify; }
        .section-title { font-weight: bold; text-decoration: underline; margin-top: 10px; margin-bottom: 2px; font-size: 11pt; }
        .indented { margin-left: 20px; }
        table { width: 100%; border-collapse: collapse; margin-top: 5px; }
        td { padding: 4px; vertical-align: top; }
        
        @media print {
            body { padding: 0; font-size: 10pt; }
            button { display: none; }
            .page-break { page-break-before: always; }
        }
    </style>
</head>
<body>
    <div style="text-align:right;">
        <button onclick="window.print()" style="padding: 10px 20px; background: #E95D0F; color: white; border: none; cursor: pointer;">PRINT AGREEMENT</button>
    </div>

    <div class="header">
        <?php if($logo_base64): ?><img src="<?php echo $logo_base64; ?>"><br><?php endif; ?>
        THE REPUBLIC OF UGANDA<br>
        IN THE MATTER OF THE CONTRACTS ACT N07 OF 2010<br>
        AND<br>
        IN THE MATTER OF THE TIER 4 MICROFINANCE INSTITUTIONS AND MONEY LENDER’S ACT, 2016<br>
        AND<br>
        IN THE MATTER OF A LOAN AGREEMENT
    </div>

    <h3>LOAN AGREEMENT</h3>

    <p>THIS LOAN AGREEMENT is made this <?php echo showVal(date('d', $loan['loan_dateout']), '30px'); ?> Day of <?php echo showVal(date('F', $loan['loan_dateout']), '80px'); ?> 20<?php echo showVal(date('y', $loan['loan_dateout']), '30px'); ?>.</p>

    <p><strong>Between</strong></p>
    <p><strong>KAROMU QUICK SERVICES LIMITED</strong> of <strong>KIBOGA BRANCH</strong> Uganda on one hand herein referred to as the <strong>“LENDER”</strong> AND</p>

    <p>
        <?php echo showVal($loan['cust_name'], '250px'); ?> of Address <?php echo showVal($loan['cust_address'], '300px'); ?>, Occupation <?php echo showVal($loan['cust_occup'], '150px'); ?><br>
        TEL <?php echo showVal($loan['cust_phone'], '150px'); ?> File number No. <?php echo showVal($loan['loan_no'], '100px'); ?> (Hereinafter referred to as the <strong>“BORROWER”</strong> of the other part).
    </p>

    <p>WHEREAS the lender is willing and prepared to lend/advance to the borrower the principal sum on the terms and conditions set out hereunder.</p>
    <p>AND WHEREAS the borrower undertakes, is willing and desirous to borrow and pay back the said principal sum and agreed accrued interest on the terms and Conditions herein below set out.</p>

    <p><strong>NOW THEREFORE THE PARTIES HERETO AGREE AS FOLLOWS:-</strong></p>

    <div class="section-title">1. AGREEMENT TO LEND</div>
    <p>The lender hereby lends/advances the principal sum of Ugx Shs <?php echo showVal(number_format($loan['loan_principal']), '120px'); ?> (In words <b><?php echo numberToWords($loan['loan_principal']); ?> SHILLINGS ONLY</b>) to the borrower which sum shall be used exclusively for the purpose(s) for which the loan was obtained as per the loan application form.</p>

    <div class="section-title">2. MODE OF REPAYMENT OF THE LOAN.</div>
    <p>The borrower shall repay the loan to the lender by monthly installments and with each installment shall pay the interest then due. The money to be paid per month is Ug. Shs <?php echo showVal(number_format($loan['loan_rate']), '120px'); ?> (In words <?php echo dottedLine('250px'); ?>) for <?php echo showVal($loan['loan_period'], '30px'); ?> (months).</p>

    <div class="section-title">3. REPAYMENT DATE</div>
    <p>The borrower shall repay the principal sum together with accrued interest on or before <?php echo dottedLine('50px'); ?> day of <?php echo dottedLine('100px'); ?> 20....... without fail.</p>

    <p><strong>4.</strong> In the event the borrower(s) wish to pay back the principle sum in a lesser period than the period agreed upon under paragraph 2 and 3, the borrower shall pay back the said sum at 15% interest rate.</p>

    <div class="section-title">5. PENALTY FOR LATE PAYMENT.</div>
    <p>In the event that the borrower fails to make any payment under this agreement by the payment due date, the borrower shall be subjected to a penalty rate of the monthly amount in Arrears per day of default commencing on the day following the due date and continuing until the full payment is made.</p>

    <div class="section-title">6. RESTRUCTURE.</div>
    <p>In case the borrower fails to pay back the money according to the above given schedule, the borrower shall be given an extension of three months to pay back the money but the same shall be considered as a new loan.</p>

    <div class="section-title">6. SECURITIES/CAVEATS</div>
    <p>(i) The borrower has pledged the following property of which he /she has retained title and ownership as securities for the loan.</p>
    <?php if(!empty($securities)): ?>
        <?php foreach($securities as $k => $sec): ?>
            <p class="indented">a) <?php echo $sec; ?></p>
        <?php endforeach; ?>
    <?php else: ?>
        <p class="indented">a) NO SECURITY LISTED</p>
    <?php endif; ?>
    <p>(ii) The lender shall be at liberty to lodge a caveat or caveats against or over any land/property chattel or asset provided by the Borrower as security for repayment of the loan.</p>

    <div class="section-title">7. REGISTRATION FEES, STAMP DUTY ETC</div>
    <p>(i) The borrower hereby undertakes to pay 2% of the loan amount as the Loan processing fee.</p>
    <p>(ii) The borrower hereby undertakes to pay legal fees and all registration fees, stamp duty and other charges that shall be required in preparing and registering the securities set out hereinabove.</p>

    <div class="page-break"></div>

    <div class="section-title">8. RECOVERY/COLLECTION CHARGES</div>
    <p>The borrower hereby agrees to pay all fees charges and costs incidental to the recovery/collection of the outstanding loan and the lender shall be at liberty to debit the Borrower’s account(s) accordingly.</p>

    <div class="section-title">9. GUARANTORS</div>
    <p>The borrower has presented the following persons as guarantors and have duly committed themselves to be fully liable and repay the loan and accrued interest thereon in case the principal borrower fails to pay on the due date.</p>
    
    <table border="0">
        <tr>
            <td width="50%">
                <strong>(1) Name</strong> <?php echo showVal($loan['loan_guarant1'], '180px'); ?><br><br>
                Occupation <?php echo dottedLine('180px'); ?><br><br>
                Address <?php echo dottedLine('120px'); ?> Tel <?php echo showVal($loan['loan_guarant2'], '100px'); ?><br><br>
                Signature <?php echo dottedLine('200px'); ?>
            </td>
            <td width="50%">
                <strong>(2) Name</strong> <?php echo showVal($loan['loan_guarant3'], '180px'); ?><br><br>
                Occupation <?php echo dottedLine('180px'); ?><br><br>
                Address <?php echo dottedLine('120px'); ?> Tel <?php echo showVal($loan['loan_xtra1'], '100px'); ?><br><br>
                Signature <?php echo dottedLine('200px'); ?>
            </td>
        </tr>
    </table>

    <div class="section-title">10. RIGHT TO SELL OFF</div>
    <p>In the event of the Borrower’s failure to pay all principal or any part here of at the agreed time, the lender shall be free to institute Legal proceedings against the borrower and his or her guarantors to recover the debt due or SELL by private treaty with or without recourse to court the security hereby pledged PROVIDED that such security shall be sold to the highest bidder and thereafter the Lender has realized the loan plus the accumulated interest and the cost of the sale of property the lender shall hand over the balance if any to the Borrower.</p>

    <p><strong>11.</strong> The borrower shall not sell the loan security items before notifying the Lender.</p>
    <p><strong>12.</strong> The lender is at liberty to recall the loan or demand all the principal and accrued interest to be paid before the expiration of the agreed loan period in case the borrower defaults on payment of at least three installments.</p>

    <div class="section-title">13. NOTICE.</div>
    <p>Any Notice, consent or communication required or permitted to be given or made by this agreement shall be in writing and shall be deemed or to have been dully given or made to the borrower or sent by registered post/mail to the Borrower’s last known address, Notice shall be deemed to have been given to the lender or its relevant branch or sent by registered mail to the lender’s postal addressor that it its relevant branch.</p>

    <div class="section-title">14. Borrower’s Spouses.</div>
    <p>I <?php echo dottedLine('150px'); ?> of <?php echo dottedLine('150px'); ?> Tel <?php echo dottedLine('100px'); ?> Signature <?php echo dottedLine('100px'); ?> the spouse of <?php echo showVal($loan['cust_name'], '150px'); ?> (the borrower) do hereby agree and consent that my spouse be advanced money amounting to <?php echo showVal(number_format($loan['loan_principal']), '100px'); ?> ugx and I further consent to the security advanced to Karomu Quick services Limited as security for the loan,</p>
    
    <p><strong>In witness of an advocate</strong></p>
    <p>Name <?php echo dottedLine('250px'); ?> Designation <?php echo dottedLine('150px'); ?></p>
    <p>Signature and stamp <?php echo dottedLine('200px'); ?></p>

    <div class="section-title">15. Chairman’s LC1 confirmation</div>
    <p>I <?php echo dottedLine('200px'); ?> Chairperson LC1 of <?php echo dottedLine('200px'); ?> do hereby confirm that I have never seen the borrower or any person claiming interest in the above property given as security being given to any other individual or any institution as security for a loan.</p>
    <br>
    <p>Signature <?php echo dottedLine('200px'); ?> Official Stamp <?php echo dottedLine('150px'); ?></p>

    <div class="section-title" style="text-align:center;">CERTIFICATE OF TRANSLATION</div>
    <p>I/We the undersigned hereby certify that the contents of this agreement have prior; to execution been read over and explained to the Borrower in the <?php echo dottedLine('150px'); ?> language and he/she appeared fully to understand the same.</p>
    
    <table border="0">
        <tr>
            <td>NAME 1 <?php echo dottedLine('200px'); ?></td>
            <td>POSITION <?php echo dottedLine('150px'); ?></td>
        </tr>
        <tr>
            <td colspan="2">SIGNATURE <?php echo dottedLine('200px'); ?> <?php echo dottedLine('100px'); ?></td>
        </tr>
    </table>

    <br>
    <p>IN WITNESS WHERE OF the parties here to have caused this agreement to be executed the day and year above mentioned.</p>

    <p><strong>WITNESSES</strong></p>
    <p>1. Name <?php echo dottedLine('200px'); ?> signature <?php echo dottedLine('100px'); ?> Tel No <?php echo dottedLine('100px'); ?></p>
    <p>2. Name <?php echo dottedLine('200px'); ?> Signature <?php echo dottedLine('100px'); ?> Tel.No <?php echo dottedLine('100px'); ?></p>

    <p><strong>Signed by:</strong></p>
    
    <table border="0" style="width:100%;">
        <tr>
            <td colspan="2">
                <strong>Loans Officer</strong><br>
                Name <?php echo dottedLine('180px'); ?><br>
                Signature <?php echo dottedLine('150px'); ?> Tel No <?php echo dottedLine('150px'); ?>
            </td>
        </tr>
        <tr>
            <td width="50%">
                <br><strong>BRANCH MANAGER</strong><br>
                Name <?php echo dottedLine('180px'); ?><br>
                Signature <?php echo dottedLine('150px'); ?><br>
                Tel No <?php echo dottedLine('150px'); ?>
            </td>
            <td width="50%">
                <br><strong>CASHIER</strong><br>
                Name <?php echo dottedLine('180px'); ?><br>
                Signature <?php echo dottedLine('150px'); ?><br>
                Tel No <?php echo dottedLine('150px'); ?>
            </td>
        </tr>
    </table>

    <br>
    <p style="text-align:center;">for and on behalf of KAROMU QUICK SERVICES LIMITED</p>
    <br>
    <p>Signed by the said <?php echo dottedLine('300px'); ?></p>
    <p style="text-align:right;">“Borrower”</p>

</body>
</html>