<?php
// getLoanDetails.php
header('Content-Type: application/json');
include '../../config.php';
$base_url = "https://api.bexamicrofinance.com/";

if (isset($_GET['loan_id'])) {
    $loan_id = mysqli_real_escape_string($conn, $_GET['loan_id']);
    
    // Query ya kujoin loans, customers, na branches ili kupata interest
    $query = "SELECT 
                l.loan_id, l.customer_id, l.branch_id, l.loan_amount, 
                l.collateral1, l.collateral2, l.collateral3, 
                l.guarantor_firstname, l.guarantor_lastname, l.guarantor_phone, 
                l.guarantor_collateral1, l.guarantor_collateral2, l.guarantor_collateral3, 
                l.loan_period, l.loan_purpose, l.payment_method, l.user_id, 
                l.guarantor_image, l.loan_date, l.status, l.insurance_balance,
                c.firstname, c.middlename, c.lastname, c.phone, c.nation_id, 
                c.country, c.region, c.street, c.ward, c.image AS customer_image,
                l.interest
              FROM loans l 
              LEFT JOIN customers c ON l.customer_id = c.id 
              LEFT JOIN branches b ON l.branch_id = b.branch_id
              WHERE l.loan_id = '$loan_id'";

    $result = mysqli_query($conn, $query);
    if ($result && mysqli_num_rows($result) > 0) {
        $data = mysqli_fetch_assoc($result);
        
        // Ongeza base URL kwa images
        if (!empty($data['customer_image'])) {
            $data['customer_image'] = $base_url . $data['customer_image'];
        }
        if (!empty($data['guarantor_image'])) {
            $data['guarantor_image'] = $base_url . $data['guarantor_image'];
        }

        // Retrieve repayment schedule
        $scheduleQuery = "SELECT id, loan_id, customer_id, branch_id, scheduled_amount, paid_amount, schedule_date, status "
                       . "FROM loans_schedule WHERE loan_id = '$loan_id' ORDER BY schedule_date";
        $scheduleResult = mysqli_query($conn, $scheduleQuery);
        $schedules = [];
        if ($scheduleResult) {
            while ($row = mysqli_fetch_assoc($scheduleResult)) {
                $schedules[] = $row;
            }
        }

        // Compute start/end dates and total days
        $dates = array_column($schedules, 'schedule_date');
        $start_date     = !empty($dates) ? min($dates) : null;
        $end_date       = !empty($dates) ? max($dates) : null;
        $repayment_days = count($schedules);

        // Attach to payload
        $data['schedule']             = $schedules;
        $data['schedule_start_date']  = $start_date;
        $data['schedule_end_date']    = $end_date;
        $data['repayment_days']       = $repayment_days;

        echo json_encode([
            'status' => 'success',
            'data'   => $data
        ]);
    } else {
        echo json_encode([
            'status' => 'error',
            'message' => mysqli_error($conn) ?: 'Loan not found'
        ]);
    }
} else {
    echo json_encode([
        'status' => 'error',
        'message' => 'loan_id parameter missing'
    ]);
}
?>
