argument('file'); if (! is_file($path)) { $this->error("File not found: {$path}"); return self::FAILURE; } $payload = json_decode((string) file_get_contents($path), true); if (! is_array($payload)) { $this->error('Invalid JSON'); return self::FAILURE; } $counts = ['regions' => 0, 'provinces' => 0, 'cities' => 0, 'barangays' => 0]; try { DB::transaction(function () use ($payload, &$counts) { foreach ($payload['regions'] ?? [] as $r) { Region::updateOrCreate( ['psgc_code' => $r['psgc_code']], [ 'code' => $r['code'], 'name' => $r['name'], 'island_group' => $r['island_group'] ?? null, ], ); $counts['regions']++; } foreach ($payload['provinces'] ?? [] as $p) { $region = Region::where('psgc_code', $p['region_psgc'])->firstOrFail(); Province::updateOrCreate( ['psgc_code' => $p['psgc_code']], [ 'code' => $p['code'], 'name' => $p['name'], 'region_id' => $region->id, 'income_classification' => $p['income_classification'] ?? null, ], ); $counts['provinces']++; } foreach ($payload['cities_municipalities'] ?? [] as $c) { $province = Province::where('psgc_code', $c['province_psgc'])->firstOrFail(); CityMunicipality::updateOrCreate( ['psgc_code' => $c['psgc_code']], [ 'code' => $c['code'], 'name' => $c['name'], 'province_id' => $province->id, 'type' => $c['type'] ?? 'municipality', 'is_capital' => (bool) ($c['is_capital'] ?? false), 'classification' => $c['classification'] ?? null, ], ); $counts['cities']++; } foreach ($payload['barangays'] ?? [] as $b) { $city = CityMunicipality::where('psgc_code', $b['city_psgc'])->firstOrFail(); $boundary = isset($b['boundary_geojson']) ? Polygon::fromJson(json_encode($b['boundary_geojson'])) : null; $centroid = isset($b['centroid']) ? new Point((float) $b['centroid']['lat'], (float) $b['centroid']['lng'], 4326) : null; Barangay::updateOrCreate( ['psgc_code' => $b['psgc_code']], [ 'code' => $b['code'], 'name' => $b['name'], 'city_municipality_id' => $city->id, 'urban_rural' => $b['urban_rural'] ?? Barangay::URBAN_RURAL_UNKNOWN, 'population' => $b['population'] ?? null, 'boundary' => $boundary, 'centroid' => $centroid, ], ); $counts['barangays']++; } }); } catch (Throwable $e) { $this->error('Import failed: '.$e->getMessage()); return self::FAILURE; } $this->info(sprintf( 'Imported %d regions, %d provinces, %d cities, %d barangays', $counts['regions'], $counts['provinces'], $counts['cities'], $counts['barangays'], )); return self::SUCCESS; } }