<?php
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");

date_default_timezone_set('Africa/Dar_es_Salaam');
include '../config.php';

$branch_id = isset($_GET['branch_id']) ? intval($_GET['branch_id']) : 0;

if ($branch_id == 0) {
    echo json_encode(["success" => false, "message" => "Branch ID is required"]);
    exit;
}

// Pata mikopo ya customers kwa branch husika ambapo status ni NULL
$sql_customers = "SELECT c.id AS customer_id, c.firstname, c.lastname, l.loan_id, l.loan_amount, l.loan_period, l.repayment_type, l.interest
                  FROM customers c 
                  INNER JOIN loans l ON c.id = l.customer_id
                  WHERE l.status IS NULL AND l.branch_id = ?";
$stmt = $conn->prepare($sql_customers);
$stmt->bind_param("i", $branch_id);
$stmt->execute();
$result = $stmt->get_result();

$loan_schedules = [];
while ($row = $result->fetch_assoc()) {
    $loan_id = $row['loan_id'];
    $loan_amount = floatval($row['loan_amount']);
    $loan_period = intval($row['loan_period']); // Miezi ya mkopo
    $repayment_type_raw = isset($row['repayment_type']) && $row['repayment_type'] !== '' ? $row['repayment_type'] : 'siku';
    // Normalize to lowercase for consistency
    $repayment_type = strtolower(trim($repayment_type_raw));

    // Idadi ya siku kwa kipindi cha mkopo (legacy behaviour: loan_period treated as months)
    $total_days = $loan_period * 30;
    if ($total_days <= 0) $total_days = 30;

    // Tumia interest kutoka loans table (l.interest)
    $loan_interest = isset($row['interest']) ? floatval($row['interest']) : 0.0;

    // Ikiwa interest imehifadhiwa kama percentage (mf. 5), toa kama 5 -> 0.05 kwa kutumia /100
    // Uncomment if your data stores interest as whole percentages:
    // if ($loan_interest > 1) { $loan_interest = $loan_interest / 100; }

    // Hesabu jumla ya mkopo (loan + interest)
    $total_amount = $loan_amount * (1 + $loan_interest * $loan_period);

    // Hesabu marejesho kwa siku, wiki, na mwezi
    $repayment_per_day = $total_amount / $total_days;
    $repayment_per_week = $repayment_per_day * 7;
    $repayment_per_month = $loan_period > 0 ? ($total_amount / $loan_period) : $total_amount;

    // Format numbers as strings with 2 decimals (same as before)
    $loan_schedules[] = [
        "loan_id" => $loan_id,
        "customer_name" => $row['firstname'] . " " . $row['lastname'],
        "loan_amount" => number_format($loan_amount, 2),
        "total_amount" => number_format($total_amount, 2),
        "loan_period" => $loan_period,
        "repayment_per_day" => number_format($repayment_per_day, 2),
        "repayment_per_week" => number_format($repayment_per_week, 2),
        "repayment_per_month" => number_format($repayment_per_month, 2),
        "repayment_type" => $repayment_type
    ];
}
$stmt->close();
$conn->close();

echo json_encode(["success" => true, "data" => $loan_schedules]);
?>
