<?php

namespace Database\Seeders;

use App\Models\DepartmentMunicipality;
use Illuminate\Database\Seeder;
use Maatwebsite\Excel\Facades\Excel; // Asegúrate de que esto esté importado

class GeoDataSeeder extends Seeder
{
    public function run(): void
    {
        $file = storage_path('app/geo/municipios.csv'); // Ajusta la ruta a tu archivo CSV/Excel

        if (! file_exists($file)) {
            // Crea el directorio si no existe
            if (! is_dir(storage_path('app/geo'))) {
                mkdir(storage_path('app/geo'), 0755, true);
            }
            // Por favor, pon tu archivo de geodatos en esta ruta.
            $this->command->warn('❌ Archivo de geodatos no encontrado en: '.$file);

            return;
        }

        $this->command->info('⏳ Importando datos geográficos...');

        // Usamos la importación simple si el archivo es un CSV bien formateado
        $data = Excel::toArray([], $file)[0]; // Obtiene los datos del primer sheet/archivo

        // Eliminar la fila de cabeceras
        $headers = array_shift($data);

        $insertData = [];
        $now = now();

        foreach ($data as $row) {
            // 1. Reemplazar la coma por el punto en las coordenadas (si existen)
            $longitude = $row[5] ?? null;
            if ($longitude !== null) {
                $longitude = str_replace(',', '.', $longitude);
            }

            $latitude = $row[6] ?? null;
            if ($latitude !== null) {
                $latitude = str_replace(',', '.', $latitude);
            }

            $insertData[] = [
                'department_code' => $row[0],
                'department_name' => $row[1],
                'municipality_code' => $row[2],
                'municipality_name' => $row[3],
                'type' => $row[4] ?? 'Municipio',
                // 2. Usar las variables corregidas
                'longitude' => $longitude,
                'latitude' => $latitude,
                'created_at' => $now,
                'updated_at' => $now,
            ];
        }

        // Insertar en bloques para eficiencia
        $chunks = array_chunk($insertData, 500);
        foreach ($chunks as $chunk) {
            DepartmentMunicipality::insert($chunk);
        }

        $this->command->info('✅ Importación de '.count($insertData).' registros completada.');
    }
}
