<?php
// council_lookup.php
header('Content-Type: application/json; charset=utf-8');

try {
    // Expect town, postcode, state = TAS
    $town     = isset($_GET['town']) ? trim($_GET['town']) : '';
    $postcode = isset($_GET['postcode']) ? trim($_GET['postcode']) : '';
    $state    = isset($_GET['state']) ? strtoupper(trim($_GET['state'])) : '';

    if ($town === '' || $postcode === '' || $state !== 'TAS') {
        echo json_encode(['ok' => false, 'reason' => 'missing or invalid params']);
        exit;
    }

    // Load your data file that defines $councils
    // Change this path to where your 743 line file lives
    require __DIR__ . '/councils_tas.php'; // defines $councils = array(...)

    $needleTown = mb_strtolower($town);
    $needlePC   = $postcode;

    $found = null;
    foreach ($councils as $row) {
        // Defensive checks
        if (!isset($row['town'], $row['postcode'])) continue;

        if (mb_strtolower($row['town']) === $needleTown && (string)$row['postcode'] === (string)$needlePC) {
            $found = [
                'council'   => $row['council'] ?? '',
                'shapeFile' => $row['shapeFile'] ?? ''
            ];
            break;
        }
    }

    if ($found) {
        echo json_encode(['ok' => true] + $found);
    } else {
        echo json_encode(['ok' => false, 'reason' => 'not found']);
    }
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'reason' => 'server error']);
}
