<?php
if (file_exists('../../../' . $_REQUEST['tenant'] . '/config.php')) {
    require_once('../../../' . $_REQUEST['tenant'] . '/config.php');
}

$client_id = (int)($_REQUEST['client_id'] ?? 0);
if ($client_id <= 0) {
    echo json_encode(['locations' => []]);
    exit;
}

$stmt = $con->prepare("
    SELECT locnumber, locname, postcode, locaddress1, locaddress2, locaddress3, locaddress4
    FROM locations
    WHERE clientnumber = ? AND statuslive = 1
    ORDER BY locname ASC, postcode ASC
");
$stmt->bind_param('i', $client_id);
$stmt->execute();
$result = $stmt->get_result();

$locations = [];
while ($row = $result->fetch_assoc()) {
    $address = array_filter([
        $row['locaddress1'] ?? '',
        $row['locaddress2'] ?? '',
        $row['locaddress3'] ?? '',
        $row['locaddress4'] ?? '',
        $row['postcode'] ?? ''
    ]);
    $locations[] = [
        'locnumber' => (int)$row['locnumber'],
        'locname' => $row['locname'],
        'postcode' => $row['postcode'],
        'address' => implode(', ', $address)
    ];
}

echo json_encode(['locations' => $locations]);

$stmt->close();
$con->close();
?>
