<?php
include '../../config.php';

$branch_id = isset($_GET['branch_id']) ? intval($_GET['branch_id']) : null;
$user_id   = isset($_GET['user_id'])   ? intval($_GET['user_id'])   : 0;
$baseUrl   = "https://api.bexamicrofinance.com/";

if ($branch_id !== null && $branch_id > 0) {
    $sql = 
      "SELECT DISTINCT c.id,
               c.firstname, c.middlename, c.lastname,
               c.phone, c.street, c.ward,
               c.nation_id, c.country, c.region,
               c.gps, c.image,
               b.branch_name
       FROM customers c
       INNER JOIN branches b ON c.branch_id = b.branch_id
       LEFT JOIN loans l ON c.id = l.customer_id AND l.status IS NULL
       WHERE c.branch_id = ?
         AND b.user_id    = ?
         AND l.loan_id IS NULL
       ORDER BY c.firstname ASC";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ii", $branch_id, $user_id);

} else {
    $sql = 
      "SELECT DISTINCT c.id,
               c.firstname, c.middlename, c.lastname,
               c.phone, c.street, c.ward,
               c.nation_id, c.country, c.region,
               c.gps, c.image,
               b.branch_name
       FROM customers c
       INNER JOIN branches b ON c.branch_id = b.branch_id
       LEFT JOIN loans l ON c.id = l.customer_id AND l.status IS NULL
       WHERE b.user_id = ?
         AND l.loan_id IS NULL
       ORDER BY c.firstname ASC";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $user_id);
}


$stmt->execute();
$result = $stmt->get_result();

$customers = [];
while ($row = $result->fetch_assoc()) {
    if (!empty($row['image']) && !preg_match('/^https?:\/\//', $row['image'])) {
        $row['image'] = $baseUrl . $row['image'];
    }
    $customers[] = $row;
}

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

header('Content-Type: application/json');
echo json_encode($customers);
