<?php
// assets/includes/loadLocationsAndLevies.php
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');

require_once('../config/dbConnection.php');

$db   = DatabaseConnection::getInstance();
$conn = $db->getConnection();

if (!isset($_GET['cat']) || !ctype_digit((string)$_GET['cat'])) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid category id', 'locations' => [], 'count' => 0]);
    exit;
}

$cat = (int) $_GET['cat'];

$sql = "SELECT
          l.id,
          l.name,
          r.business_levy,
          r.fire_levy,
          r.health_permit,
          r.personal_levy_per_employee
        FROM smartsync_businesslocations AS l
        INNER JOIN smartsync_levyrates AS r
            ON r.location_id = l.id
        WHERE r.business_category_id = ?
        ORDER BY l.name ASC";

$stmt = $conn->prepare($sql);
if (!$stmt) {
    http_response_code(500);
    echo json_encode(['error' => 'Prepare failed: '.$conn->error, 'locations' => [], 'count' => 0]);
    exit;
}

$stmt->bind_param('i', $cat);
if (!$stmt->execute()) {
    http_response_code(500);
    echo json_encode(['error' => 'Execute failed: '.$stmt->error, 'locations' => [], 'count' => 0]);
    $stmt->close();
    exit;
}

/* Work with and without mysqlnd */
$locations = [];
if (method_exists($stmt, 'get_result')) {
    $res = $stmt->get_result();
    while ($row = $res->fetch_assoc()) {
        $locations[] = [
            'id'    => (int)$row['id'],
            'name'  => (string)$row['name'],
            'business_levy' => (float)$row['business_levy'],
            'fire_levy'     => (float)$row['fire_levy'],
            'health_permit' => (float)$row['health_permit'],
            'personal_levy_per_employee' => isset($row['personal_levy_per_employee'])
                ? (float)$row['personal_levy_per_employee'] : 0.0
        ];
    }
} else {
    $stmt->store_result();
    $stmt->bind_result($id, $name, $business_levy, $fire_levy, $health_permit, $personal);
    while ($stmt->fetch()) {
        $locations[] = [
            'id'    => (int)$id,
            'name'  => (string)$name,
            'business_levy' => (float)$business_levy,
            'fire_levy'     => (float)$fire_levy,
            'health_permit' => (float)$health_permit,
            'personal_levy_per_employee' => (float)($personal ?? 0.0),
        ];
    }
}

$stmt->close();

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