<?php
/*
    Nombre del programador:         Cordourier Rojas Mathew
    Ultima fecha de modificación:   [ 24 / Abril / 2023 ]
    Descripción:                    Controlador del submodulo Personal. Perteneciente al Módulo 13 - Gestion del Personal de Mantenimiento
*/

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use PhpOffice\PhpSpreadsheet\IOFactory;
use stdClass;
use Throwable;

ini_set('memory_limit', '-1');

class CountriesController extends Controller
{
    private $response_controller;
    private $encrypt_controller;
    public function __construct()
    {
        $this->response_controller = new ResponseController();
        $this->encrypt_controller = new EncryptionController();
    }

    public function getCountries($line_number)
    {
        try {

            // Busca si el subcontratista existe
            $countries = DB::table("S002V01TPAIS")
                ->select(
                    "PAIS_IDPA as COUNTRY_ID",
                    "PAIS_NOMB as NAME",
                    "PAIS_LADA as LADA",
                    "PAIS_NOME AS NOMECLARUTA_ISO2",
                    "PAIS_NOM2 AS NOMECLARUTA_ISO3"
                )
                ->where('PAIS_NULI', '=', $line_number)
                ->get();

            // Verifica si el objeto esta vacio
            if (!isset($countries[0]) && empty($countries[0])) {
                return $this->response_controller
                    ->makeResponse(TRUE, "ERR_SUBCONTRATISTA_REG001: No se encontró al subcontratista", $countries, 500);
            }

            return $this->response_controller->makeResponse(FALSE, 'Consulta exitosa', $countries);

        } catch (Throwable $th) {
            return $this->response_controller
                ->makeResponse(TRUE, 'ERR_SUBCONTRATISTA_REG005: Error inesperado', strtoupper($th->getMessage()), 500);
        }
    }

    public function getDataByPostalCode($postal_code, $line)
    {
        try {

            $state = "N/A";
            $municipality = "N/A";
            $arr_suburb = [];
            $country = "N/A";

            $flag = false; # Indica cuando la información sea encontrada para salir del ciclo

            // Carga el documento y verifica cuantas hojas tiene
            $document = IOFactory::load(Storage::disk('excel')->path("c_CodigoPostal.xls"));
            $max_sheets = $document->getSheetCount();

            // Verifica por fila los datos buscando el correcto
            for ($i = 0; $i < $max_sheets; $i++) {
                $sheet = $document->getSheet($i);
                $max_row = $sheet->getHighestRow(); # Fila
                for ($o = 8; $o <= $max_row; $o++) {
                    if ($sheet->getCell("A" . $o)->getValue() == $postal_code) {
                        $state = $sheet->getCell("B" . $o)->getValue();
                        $municipality = $sheet->getCell("C" . $o)->getValue();
                        $flag = true;
                        break;
                    }
                }

                // Si el dato se encontró, sale del ciclo para no entrar en otra hoja
                if ($flag) {
                    break;
                }
            }

            // Verifica si el código postal se encontró en el catalogo
            if($flag){
                $flag = false;
            }else{
                return $this->response_controller
                ->makeResponse(TRUE, "ERR_PAIS_REG001: El código postal {$postal_code} no existe", [], 400);
            }

            $document = IOFactory::load(Storage::disk('excel')->path("c_Municipio.xls"));
            $max_sheets = $document->getSheetCount();


            for ($i = 0; $i < $max_sheets; $i++) {
                $sheet = $document->getSheet($i);
                $max_row = $sheet->getHighestRow(); # Fila
                for ($o = 5; $o <= $max_row; $o++) {
                    if ($sheet->getCell("A" . $o)->getValue() == $municipality && $sheet->getCell("B" . $o)->getValue() == $state) {
                        $municipality = $sheet->getCell("C" . $o)->getValue();
                        break;
                    }
                }
            }

            $document = IOFactory::load(Storage::disk('excel')->path("c_Estado.xls"));
            $max_sheets = $document->getSheetCount();


            for ($i = 0; $i < $max_sheets; $i++) {
                $sheet = $document->getSheet($i);
                $max_row = $sheet->getHighestRow(); # Fila
                for ($o = 5; $o <= $max_row; $o++) {
                    if ($sheet->getCell("A" . $o)->getValue() == $state) {
                        $country = $sheet->getCell("B" . $o)->getValue();
                        $state = $sheet->getCell("C" . $o)->getValue();
                        break;
                    }
                }
            }

            $document = IOFactory::load(Storage::disk('excel')->path("c_Pais.xls"));
            $max_sheets = $document->getSheetCount();


            for ($i = 0; $i < $max_sheets; $i++) {
                $sheet = $document->getSheet($i);
                $max_row = $sheet->getHighestRow(); # Fila
                for ($o = 5; $o <= $max_row; $o++) {
                    if ($sheet->getCell("A" . $o)->getValue() == $country) {
                        $country = $sheet->getCell("B" . $o)->getValue();
                        break;
                    }
                }
            }

            $document = IOFactory::load(Storage::disk('excel')->path("c_Colonia.xls"));
            $max_sheets = $document->getSheetCount();

            for ($i = 0; $i < $max_sheets; $i++) {
                $sheet = $document->getSheet($i);
                $max_row = $sheet->getHighestRow(); # Fila
                for ($o = 5; $o <= $max_row; $o++) {
                    if ($sheet->getCell("B" . $o)->getValue() == $postal_code) {
                        $arr_suburb[] = $sheet->getCell("C" . $o)->getValue();
                    }
                }
            }

            $data = new stdClass();
            $data->POSTAL_CODE = $postal_code;
            $data->SUBURB = sizeof($arr_suburb) != 0 ? $arr_suburb : "N/A";
            $data->MUNICIPALITY = $municipality != null ? $municipality : "N/A";
            $data->STATE = $state != null ? $state : "N/A";
            $data->COUNTRY = $country != null ? $country : "N/A";

            return $this->response_controller->makeResponse(false, 'Consulta Exitosa', $data, 200);


        } catch (Throwable $th) {
            return $this->response_controller
                ->makeResponse(TRUE, 'ERR_PAIS_REG002: Error inesperado', strtoupper($th->getMessage()), 500);
        }
    }

    public function getSuburbByPostalCode($postal_code, $line)
    {
        try {
            $arr_suburb = [];

            $document = IOFactory::load(Storage::disk('excel')->path("c_Colonia.xls"));
            $max_sheets = $document->getSheetCount();

            for ($i = 0; $i < $max_sheets; $i++) {
                $sheet = $document->getSheet($i);
                $max_row = $sheet->getHighestRow(); # Fila
                for ($o = 5; $o <= $max_row; $o++) {
                    if ($sheet->getCell("B" . $o)->getValue() == $postal_code) {
                        $arr_suburb[] = $sheet->getCell("C" . $o)->getValue();
                    }
                }
            }

            return $this->response_controller->makeResponse(false, 'Consulta Exitosa', sizeof($arr_suburb) != 0 ? $arr_suburb : "N/A", 200);


        } catch (Throwable $th) {
            return $this->response_controller
                ->makeResponse(TRUE, 'ERR_PAIS_REG000: Error inesperado', strtoupper($th->getMessage()), 500);
        }
    }
}
