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

// Set timezone (Dar es Salaam)
date_default_timezone_set('Africa/Dar_es_Salaam');
include '../config.php';  // Inamishe DB connection $conn

// Chukua branch_id kutoka GET
$branch_id = isset($_GET['branch_id']) ? $_GET['branch_id'] : '';

if ($branch_id === '') {
    echo json_encode([
        'status'  => 'error',
        'message' => 'Missing required field: branch_id'
    ]);
    exit;
}

// Tukaeze kushirikisha fines na customer details (jina la kwanza, la kati, jina la mwisho, simu)
$sql = "
  SELECT 
    f.id AS fine_id,
    f.amount,
    f.description,
    f.date,
    f.loan_id,
    f.customer_id,
    f.branch_id,
    f.status,
    c.firstname,
    c.middlename,
    c.lastname,
    c.phone
  FROM fines AS f
  JOIN customers AS c ON f.customer_id = c.id
  WHERE f.branch_id = ?
  ORDER BY f.date DESC
";

$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $branch_id);
$stmt->execute();
$result = $stmt->get_result();

$data = [];
while ($row = $result->fetch_assoc()) {
    $data[] = [
        'id'           => (int)$row['fine_id'],
        'amount'       => (float)$row['amount'],
        'description'  => $row['description'],
        'date'         => $row['date'],
        'loan_id'      => (int)$row['loan_id'],
        'customer_id'  => (int)$row['customer_id'],
        'branch_id'    => (int)$row['branch_id'],
        'status'       => (int)$row['status'],
        'firstname'    => $row['firstname'],
        'middlename'   => $row['middlename'],
        'lastname'     => $row['lastname'],
        'phone'        => $row['phone'],
    ];
}

$stmt->close();
$conn->close();

echo json_encode([
    'status' => 'success',
    'data'   => $data
]);
?>
