<?php

namespace App\Http\Controllers\Urbano;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\{DB,Http};

class UrbanoController extends Controller
{
    CONST BASE_URL = 'https://api.urbanoexpress.com.pe/pyp/ws/ue/ge';
    CONST USER_PROD = 'WS.KR5320'; #'WS_USER_SOMET';
    CONST PWD_PROD = '4b85ba1b0cb30e7a24e3c4f99bbe1a39dd165def'; #'001e366e1029f20131e32ebad9fe3b5a6afb9668';
    CONST ID_CONTRATO = '8779'; #'8051'; 
    CONST MONEDA = 'SOL';

    public function generateGuiaUrbano (Request $request){
        
        $order = $request->orden;
        $portal = $request->portal;
        $dniClient = $request->nit_destinatario;
        $nomClient = $request->nombre_destinatario;
        $dirCli = $request->direccion_destinatario;
        $telClient = $request->telefono_destinatario;
        $emlClient = $request->email_destinatario;
        $city = $request->ciudad_destinatario;
        $dept = $request->departamento_destinatario;
        $codCity = str_pad($request->ubigeo_destinatario, 6, "0", STR_PAD_LEFT);
        $dniRemitente = $request->tienda_remitente; 
        $nomRemitente = $request->nombre_remitente;
        $dirRemitente = $request->direccion_remitente;
        $userguia = $request->user;
        
        $order_id_products = json_decode($request->orders_id);
        $qPrdsIn = "('". implode("','",$order_id_products)."')";
        $qProducts = <<<PRDS
        select sod.id, sod.order_item_id, sod.order_id, item_id sku, sod.item_price, sod.discount, sod.full_price, sod.shipping_amount, idb."No" referencia,  idb."Description" descrip, idb."Item_Family_Code" marca from sale_orders_detail sod
        inner join items_data_base idb on sod.item_id = idb."DefaultBarcode"
        where sod.order_item_id in $qPrdsIn
        PRDS;
        $products = DB::connection('pgsql')->select($qProducts);

        $tipopago = !$request->recaudar ? 'PAG' : 'COD' ;
        #$tipopago = !$request->recaudar ? 'PAG' : 'EFE' ;
        $importe = $request->recaudar ? $request->valor : '0' ;
        
        //Fin datos enviados por el InvoiceOrders
        $ubigeo = DB::connection('pgsql')->select("select ubigeo from stores_dependencies sd  where dependency = '$dniRemitente'")[0]->ubigeo;
        $userguia=$userguia.'||'.$dniRemitente;
            
        $dirClient = $dirCli;
        $codCity=ltrim($codCity);		
            
        if (!empty($codCity)) {
            $codigo = self::codeCity ($city,$dept,$codCity);
        }else {
            $codigo = self::codCity ($city,$city);
        }
        
        $params = [
            "linea"			=> "3",
            "id_contrato"	=> self::ID_CONTRATO,
            
            # DATOS DEL DOCUMENTO CLIENTE,
            "cod_rastreo"	=> $order, //de donde sale
            "cod_barras"	=> '',// no es necesario
            "fech_emi_vent"	=> '',
            "nro_o_compra"	=> '',// no es necesario
            "nro_guia_trans"=> '',// no es necesario
            "nro_factura"	=> '',// no es necesario
            
            # data cliente
            "cod_cliente"	=> $dniClient,
            "nom_cliente"	=> $nomClient,
            "nom_empresa"	=> '',
            "nro_telf"		=> str_ireplace(["number","area_code"," "] , ["/","/",""], $telClient),
            "nro_telf_mobil"=> str_ireplace(["number","area_code"," "] , ["/","/",""], $telClient),
            "correo_elec"	=> $emlClient,
            
            # datos de la entrega
            "dir_entrega"	=> self::acronimos($dirClient),
            "nro_via" 		=> '',
            "nro_int" 		=> '',
            "nro_urb"		=> '',
            "nom_urb"		=> '',
            "ubi_direc"		=> $codigo,
            "ref_direc"		=> '',
            "id_direc"		=> 0,
            
            # datos de la entrega
            "fech_pro"	=> '',
            "arco_hor"	=> '',
            "fech_venc"	=> '',
            
            # AUTORIZADOS 
            "nom_autorizado"		=> '',
            "nro_doc_autorizado"	=> '',
            "nom_autorizado_2"		=> '',
            "nro_doc_autorizado_2"	=> '',
            
            # COBRANZA
            "med_pago"		=> $tipopago,
            "descripcion"	=> '',
            "anotacion"		=> '',
            "moneda"		=> self::MONEDA,
            "importe"		=> $importe,

            # DATOS PARAA DESPACHOS DEL BULTO O PAQUETE QUE SE ENVIA
            "peso_total"		=> "1",
            "pieza_total"		=> count($order_id_products),
            "urgente"			=> "NO",
            "picking"			=> "NO",
            "mecanizado"		=> "NO",
            "asegurado"			=> "NO",
            "monto_asegurado"	=> 0,
            "via_aereo"			=> "NO",
            
            # DATOS DEL SELLER
            "venta_seller"	=> "SI",
            
            #SELLER DATOS REMITENTE
            "sell_codigo"	=> $dniRemitente,
            "sell_nombre"	=> $nomRemitente,
            "sell_direcc"	=> $dirRemitente,
            "sell_ubigeo"	=> $ubigeo
        ];

        $arrDad = [];
        $items='';
        
        foreach ($products as $prd) {       
            
            $items= $items."'".$prd->referencia."',";
            $pila = [
                "cod_sku"		=> $prd->sku,
                "descr_sku"		=> $prd->descrip,
                "modelo_sku"	=> $prd->referencia,
                "marca_sku"		=> $prd->marca,
                "peso_sku"		=> "1",
                "peso_v_sku"	=> "1",
                "valor_sku"		=> $prd->item_price,
                "cantidad_sku"	=> 1,
                "alto"			=> "13",
                "largo"			=> "15",
                "ancho"			=> "18"
            ];

            $arrDad[] = $pila;
        }

        $params['productos'] = $arrDad;
        
        $items = substr($items, 0, -1);
        $data = ['json' => json_encode ($params)];

        $responseHttpClient = Http::withHeaders([
            'Content-Type' => 'application/x-www-form-urlencoded',
            'user' => self::USER_PROD,
            'pass' => self::PWD_PROD,
        ])->asForm()
          ->post(self::BASE_URL, $data);

        if($responseHttpClient->successful()){
            $resGuia = $responseHttpClient->json();
            #if($request->orden == '1273-MALVA_ONLINE'){ dd($resGuia); }
            $fileName = 'mvper_'.$resGuia['guia'].'.pdf';
            try {
                $reqFile = Http::get($resGuia['etiqueta']);
                if ($reqFile->successful()) {
                    $filePath = public_path('Files/Urbano/Malva-Vendor-peru') . '/' . $fileName;
                    file_put_contents($filePath, $reqFile->body());
                    $fileBase64 = base64_encode(file_get_contents($filePath));
                    $resGuia['guiaBase64'] = $fileBase64;
                    $paramSaveToDatabase = json_encode($params);
                    $dateLog = date('Y-m-d H:i:s');
                    DB::connection('pgsql')->insert("insert into webhook_records (canal, contenido,fecha) values ('guide_urbano_param','$paramSaveToDatabase','$dateLog')");
                }
            } catch (\Exception $e) {
                #dd($e);
                $resGuia = [ 'params' => $params, 'message'=> 'Ha ocurrido un error al generar la guia por urbano! Proyecto: g_new_transportadoras - File: UrbanoController - Funcion: generateGuiaUrbano' ,'error'=> $resGuia];
            }
            
        }else{
            $resGuia = [ 'params' => $params, 'message'=> 'Ha ocurrido un error al generar la guia por urbano! Proyecto: g_new_transportadoras - File: UrbanoController - Funcion: generateGuiaUrbano' ,'error'=> $responseHttpClient->json()];
        }

        return $resGuia;
    }

