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

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

// Define base URL for images
$baseUrl = "https://api.bexamicrofinance.com/";

// Hakikisha table yako ina columns: nation_id, country, region, gps, na image
$sql = "SELECT 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, c.created_at,
               b.branch_name 
        FROM customers c 
        INNER JOIN branches b ON c.branch_id = b.branch_id 
        WHERE c.branch_id = ?
        ORDER BY c.firstname ASC";  // Panga alfabetically kulingana na firstname

if ($stmt = $conn->prepare($sql)) {
    $stmt->bind_param("i", $branch_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $customers = [];
    while ($row = $result->fetch_assoc()){
        // Ongeza base URL kama image haija kuwa URL kamili
        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);
} else {
    echo json_encode(["error" => "Query preparation failed"]);
}
?>
