<?php
header("Content-Type: application/json");
include_once("../config.php"); // Hakikisha config inajumuisha $conn

if (isset($_GET['branch_id'])) {
    $branch_id = intval($_GET['branch_id']);
    
    // Chukua collections kutoka loans_collection kulingana na branch_id
    $sqlCollections = "SELECT id, customer_id, loan_id, branch_id, amount_paid, payment_method, payment_date 
                        FROM loans_collection 
                        WHERE branch_id = $branch_id 
                        ORDER BY payment_date ASC";
    $resultCollections = mysqli_query($conn, $sqlCollections);
    $collections = array();
    
    if ($resultCollections) {
        while ($row = mysqli_fetch_assoc($resultCollections)) {
            $row['amount_paid'] = floatval($row['amount_paid']); // Badilisha kuwa float
            $collections[] = $row;
        }
    }
    
    if (empty($collections)) {
        echo json_encode(["error" => "No collections found for this branch"]);
        exit;
    }
    
    // Gawa collections kwa mkopo (loan_id) na mteja (customer_id)
    $grouped = array();
    foreach ($collections as $col) {
        $key = $col['loan_id'] . '-' . $col['customer_id'];
        if (!isset($grouped[$key])) {
            $grouped[$key] = array();
        }
        $grouped[$key][] = $col;
    }
    
    $receipts = array();
    
    // Tengeneza risiti tofauti kwa kila kikundi cha collections
    foreach ($grouped as $group) {
        // Tumia collection ya kwanza katika kikundi kupata customer_id na loan_id
        $firstCollection = $group[0];
        $customer_id = intval($firstCollection['customer_id']);
        $loan_id = intval($firstCollection['loan_id']);
        
        // Chukua taarifa za mteja
        $sqlCustomer = "SELECT id, branch_id, firstname, middlename, lastname, phone FROM customers WHERE id = $customer_id";
        $resultCustomer = mysqli_query($conn, $sqlCustomer);
        $customer = mysqli_fetch_assoc($resultCustomer);
        
        // Chukua taarifa za mkopo, sasa tukule interest kutoka loans table
        $sqlLoan = "SELECT loan_id, customer_id, branch_id, loan_amount, loan_period, loan_date, status, interest 
                    FROM loans 
                    WHERE loan_id = $loan_id AND customer_id = $customer_id";
        $resultLoan = mysqli_query($conn, $sqlLoan);
        $loan = mysqli_fetch_assoc($resultLoan);
        
        if (!$loan) {
            // Ikiwa mkopo haupatikani, skip kikundi hiki
            continue;
        }
        
        $loan_amount = floatval($loan['loan_amount']);
        $loan_period = intval($loan['loan_period']);
        // Tumia interest kutoka loan (hapa interest inatarajiwa kuwa decimal mfano 0.05 kwa 5%)
        $loan_interest = isset($loan['interest']) ? floatval($loan['interest']) : 0.0;

        // Ikiwa interest yako imestore kama percentage (mf. 5), toa kama 5 -> 0.05 kwa kutumia /100
        // Uncomment if needed:
        // if ($loan_interest > 1) { $loan_interest = $loan_interest / 100; }

        $totalDue = $loan_amount * (1 + ($loan_interest * $loan_period));
        
        // Hesabu malipo na update currentRemainingDue kwa kila collection ndani ya kikundi
        $cumulative = 0;
        foreach ($group as &$collection) {
            $cumulative += $collection['amount_paid'];
            $collection['currentRemainingDue'] = $totalDue - $cumulative;
        }
        unset($collection);
        
        $totalCollected = $cumulative;
        $remainingDue = $totalDue - $totalCollected;
        
        // Tengeneza risiti moja kwa kikundi hiki
        $receipt = array(
            "customer" => $customer,
            "loanAmount" => $loan_amount,
            "loanInterest" => $loan_interest,
            "totalDue" => $totalDue,
            "totalCollected" => $totalCollected,
            "remainingDue" => $remainingDue,
            "collections" => $group,
            "loan" => $loan
        );
        
        $receipts[] = $receipt;
    }
    
    echo json_encode(["receipts" => $receipts]);
} else {
    echo json_encode(["error" => "Missing parameter branch_id"]);
}
?>