    public function codeCity ($city, $dept ,$codCiudad = null) {
        
        /* if( $city == 'ICA' && $dept == 'ICA' ){ $codCiudad='110101'; }
        if (!empty($codCiudad)) {
            $query = "SELECT codigo FROM delivery_cities_urbano WHERE codigo ilike '%$codCiudad%' limit 1";
        }else {
            code_city:
            $query = "SELECT codigo FROM delivery_cities_urbano WHERE departamento ilike '%$dept%' AND distrito ilike '%$city%' limit 1";
        }

        $code = DB::connection('pgsql')->select($query);
        
        if ($code && isset($code[0]->codigo)) {
          return $code[0]->codigo;
        }else {
            goto code_city;
            #return '150101'; #"Error: No se pudo obtener el codigo para ".$provincia." - ".$distrito;
        } */

        $maxIntentos = 2; // Número máximo de intentos
        $intentos = 0; // Contador de intentos

        if ($city == 'ICA' && $dept == 'ICA') {
            $codCiudad = '110101';
        }

        if (!empty($codCiudad)) {
            $query = "SELECT codigo FROM delivery_cities_urbano WHERE codigo ilike '%$codCiudad%' limit 1";
        } else {
            $query = "SELECT codigo FROM delivery_cities_urbano WHERE departamento ilike '%$dept%' AND distrito ilike '%$city%' limit 1";
        }

        while ($intentos < $maxIntentos) {
            $code = DB::connection('pgsql')->select($query);
            
            if ($code && isset($code[0]->codigo)) {
                return $code[0]->codigo;
            } else {
                $intentos++;
                if ($intentos < $maxIntentos) {
                    $query = "SELECT codigo FROM delivery_cities_urbano WHERE departamento ilike '%$dept%' AND distrito ilike '%$city%' limit 1";
                }
            }
        }
        throw new Exception("Error: No se pudo obtener el código para $dept - $city después de $maxIntentos intentos.");
    }

    public function acronimos ($addres) {
        return str_ireplace(["calle","referencia","carrera","avenida"], ["Cll","Ref","Cra","Av"] , $addres);
    }
        
}
