<?php

namespace Koneko\SatCatalogs\Http\Controllers;

use App\Http\Controllers\Controller;

use Koneko\SatCatalogs\Imports\SatCatalogsImport;
use Koneko\SatCatalogs\Services\SatCatalogService;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class SatCatalogController extends Controller
{
    /**
     * @return \Illuminate\Support\Collection
     */
    public function import(Request $request)
    {
        // Si es una solicitud POST, procesa la importación
        if ($request->isMethod('post')) {
            $validator = Validator::make($request->all(), [
                'file' => ['required', 'mimes:xls,xlsx'],
            ]);

            if ($validator->fails())
                return back()->withInput()->withErrors($validator);

            $time_start = microtime(true);
            $results    = [
                'details'       => [],
                'total_rows'    => 0,
                'total_created' => 0,
                'total_updated' => 0,
                'total_time'    => 0,
            ];

            $import   = new SatCatalogsImport();
            $filePath = request()->file('file');


            $time_sheet_start = microtime(true);
            $import->onlySheets('c_FormaPago');
            Excel::import($import, $filePath);
            $results['details'][] = [
                'name' => 'Forma de pago',
                'time' => round(microtime(true) - $time_sheet_start, 2),
                'created' => session('created'),
                'updated' => session('updated'),
            ];
            $results['total_rows'] += session('created') + session('updated');
            $results['total_created'] += session('created');
            $results['total_updated'] += session('updated');


            $time_sheet_start = microtime(true);
            $import->onlySheets('c_Moneda');
            Excel::import($import, $filePath);
            $results['details'][] = [
                'name' => 'Moneda',
                'time' => round(microtime(true) - $time_sheet_start, 2),
                'created' => session('created'),
                'updated' => session('updated'),
            ];
            $results['total_rows'] += session('created') + session('updated');
            $results['total_created'] += session('created');
            $results['total_updated'] += session('updated');


            $time_sheet_start = microtime(true);
            $import->onlySheets('c_CodigoPostal_Parte_1');
            Excel::import($import, $filePath);
            $import->onlySheets('c_CodigoPostal_Parte_2');
            Excel::import($import, $filePath);
            $results['details'][] = [
                'name' => 'Código postal',
                'time' => round(microtime(true) - $time_sheet_start, 2),
                'created' => session('created'),
                'updated' => session('updated'),
            ];


            $time_sheet_start = microtime(true);
            $import->onlySheets('c_RegimenFiscal');
            Excel::import($import, $filePath);
            $results['details'][] = [
                'name' => 'Regimen fiscal',
                'time' => round(microtime(true) - $time_sheet_start, 2),
                'created' => session('created'),
                'updated' => session('updated'),
            ];
            $results['total_rows'] += session('created') + session('updated');
            $results['total_created'] += session('created');
            $results['total_updated'] += session('updated');


            $time_sheet_start = microtime(true);
            $import->onlySheets('c_Pais');
            Excel::import($import, $filePath);
            $results['details'][] = [
                'name' => 'País',
                'time' => round(microtime(true) - $time_sheet_start, 2),
                'created' => session('created'),
                'updated' => session('updated'),
            ];
            $results['total_rows'] += session('created') + session('updated');
            $results['total_created'] += session('created');
            $results['total_updated'] += session('updated');


            $time_sheet_start = microtime(true);
            $import->onlySheets('c_UsoCFDI');
            Excel::import($import, $filePath);
            $results['details'][] = [
                'name' => 'Uso de CFDI',
                'time' => round(microtime(true) - $time_sheet_start, 2),
                'created' => session('created'),
                'updated' => session('updated'),
            ];
            $results['total_rows'] += session('created') + session('updated');
            $results['total_created'] += session('created');
            $results['total_updated'] += session('updated');


            $time_sheet_start = microtime(true);
            $import->onlySheets('c_Colonia_1');
            Excel::import($import, $filePath);
            $time_sheet_start = microtime(true);
            $import->onlySheets('c_Colonia_2');
            Excel::import($import, $filePath);
            $time_sheet_start = microtime(true);
            $import->onlySheets('c_Colonia_3');
            Excel::import($import, $filePath);
            $results['details'][] = [
                'name' => 'Colonia',
                'time' => round(microtime(true) - $time_sheet_start, 2),
                'created' => session('created'),
                'updated' => session('updated'),
            ];
            $results['total_rows'] += session('created') + session('updated');
            $results['total_created'] += session('created');
            $results['total_updated'] += session('updated');


            $time_sheet_start = microtime(true);
            $import->onlySheets('c_Estado');
            Excel::import($import, $filePath);
            $results['details'][] = [
                'name' => 'Estado',
                'time' => round(microtime(true) - $time_sheet_start, 2),
                'created' => session('created'),
                'updated' => session('updated'),
            ];
            $results['total_rows'] += session('created') + session('updated');
            $results['total_created'] += session('created');
            $results['total_updated'] += session('updated');


            $time_sheet_start = microtime(true);
            $import->onlySheets('c_localidad');
            Excel::import($import, $filePath);
            $results['details'][] = [
                'name' => 'Localidad',
                'time' => round(microtime(true) - $time_sheet_start, 2),
                'created' => session('created'),
                'updated' => session('updated'),
            ];
            $results['total_rows'] += session('created') + session('updated');
            $results['total_created'] += session('created');
            $results['total_updated'] += session('updated');


            $time_sheet_start = microtime(true);
            $import->onlySheets('c_municipio');
            Excel::import($import, $filePath);
            $results['details'][] = [
                'name' => 'Municipio',
                'time' => round(microtime(true) - $time_sheet_start, 2),
                'created' => session('created'),
                'updated' => session('updated'),
            ];
            $results['total_rows'] += session('created') + session('updated');
            $results['total_created'] += session('created');
            $results['total_updated'] += session('updated');


            $results['total_time'] = round(microtime(true) - $time_start, 2);

            return back()->with('results', $results);
        }

        return view('sat-catalogs::import.sat-catalog');
    }

    public function catalogAjax(string $catalog, Request $request)
    {
        $searchTerm = (string) $request->input('searchTerm', '');

        // Toma solo las llaves necesarias (o las que quieras permitir del request):
        $rawOptions = $request->only([
            'order_by',
            'order_dir',
            'status',
            'limit',
            'c_pais',
            'c_estado',
            'c_municipio',
            'c_localidad',
            'c_colonia',
            'c_codigo_postal',
            'select2Mode',
            'rawMode',
            'firstRow',
        ]);

        if($catalog == 'colonia'){
            $rawOptions['sat_codigo_postal.c_estado'] = $rawOptions['c_estado'] ?? '';
            $rawOptions['sat_codigo_postal.c_municipio'] = $rawOptions['c_municipio'] ?? '';
            $rawOptions['sat_codigo_postal.c_codigo_postal'] = $rawOptions['c_codigo_postal'] ?? '';
            $rawOptions['sat_colonia.c_colonia'] = $rawOptions['c_colonia'] ?? '';
        }

        // Filtra valores nulos o vacíos, para que no aparezcan esas claves.
        // (Si consideras '0', null o 'false' como válidos, ajusta la función de filtro)
        $options = array_filter($rawOptions, function ($value) {
            return !($value === '');
        });

        return response()->json(
            app(SatCatalogService::class)->searchCatalog($catalog, $searchTerm, $options)
        );
    }

}
