<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\District;
use App\Models\Upazila;

class UpazilaSeeder extends Seeder
{
    public function run(): void
    {
        $path = base_path('public/data/bd_locations_bn.json');

        if (!file_exists($path)) {
            $this->command?->error("File not found: {$path}");
            return;
        }

        $json = json_decode(file_get_contents($path), true);

        $divisions = $json['data'] ?? [];
        $count = 0;

        foreach ($divisions as $div) {
            foreach (($div['districts'] ?? []) as $dist) {

                // District match by name_en (recommended)
                $district = District::where('name_en', $dist['name'] ?? null)->first();

                // fallback: name_bn match
                if (!$district && !empty($dist['bn_name'])) {
                    $district = District::where('name_bn', $dist['bn_name'])->first();
                }

                if (!$district) {
                    continue; // district না পেলে skip
                }

                foreach (($dist['upazilas'] ?? []) as $upa) {
                    $nameEn = $upa['name'] ?? null;
                    $nameBn = $upa['bn_name'] ?? null;

                    if (!$nameEn || !$nameBn) continue;

                    Upazila::updateOrCreate(
                        [
                            'district_id' => $district->id,
                            'name_en' => $nameEn,
                        ],
                        [
                            'name_bn' => $nameBn,
                        ]
                    );

                    $count++;
                }
            }
        }

        $this->command?->info("Upazilas seeded/updated: {$count}");
    }
}
