<?php

namespace Modules\Admin\Database\seeders;

use Modules\Admin\App\Imports\SatCatalogsImport;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\File;
use Modules\Admin\App\Models\Sat\Banco;

class SATCatalogsSeeder extends Seeder
{
    protected $console;

    public function __construct($console = null)
    {
        $this->console = $console;
    }

    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $this->importCatCFDIV4(base_path("modules/Admin/Database/data/catCFDI_V_4_20241121.xls"));
        $this->importCatBancos(base_path('modules/Admin/Database/data/catalog-sat_bancos.json'));
    }

    private function importCatCFDIV4($file_path)
    {
        $import = new SatCatalogsImport($this->console);

        $sheets = [
            'c_FormaPago',
            'c_Moneda',
            'c_CodigoPostal_Parte_1',
            'c_CodigoPostal_Parte_2',
            'c_RegimenFiscal',
            'c_Pais',
            'c_UsoCFDI',
            'C_Colonia_1',
            'C_Colonia_2',
            'C_Colonia_3',
            'c_Estado',
            'C_Localidad',
            'C_Municipio',
        ];

        $this->command->getOutput()->progressStart(count($sheets));

        foreach ($sheets as $sheet) {
            $import = new SatCatalogsImport();
            $import->onlySheets($sheet);

            Excel::import($import, $file_path);

            $this->command->getOutput()->progressAdvance();
        }

        $this->command->getOutput()->progressFinish();
    }

    private function importCatBancos($file_path)
    {
        $json = File::get($file_path);

        // Convierte el contenido JSON a un array asociativo
        $bancos = json_decode($json, true);

        // Inserta cada banco en la base de datos
        foreach ($bancos as $banco) {
            Banco::create([
                'c_banco' => $banco['c_banco'],
                'descripcion' => $banco['descripcion'],
                'razon_social' => $banco['razon_social'],
                'rfc' => null,
                'status' => Banco::STATUS_ENABLED,
            ]);
        }
    }
}
