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

// Pata branch_id kutoka kwa GET; unaweza pia kutumia POST
if (isset($_GET['branch_id'])) {
    $branch_id = intval($_GET['branch_id']);
} else {
    echo json_encode(["error" => "branch_id not provided"]);
    exit;
}

$today = date("Y-m-d");

// 0. Pata interest ya branch
$branch_interest = 0;
$sql_branch = "SELECT interest FROM branches WHERE branch_id = ?";
if ($stmt = $conn->prepare($sql_branch)) {
    $stmt->bind_param("i", $branch_id);
    $stmt->execute();
    $stmt->bind_result($branch_interest);
    $stmt->fetch();
    $stmt->close();
}
$branch_interest = $branch_interest * 100;


// 1. Wateja wote (filtered by branch)
$total_customers = 0;
$sql = "SELECT COUNT(DISTINCT c.id) AS total
        FROM customers c
        JOIN loans l ON l.customer_id = c.id
        WHERE c.branch_id = ? AND l.status IS NULL";
if ($stmt = $conn->prepare($sql)) {
    $stmt->bind_param("i", $branch_id);
    $stmt->execute();
    $stmt->bind_result($total_customers);
    $stmt->fetch();
    $stmt->close();
}

// 2. Wateja wa leo (filtered by branch)
$today_customers = 0;
$sql = "SELECT COUNT(*) AS total FROM customers WHERE DATE(created_at) = ? AND branch_id = ?";
if ($stmt = $conn->prepare($sql)) {
    $stmt->bind_param("si", $today, $branch_id);
    $stmt->execute();
    $stmt->bind_result($today_customers);
    $stmt->fetch();
    $stmt->close();
}

// 3. Mikopo ya leo (filtered by branch)
$total_loans_today = 0;
$sql = "SELECT SUM(loan_amount) AS total FROM loans WHERE DATE(loan_date) = ? AND branch_id = ?";
if ($stmt = $conn->prepare($sql)) {
    $stmt->bind_param("si", $today, $branch_id);
    $stmt->execute();
    $stmt->bind_result($total_loans_today);
    $stmt->fetch();
    $stmt->close();
}

// 4. Waliokopa leo (filtered by branch)
$total_borrowers_today = 0;
$sql = "SELECT COUNT(DISTINCT customer_id) AS total FROM loans WHERE DATE(loan_date) = ? AND branch_id = ?";
if ($stmt = $conn->prepare($sql)) {
    $stmt->bind_param("si", $today, $branch_id);
    $stmt->execute();
    $stmt->bind_result($total_borrowers_today);
    $stmt->fetch();
    $stmt->close();
}

// 5. Marejesho ya leo (filtered by branch)
$total_collection_today = 0;
$sql = "SELECT SUM(amount_paid) AS total FROM loans_collection WHERE DATE(payment_date) = ? AND branch_id = ?";
if ($stmt = $conn->prepare($sql)) {
    $stmt->bind_param("si", $today, $branch_id);
    $stmt->execute();
    $stmt->bind_result($total_collection_today);
    $stmt->fetch();
    $stmt->close();
}

// 6. Mikopo yote (filtered by branch)
$total_loans = 0;
$sql = "SELECT SUM(loan_amount) AS total FROM loans WHERE branch_id = ? AND (status IS NULL OR status != 'Paid')";
if ($stmt = $conn->prepare($sql)) {
    $stmt->bind_param("i", $branch_id);
    $stmt->execute();
    $stmt->bind_result($total_loans);
    $stmt->fetch();
    $stmt->close();
}

// 7. Pesa mtaani (calculation ya remaining kwa kila mkopo)
//    Sasa tunachukua interest moja kwa moja kutoka loans (l.interest)
$total_remaining = 0;
$sql = "SELECT l.loan_amount, l.loan_period, l.interest, COALESCE(SUM(lc.amount_paid),0) AS paid 
        FROM loans l
        LEFT JOIN loans_collection lc ON l.loan_id = lc.loan_id
        WHERE l.branch_id = ?
        GROUP BY l.loan_id";
if ($stmt = $conn->prepare($sql)) {
    $stmt->bind_param("i", $branch_id);
    $stmt->execute();
    $result_total = $stmt->get_result();
    while ($row = $result_total->fetch_assoc()){
        $loan_interest = isset($row['interest']) ? floatval($row['interest']) : 0.0;
        // kama interest imehifadhiwa kama 5 (yaani 5%), fungua line hii:
        // if ($loan_interest > 1) { $loan_interest = $loan_interest / 100; }

        $calculated_interest = $row['loan_amount'] * $loan_interest * $row['loan_period'];
        $total_due = $row['loan_amount'] + $calculated_interest;
        $remaining = $total_due - $row['paid'];
        $total_remaining += $remaining;
    }
    $stmt->close();
}

// 8. Waliorejesha leo (filtered by branch)
$total_customers_today_collection = 0;
$sql_total_payments_today = "SELECT COUNT(DISTINCT customer_id) AS total_customers FROM loans_collection WHERE DATE(payment_date) = ? AND branch_id = ?";
if ($stmt = $conn->prepare($sql_total_payments_today)) {
    $stmt->bind_param("si", $today, $branch_id);
    $stmt->execute();
    $stmt->bind_result($total_customers_today_collection);
    $stmt->fetch();
    $stmt->close();
}

$conn->close();

// Tengeneza array ya response
$response = [
    "branch_interest" => $branch_interest,
    "total_customers" => $total_customers,
    "today_customers" => $today_customers,
    "total_loans_today" => $total_loans_today,
    "total_borrowers_today" => $total_borrowers_today,
    "total_collection_today" => $total_collection_today,
    "total_loans" => $total_loans,
    "total_remaining" => $total_remaining,
    "total_customers_today_collection" => $total_customers_today_collection,
];

header('Content-Type: application/json');
echo json_encode($response);
?>
