<?php
date_default_timezone_set('Africa/Dar_es_Salaam'); 
header('Content-Type: application/json');
include '../../config.php'; 

$branch_id = isset($_GET['branch_id']) ? intval($_GET['branch_id']) : 0;
if ($branch_id <= 0) {
    echo json_encode(['error' => 'Invalid branch id']);
    exit;
}

$sql = "SELECT 
            ls.id,
            ls.loan_id,
            ls.customer_id,
            ls.branch_id,
            ls.scheduled_amount,
            ls.paid_amount,
            ls.schedule_date,
            ls.status,
            c.firstname,
            c.middlename,
            c.lastname,
            c.phone
        FROM loans_schedule ls
        INNER JOIN customers c ON ls.customer_id = c.id
        WHERE ls.branch_id = ? 
          AND ls.status = 'Not Paid'
        ORDER BY ls.schedule_date DESC";

if ($stmt = $conn->prepare($sql)) {
    $stmt->bind_param("i", $branch_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $schedules = [];
    $totalExpected = 0;
    $totalCollected = 0;
    
    while ($row = $result->fetch_assoc()) {
        $schedules[] = $row;
        $totalExpected += $row['scheduled_amount'];
        $totalCollected += $row['paid_amount'];
    }
    $stmt->close();
    
    $remaining = $totalExpected - $totalCollected;
    
    echo json_encode([
        'status' => 'success',
        'data' => $schedules,
        'totals' => [
            'expected' => $totalExpected,
            'collected' => $totalCollected,
            'remaining' => $remaining
        ]
    ]);
} else {
    echo json_encode(['error' => 'Query failed']);
}
?>
