<?php
/**
 * ONE-TIME converter: upazilas.csv -> /data/upazilas.json
 *
 * Why this exists:
 * The upstream file the site used to depend on
 * (raw.githubusercontent.com/nuhil/bangladesh-geocode) now 404s because the
 * project moved its files into subfolders. Rather than depend on an external
 * URL at all (bad for production - the whole reason the site broke), this
 * script converts a LOCAL copy of the official CSV into the exact JSON shape
 * GlowSpace's checkout page expects:
 *   [{"id":"1","district_id":"47","name":"Savar","bn_name":"সাভার"}, ...]
 *
 * HOW TO USE:
 * 1. On your own computer, open this URL in a normal browser (not curl/bot):
 *    https://github.com/nuhil/bangladesh-geocode/raw/refs/heads/master/upazilas/upazilas.csv
 *    Save it as upazilas.csv
 * 2. Upload upazilas.csv into this /tools folder via cPanel File Manager (or SFTP).
 * 3. Run this script once:
 *      php tools/csv_to_json.php
 *    (or open https://yourdomain.com/tools/csv_to_json.php in a browser ONE TIME,
 *     then delete this file immediately afterward - never leave it public.)
 * 4. It writes the result to /data/upazilas.json.
 * 5. Delete tools/upazilas.csv and tools/csv_to_json.php from the server.
 *
 * The CSV columns follow the source project's format:
 * id,district_id,name,bn_name,lat,lon
 * If the header row differs, adjust $map below to match.
 */

$csvPath  = __DIR__ . '/upazilas.csv';
$outPath  = dirname(__DIR__) . '/data/upazilas.json';

if (!is_file($csvPath)) {
    die("Place upazilas.csv in this folder first (see instructions in this file's header comment).\n");
}

$rows = array_map('str_getcsv', file($csvPath));
$header = array_map('trim', array_shift($rows));

$result = [];
foreach ($rows as $row) {
    if (count($row) < count($header)) continue;
    $assoc = array_combine($header, $row);
    $result[] = [
        'id'          => $assoc['id'] ?? '',
        'district_id' => $assoc['district_id'] ?? '',
        'name'        => $assoc['name'] ?? '',
        'bn_name'     => $assoc['bn_name'] ?? '',
    ];
}

file_put_contents($outPath, json_encode($result, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
echo "Wrote " . count($result) . " upazilas to $outPath\n";