<?php
header("Content-Type: application/json");
include_once("../../config.php"); // Hakikisha file hii inaseti $conn kwa DB yako

if (isset($_GET['customer_id'])) {
    $customer_id = intval($_GET['customer_id']);
    // Angalia kama loan_id imetolewa
    $loan_id = isset($_GET['loan_id']) ? intval($_GET['loan_id']) : null;
    
    // Tengeneza query ya SQL
    $sql = "SELECT id, loan_id, customer_id, branch_id, scheduled_amount, paid_amount, schedule_date, status 
            FROM loans_schedule 
            WHERE customer_id = $customer_id";
    if ($loan_id !== null) {
        $sql .= " AND loan_id = $loan_id";
    }
    $sql .= " ORDER BY schedule_date ASC";
    
    $result = mysqli_query($conn, $sql);
    $schedules = array();
    $totalPaid = 0;
    $totalScheduled = 0;
    
    if ($result) {
        while ($row = mysqli_fetch_assoc($result)) {
            $schedules[] = $row;
            $totalPaid += $row['paid_amount'];
            $totalScheduled += $row['scheduled_amount'];
        }
        echo json_encode([
            "schedules" => $schedules,
            "totalPaid" => $totalPaid,
            "totalScheduled" => $totalScheduled
        ]);
    } else {
        echo json_encode(["error" => "Query failed"]);
    }
} else {
    echo json_encode(["error" => "customer_id parameter missing"]);
}
?>
