<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use App\Http\Controllers\ResponseController;
use App\Http\Controllers\ResourcesController;
use App\Http\Controllers\EncryptionController;
use App\Http\Controllers\DocumentManagementController;
use App\Http\Controllers\FunctionsController;

class InvoiceControlController extends Controller {

    private $responseController;
    private $encController;
    private $resourcesController;
    private $functionsController;
    private $documentManagementController;

    public function __construct() {
        $this->responseController = new ResponseController();
        $this->encController = new EncryptionController();
        $this->resourcesController = new ResourcesController();
        $this->functionsController = new FunctionsController();
        $this->documentManagementController = new DocumentManagementController();
    }

    public function getCompareInvoice($user, $line) {
        try {
            $getInvoice = DB::table('S002V01TFALS')
                ->where('FALS_NULI', '=', $line)
                ->where('DLSC_NULI', '=', $line)
                ->where('LINE_NULI', '=', $line)
                ->join('S002V01TLINE','LINE_IDLI','=','FALS_IDLI')
                ->join('S002V01TDLSC','FALS_IDFA','=','DLSC_IDFA')
                ->get([
                    'FALS_IDFA',
                    'FALS_IDLI',
                    'FALS_CODO',
                    'FALS_UUID',
                    'FALS_VERS',
                    'FALS_FEEM',
                    'FALS_RFCE',
                    'FALS_RFCR',
                    'FALS_FOLI',
                    'FALS_SERI',
                    'FALS_FOPA',
                    'FALS_MEPA',
                    'FALS_TICA',
                    'FALS_MONE',
                    'FALS_COPA',
                    'FALS_ESTA',
                    'FALS_USRE',
                    'FALS_FERE',
                    'FALS_USMO',
                    'FALS_FEMO',
                    'LINE_NUPR',
                    'LINE_OTPR',
                    'LINE_OTCO',
                    'LINE_ESTA',
                    'DLSC_IDDO',
                    'DLSC_CODO',
                    'DLSC_TIPO',
                    'DLSC_DESC',
                    'DLSC_ESTA',
                ]);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true, "ERR_INVOICE_GET000: Ocurrió un error al obtener las facturas.", $th->getMessage(), 500);
        }
        $arrInvoice = json_decode(json_encode($getInvoice), true);
        return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $arrInvoice);
    }

    public function getInvoicePayment($user, $line ){
        try {
            $getInvoice = DB::table('S002V01TFALS')
                ->where('FALS_NULI', '=', $line)
                ->where('DLSC_NULI', '=', $line)
                ->where('LINE_NULI', '=', $line)
                ->where('DLSC_TIPO', '=', 'Abono')
                ->join('S002V01TLINE','LINE_IDLI','=','FALS_IDLI')
                ->join('S002V01TDLSC','FALS_IDFA','=','DLSC_IDFA')
                ->get([
                    'FALS_IDFA',
                    'FALS_IDLI',
                    'FALS_CODO',
                    'FALS_UUID',
                    'FALS_VERS',
                    'FALS_FEEM',
                    'FALS_RFCE',
                    'FALS_RFCR',
                    'FALS_FOLI',
                    'FALS_SERI',
                    'FALS_FOPA',
                    'FALS_MEPA',
                    'FALS_TICA',
                    'FALS_MONE',
                    'FALS_COPA',
                    'FALS_ESTA',
                    'FALS_USRE',
                    'FALS_FERE',
                    'FALS_USMO',
                    'FALS_FEMO',
                    'LINE_NUPR',
                    'LINE_OTPR',
                    'LINE_OTCO',
                    'LINE_ESTA',
                    'DLSC_IDDO',
                    'DLSC_CODO',
                    'DLSC_TIPO',
                    'DLSC_DESC',
                    'DLSC_ESTA',
                ]);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true, "ERR_INVOICE_GET000: Ocurrió un error al obtener las facturas.", $th->getMessage(), 500);
        }
        $arrInvoice = json_decode(json_encode($getInvoice), true);
        return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $arrInvoice);
    }

    public function getInvoiceById($idInvoice, $user, $line) {
        try {
            $idInvoice = $this->encController->decrypt($idInvoice);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true, "ERR_INVOICE_GETBYID000: Ocurrió un error al obtener el identificador de la factura.", $th->getMessage(), 500);
        }

        try {
            $arrInvoice = (array) DB::table('S002V01TFALS')
                ->where('FALS_IDFA', '=', $idInvoice)
                ->where('FALS_NULI', '=', $line)
                ->where('FALS_ESTA', '=', 'Activo')
                ->first([
                    'FALS_IDFA',
                    'FALS_NULI',
                    'FALS_IDLI',
                    'FALS_CODO',
                    'FALS_UUID',
                    'FALS_VERS',
                    'FALS_FEEM',
                    'FALS_RFCE',
                    'FALS_RFCR',
                    'FALS_FOLI',
                    'FALS_SERI',
                    'FALS_FOPA',
                    'FALS_MEPA',
                    'FALS_TICA',
                    'FALS_MONE',
                    'FALS_COPA',
                ]);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true, "ERR_INVOICE_GETBYID001: Ocurrió un error al obtener la factura.", $th->getMessage(), 500);
        }

        return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $arrInvoice);
    }

    public function getBudgetManagement($user, $line) {
        try {
            $getInvoice = DB::table('S002V01TFALS')
                ->where('FALS_NULI', '=', $line)
                ->where('DLSC_NULI', '=', $line)
                ->where('LINE_NULI', '=', $line)
                ->whereNotNull('LINE_OTPR')
                ->orWhereNotNull('LINE_OTCO')
                ->join('S002V01TLINE','LINE_IDLI','=','FALS_IDLI')
                ->join('S002V01TDLSC','FALS_IDFA','=','DLSC_IDFA')
                ->get([
                    'FALS_IDFA',
                    'FALS_IDLI',
                    'FALS_CODO',
                    'FALS_UUID',
                    'FALS_VERS',
                    'FALS_FEEM',
                    'FALS_RFCE',
                    'FALS_RFCR',
                    'FALS_FOLI',
                    'FALS_SERI',
                    'FALS_FOPA',
                    'FALS_MEPA',
                    'FALS_TICA',
                    'FALS_MONE',
                    'FALS_COPA',
                    'FALS_ESTA',
                    'FALS_USRE',
                    'FALS_FERE',
                    'FALS_USMO',
                    'FALS_FEMO',
                    'LINE_NUPR',
                    'LINE_OTPR',
                    'LINE_OTCO',
                    'LINE_ESTA',
                    'DLSC_IDDO',
                    'DLSC_CODO',
                    'DLSC_TIPO',
                    'DLSC_DESC',
                    'DLSC_ESTA',
                ]);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true, "ERR_INVOICE_GET000: Ocurrió un error al obtener las facturas.", $th->getMessage(), 500);
        }
        $arrInvoice = json_decode(json_encode($getInvoice), true);
        return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $arrInvoice);
    }

    public function generateSheetInvoiceXLS( $orderNumber, $user, $line ) {
        try {
            $idOrder = $this->encController->decrypt($orderNumber);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(
                true, 
                "ERR_ORDER_SHEET000: Ocurrió un error al obtener el número del proveedor.", 
                $th->getMessage(), 
                500
            );
        }

        try {
            $user = $this->encController->decrypt($user);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(
                true, 
                "ERR_ORDER_SHEET001: Ocurrió un error al obtener el usuario.", 
                $th->getMessage(), 
                500
            );
        }

        try {
            $arrOrder = (array) DB::table('S002V01TORCO')
                ->where('ORCO_NUOR', '=', $idOrder)
                ->where('ORCO_NULI', '=', $line)
                ->where('LINE_NULI', '=', $line)
                ->where('DESP_NULI', '=', $line)
                ->where('PROV_NULI', '=', $line)
                ->where('DESP_ESTA', '=', 'Activo')
                ->where('PROV_ESTA', '=', 'Activo')
                ->join('S002V01TLINE', 'LINE_IDLI', '=', 'ORCO_IDLI')
                ->join('S002V01TDESP', 'DESP_IDDE', '=', 'ORCO_IDDE')
                ->join('S002V01TPROV', 'PROV_NUPR', '=', 'LINE_NUPR')
                ->join('S002V01TREFI', 'REFI_CRFI', '=', 'PROV_CRFI')
                ->first([
                    'ORCO_NUOR',
                    'ORCO_ESTA',
                    'LINE_IDLI',
                    'LINE_OTPR',
                    'LINE_OTCO',
                    'LINE_ESTA',
                    'DESP_IDDE',
                    'DESP_NODE',
                    'DESP_NOMB',
                    'DESP_APPA',
                    'DESP_APMA',
                    'DESP_LADA',
                    'DESP_TELE',
                    'DESP_CORR',
                    'DESP_CALL',
                    'DESP_NUEX',
                    'DESP_NUIN',
                    'DESP_COPO',
                    'DESP_COLO',
                    'DESP_LOCA',
                    'DESP_MUNI',
                    'DESP_ENTI',
                    'DESP_PAIS',
                    'DESP_COME',
                    'PROV_NUPR',
                    'PROV_IDPS',
                    'PROV_NOCO',
                    'PROV_NOMB',
                    'PROV_APPA',
                    'PROV_APMA',
                    'PROV_CORR',
                    'PROV_LAD1',
                    'PROV_TEL1',
                    'PROV_LAD2',
                    'PROV_TEL2',
                    'PROV_XRFC',
                    'PROV_XTAX',
                    'PROV_TIPO',
                    'PROV_TICO',
                    'PROV_SIWE',
                    'PROV_MEPA',
                    'PROV_CALL',
                    'PROV_NUEX',
                    'PROV_NUIN',
                    'PROV_COPO',
                    'PROV_COLO',
                    'PROV_MUNI',
                    'PROV_LOCA',
                    'PROV_ENTI',
                    'PROV_PAIS',
                    'REFI_CRFI',
                    'REFI_DRFI',
                ]);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(
                true, 
                "ERR_ORDER_SHEET002: Ocurrió un error al obtener la información de la orden de compra.", 
                $th->getMessage(), 
                500
            );
        }


        try {
            $arrArtitle = DB::table('S002V01TARSE')
                ->where('ARSE_NULI', '=', $line)
                ->where('INAR_NULI', '=', $line)
                ->where('CAMO_NULI', '=', $line)
                ->where('DEAR_NULI', '=', $line)
                ->where('UNID_NULI', '=', $line)
                ->where('ARTI_NULI', '=', $line)
                ->where('FAMI_NULI', '=', $line)
                ->where('SUBF_NULI', '=', $line)
                ->where('ARSE_ESTA', '=', 'Activo')
                ->where('INAR_ESTA', '=', 'Activo')
                ->where('CAMO_ESTA', '=', 'Activo')
                ->where('DEAR_ESTA', '=', 'Activo')
                ->where('UNID_ESTA', '=', 'Activo')
                ->where('ARTI_ESTA', '=', 'Activo')
                ->where('FAMI_ESTA', '=', 'Activo')
                ->where('SUBF_ESTA', '=', 'Activo')
                ->where('ARSE_IDLI', '=', $arrOrder['LINE_IDLI'])
                ->where('ARSE_NUPR', '=', $arrOrder['PROV_NUPR'])
                ->join('S002V01TINAR','INAR_IDIN','=','ARSE_IDIN')
                ->join('S002V01TCAMO','CAMO_COMO','=','INAR_COMO')
                ->join('S002V01TDEAR','DEAR_IDDE','=','INAR_IDDE')
                ->join('S002V01TUNID','UNID_IDUN','=','DEAR_IDUN')
                ->join('S002V01TARTI','ARTI_IDAR','=','DEAR_IDAR')
                ->join('S002V01TFAMI','FAMI_COFA','=','ARTI_COFA')
                ->join('S002V01TSUBF','SUBF_COSU','=','ARTI_COSU')
                ->get([
                    'ARSE_IDAS',
                    'ARSE_IDLI',
                    // 'ARSE_CANT',
                    // 'ARSE_PRTO',
                    'INAR_IDIN',
                    'INAR_CODI',
                    'INAR_MODE',
                    'INAR_PREC',
                    'INAR_MOMI',
                    'INAR_CARA',
                    'CAMO_COMO',
                    'CAMO_DESC',
                    'CAMO_DECI',
                    'CAMO_POVA',
                    'CAMO_FEIN',
                    'CAMO_FEFI',
                    'DEAR_IDDE',
                    'DEAR_IMAG',
                    'DEAR_DESC',
                    'DEAR_CARA',
                    'DEAR_COWE',
                    'UNID_IDUN',
                    'UNID_NOMB',
                    'UNID_ACRO',
                    'ARTI_IDAR',
                    'ARTI_CODI',
                    'ARTI_NOMB',
                    'FAMI_COFA',
                    'FAMI_NOFA',
                    'SUBF_COSU',
                    'SUBF_NOSU',
                ]);
            $arrArtitle = json_decode( json_encode( $arrArtitle ), true );
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(
                true, 
                "ERR_ORDER_SHEET002: Ocurrió un error al obtener la información de la orden de compra.", 
                $th->getMessage(), 
                500
            );
        }
        
        $spreadsheet = new Spreadsheet();
        $activeWorksheet = $spreadsheet->getActiveSheet()->setTitle($arrOrder['ORCO_NUOR']);


        $headerA1 = 'Número de orden';
        $contentB1 = $arrOrder['ORCO_NUOR'];
        $activeWorksheet->setCellValue("A1", $headerA1);
        $activeWorksheet->setCellValue("B1", $contentB1);
        $activeWorksheet->getStyle( "A1" )->getFont()->setBold(true);


        $headerA2 = 'Estado de la orden';
        $contentB2 = $arrOrder['ORCO_ESTA'];
        $activeWorksheet->setCellValue("A2", $headerA2);
        $activeWorksheet->setCellValue("B2", $contentB2);
        $activeWorksheet->getStyle( "A2" )->getFont()->setBold(true);


        $headerA3 = 'Numero de línea de solicitud';
        $contentB3 = $arrOrder['LINE_IDLI'];
        $activeWorksheet->setCellValue("A3", $headerA3);
        $activeWorksheet->setCellValue("B3", $contentB3);
        $activeWorksheet->getStyle( "A3" )->getFont()->setBold(true);


        $headerA4 = '';
        if ( !is_null( $arrOrder['LINE_OTPR'] ) && is_null( $arrOrder['LINE_OTCO'] )  ) {
            $headerA4 = 'Orden de Trabajo Preventivo';
            $contentB4 = $arrOrder['LINE_OTPR'];
        } else if ( is_null( $arrOrder['LINE_OTPR'] ) && !is_null( $arrOrder['LINE_OTCO'] )  ) {
            $headerA4 = 'Orden de Trabajo Correctivo';
            $contentB4 = $arrOrder['LINE_OTCO'];
        } else if ( is_null( $arrOrder['LINE_OTPR'] ) && is_null( $arrOrder['LINE_OTCO'] )  ) {
            $headerA4 = 'Orden de Trabajo';
            $contentB4 = 'No aplica';
        } else {
            $headerA4 = 'Orden de Trabajo';
            $contentB4 = 'No aplica';
        }
        $activeWorksheet->setCellValue("A4", $headerA4 );
        $activeWorksheet->setCellValue("B4", $contentB4 );
        $activeWorksheet->getStyle( "A4" )->getFont()->setBold(true);


        $headerA5 = 'ID Despacho';
        $contentB5 = $arrOrder['DESP_IDDE'];
        $activeWorksheet->setCellValue("A5", $headerA5 );
        $activeWorksheet->setCellValue("B5", $contentB5 );
        $activeWorksheet->getStyle( "A5" )->getFont()->setBold(true);


        $headerA6 = 'Despacho';
        $contentB6 = $arrOrder['DESP_NODE'];
        $activeWorksheet->setCellValue("A6", $headerA6 );
        $activeWorksheet->setCellValue("B6", $contentB6 );
        $activeWorksheet->getStyle( "A6" )->getFont()->setBold(true);


        $headerA7 = 'Responsable del despacho';
        $contentB7 = $arrOrder['DESP_NOMB'] . ' ' . $arrOrder['DESP_APPA'] . ' ' . $arrOrder['DESP_APMA'];
        $activeWorksheet->setCellValue("A7", $headerA7 );
        $activeWorksheet->setCellValue("B7", $contentB7 );
        $activeWorksheet->getStyle( "A7" )->getFont()->setBold(true);


        $headerA8 = 'Teléfono del despacho';
        $contentB8 = $arrOrder['DESP_LADA'] . ' ' . $arrOrder['DESP_TELE'];
        $activeWorksheet->setCellValue("A8", $headerA8 );
        $activeWorksheet->setCellValue("B8", $contentB8 );
        $activeWorksheet->getStyle( "A8" )->getFont()->setBold(true);


        $headerA9 = 'Correo electrónico del despacho';
        $contentB9 = $arrOrder['DESP_CORR'];
        $activeWorksheet->setCellValue("A9", $headerA9 );
        $activeWorksheet->setCellValue("B9", $contentB9 );
        $activeWorksheet->getStyle( "A9" )->getFont()->setBold(true);


        $headerA10 = 'Calle del despacho';
        $contentB10 = $arrOrder['DESP_CALL'];
        $activeWorksheet->setCellValue("A10", $headerA10 );
        $activeWorksheet->setCellValue("B10", $contentB10 );
        $activeWorksheet->getStyle( "A10" )->getFont()->setBold(true);

        
        $headerA11 = 'Número exterior';
        $contentB11 = $arrOrder['DESP_NUEX'];
        $activeWorksheet->setCellValue("A11", $headerA11 );
        $activeWorksheet->setCellValue("B11", $contentB11 );
        $activeWorksheet->getStyle( "A11" )->getFont()->setBold(true);


        $headerA12 = 'Número interior';
        if ( !is_null($arrOrder['DESP_NUIN']) ) {
            $contentB12 = $arrOrder['DESP_NUIN'];
        } else {
            $contentB12 = 'No aplica';
        }
        $activeWorksheet->setCellValue("A12", $headerA12 );
        $activeWorksheet->setCellValue("B12", $contentB12 );
        $activeWorksheet->getStyle( "A12" )->getFont()->setBold(true);


        $headerA13 = 'Código postal';
        $contentB13 = $arrOrder['DESP_COPO'];
        $activeWorksheet->setCellValue("A13", $headerA13 );
        $activeWorksheet->setCellValue("B13", $contentB13 );
        $activeWorksheet->getStyle( "A13" )->getFont()->setBold(true);

        
        $headerA14 = 'Colonia';
        $contentB14 = $arrOrder['DESP_COLO'];
        $activeWorksheet->setCellValue("A14", $headerA14 );
        $activeWorksheet->setCellValue("B14", $contentB14 );
        $activeWorksheet->getStyle( "A14" )->getFont()->setBold(true);


        $headerA15 = 'Localidad';
        if ( !is_null($arrOrder['DESP_LOCA']) && !empty($arrOrder['DESP_LOCA']) ) {
            $contentB15 = $arrOrder['DESP_LOCA'];
        } else {
            $contentB15 = 'No aplica';
        }
        $activeWorksheet->setCellValue("A15", $headerA15 );
        $activeWorksheet->setCellValue("B15", $contentB15 );
        $activeWorksheet->getStyle( "A15" )->getFont()->setBold(true);


        $headerA16 = 'Municipio';
        $contentB16 = $arrOrder['DESP_MUNI'];
        $activeWorksheet->setCellValue("A16", $headerA16 );
        $activeWorksheet->setCellValue("B16", $contentB16 );
        $activeWorksheet->getStyle( "A16" )->getFont()->setBold(true);


        $headerA17 = 'Entidad Federativa';
        $contentB17 = $arrOrder['DESP_ENTI'];
        $activeWorksheet->setCellValue("A17", $headerA17 );
        $activeWorksheet->setCellValue("B17", $contentB17 );
        $activeWorksheet->getStyle( "A17" )->getFont()->setBold(true);


        $headerA18 = 'País';
        $contentB18 = $arrOrder['DESP_PAIS'];
        $activeWorksheet->setCellValue("A18", $headerA18 );
        $activeWorksheet->setCellValue("B18", $contentB18 );
        $activeWorksheet->getStyle( "A18" )->getFont()->setBold(true);


        $headerA19 = 'Número de proveedor';
        $contentB19 = $arrOrder['PROV_NUPR'];
        $activeWorksheet->setCellValue("A19", $headerA19 );
        $activeWorksheet->setCellValue("B19", $contentB19 );
        $activeWorksheet->getStyle( "A19" )->getFont()->setBold(true);


        $headerA20 = 'Número de subcontratista';
        $contentB20 = $arrOrder['PROV_IDPS'];
        $activeWorksheet->setCellValue("A20", $headerA20 );
        $activeWorksheet->setCellValue("B20", $contentB20 );
        $activeWorksheet->getStyle( "A20" )->getFont()->setBold(true);


        $headerA21 = 'Nombre comercial del proveedor';
        $contentB21 = $arrOrder['PROV_NOCO'];
        $activeWorksheet->setCellValue("A21", $headerA21 );
        $activeWorksheet->setCellValue("B21", $contentB21 );
        $activeWorksheet->getStyle( "A21" )->getFont()->setBold(true);


        $headerA22 = 'Referencia fiscal del proveedor';
        $contentB22 = $arrOrder['REFI_DRFI'] . ' (' . $arrOrder['REFI_CRFI'] . ')';
        $activeWorksheet->setCellValue("A22", $headerA22 );
        $activeWorksheet->setCellValue("B22", $contentB22 );
        $activeWorksheet->getStyle( "A22" )->getFont()->setBold(true);


        $headerA23 = 'Responsable del proveedor';
        $contentB23 = $arrOrder['PROV_NOMB'] . ' ' . $arrOrder['PROV_APPA'] . ' ' . $arrOrder['PROV_APMA'];
        $activeWorksheet->setCellValue("A23", $headerA23 );
        $activeWorksheet->setCellValue("B23", $contentB23 );
        $activeWorksheet->getStyle( "A23" )->getFont()->setBold(true);


        $headerA24 = 'Correo electrónico del proveedor';
        $contentB24 = $arrOrder['PROV_CORR'];
        $activeWorksheet->setCellValue("A24", $headerA24 );
        $activeWorksheet->setCellValue("B24", $contentB24 );
        $activeWorksheet->getStyle( "A24" )->getFont()->setBold(true);


        $headerA25 = 'Teléfono del proveedor';
        $contentB25 = $arrOrder['PROV_LAD1'] . ' ' . $arrOrder['PROV_TEL1'];
        $activeWorksheet->setCellValue("A25", $headerA25 );
        $activeWorksheet->setCellValue("B25", $contentB25 );
        $activeWorksheet->getStyle( "A25" )->getFont()->setBold(true);


        $headerA26 = '';
        $contentB26 = '';
        if ( !is_null( $arrOrder['PROV_XRFC'] ) && is_null( $arrOrder['PROV_XRFC'] )) {
            $headerA26 = 'R.F.C. del proveedor';
            $contentB26 = $arrOrder['PROV_XRFC'];
        } else if ( is_null( $arrOrder['PROV_XRFC'] ) && !is_null( $arrOrder['PROV_XRFC'] )) {
            $headerA26 = 'TAX ID. del proveedor';
            $contentB26 = $arrOrder['PROV_XTAX'];
        } else {
            $headerA26 = 'R.F.C. / TAX ID';
            $contentB26 = 'No aplica';
        }
        $activeWorksheet->setCellValue("A26", $headerA26 );
        $activeWorksheet->setCellValue("B26", $contentB26 );
        $activeWorksheet->getStyle( "A26" )->getFont()->setBold(true);

        
        $activeWorksheet->getColumnDimension("A")->setAutoSize(true);
        $activeWorksheet->getColumnDimension("B")->setAutoSize(true);


        $arrAlphabet = $this->resourcesController->arrAlphabet;


        $spreadsheet->createSheet();
        $spreadsheet->setActiveSheetIndex(1);
        $activeWorksheetArtitle = $spreadsheet->getActiveSheet()->setTitle('Artículos de la orden');
        $arrHeaderArtitle = array(
            /* A */ 'ID Artículo',
            /* B */ 'Código del artíulo',
            /* C */ 'Artículo',
            /* D */ 'Familia',
            /* E */ 'Subfamilia',
            /* F */ 'Descripción',
            /* G */ 'Características',
            /* H */ 'Unidad',
            /* I */ 'Código',
            /* J */ 'Modelo',
            /* K */ 'Precio Unitario',
            // /* L */ 'Cantidad',
            // /* M */ 'Precio Total',
            /* N */ 'No. de selección',
        );
        foreach ($arrArtitle as $key => $artitle) {
            $key = $key + 2;

            $activeWorksheetArtitle->setCellValue("A".$key, $artitle['ARTI_IDAR']);
            $activeWorksheetArtitle->setCellValue("B".$key, $artitle['ARTI_CODI']);
            $activeWorksheetArtitle->setCellValue("C".$key, $artitle['ARTI_NOMB']);
            $activeWorksheetArtitle->setCellValue("D".$key, $artitle['FAMI_NOFA'] . ' (' . $artitle['FAMI_COFA'] . ')');
            $activeWorksheetArtitle->setCellValue("E".$key, $artitle['SUBF_NOSU'] . ' (' . $artitle['SUBF_COSU'] . ')');
            $activeWorksheetArtitle->setCellValue("F".$key, $artitle['DEAR_DESC']);
            $activeWorksheetArtitle->setCellValue("G".$key, $artitle['DEAR_CARA']);
            $activeWorksheetArtitle->setCellValue("H".$key, $artitle['UNID_NOMB'] . ' (' . $artitle['UNID_IDUN'] . ')');
            $activeWorksheetArtitle->setCellValue("I".$key, $artitle['INAR_CODI']);
            $activeWorksheetArtitle->setCellValue("J".$key, $artitle['INAR_MODE']);
            $activeWorksheetArtitle->setCellValue("K".$key, '$'. $artitle['INAR_PREC'] . ' ' . $artitle['CAMO_COMO'] );
            // $activeWorksheetArtitle->setCellValue("L".$key, $artitle['ARSE_CANT']);
            // $activeWorksheetArtitle->setCellValue("M".$key, '$'. $artitle['ARSE_PRTO'] . ' ' . $artitle['CAMO_COMO'] );
            $activeWorksheetArtitle->setCellValue("N".$key, $artitle['ARSE_IDAS']);
        }
        foreach ($arrHeaderArtitle as $keyHeaderArtitle => $headerArtitle) {
            $activeWorksheetArtitle->setCellValue( $arrAlphabet[$keyHeaderArtitle]."1", $headerArtitle);
            $activeWorksheetArtitle->getColumnDimension( $arrAlphabet[$keyHeaderArtitle] )->setAutoSize(true);
            $activeWorksheetArtitle->getStyle( $arrAlphabet[$keyHeaderArtitle]."1" )->getFont()->setBold(true);
        }



        $nuli = $this->resourcesController->formatSecuence($line, 2);
        $como = 'GEAD';         // Código del módulo
        $cldo = 'IN';           // Código de la clasificación
        $fecr = date('ymd');    // Fecha en la se carga el archivo

        try {
            $arrSecuence = (array) DB::table('S002V01TAFAL')
                ->where('AFAL_COMO', '=', $como)
                ->where('AFAL_CLDO', '=', $cldo)
                ->where('AFAL_NULI', '=', $line)
                ->orderBy('AFAL_NUSE', 'desc')
                ->first([ 'AFAL_NUSE' ]);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(
                true, 
                "ERR_PROVIDER_SHEET020: Ocurrió un error al obtener la información de la secuencia.", 
                $th->getMessage(), 
                500
            );
        }
        $nuse = 1;              // Secuencia del documento
        if ( !empty( $arrSecuence ) && !is_null( $arrSecuence ) ) {
            $nuse = intval( $arrSecuence['AFAL_NUSE'] ) + 1; 
        }
        $nuse = $this->resourcesController->formatSecuence($nuse, 6);
        $nuve = $this->resourcesController->formatSecuence('1', 2);
        $noar = 'ficha_de_adquisición_' . $arrOrder['ORCO_NUOR'];
        $exte = 'xlsx';

        if ($_SERVER['SERVER_NAME'] === '192.168.100.105') {
            $filePath = 'C:/ITTEC/SAM/Dev/SistemaMantenimiento/sistema-mantenimiento-back/public/public_files/';    // API JEAN
        } else {
            $filePath = 'C:\inetpub\wwwroot\sam\public_files\\';     // API QA
        }

        $fileName = $nuli.'-'.$como.'-'.$cldo.'-'.$fecr.'-'.$nuse.'='.$nuve.'='.$noar.'.'.$exte;

        $tempFile = $filePath.$fileName;

        if ( file_exists( $tempFile ) ) {
            if ( !unlink( $tempFile ) ) {
                return $this->responseController->makeResponse(
                    true, 
                    "ERR_PROVIDER_SHEET021: Ocurrió un error al eliminar el siguiente archivo: " . $tempFile, 
                    [], 
                    500
                );
            }
        }
        
        try {
            $writer = new Xlsx($spreadsheet);
            ob_start();
            $writer->save('php://output');
            $base64 = base64_encode(ob_get_clean());
            $validate = \File::put( $tempFile, base64_decode($base64));
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(
                true, 
                "ERR_PROVIDER_SHEET022: Ocurrió un error al guardar el documento.", 
                $th->getMessage(), 
                500
            );
        }


        $ubic = Storage::putFile('files', new File($tempFile));
        $ubic = str_replace("/", "\\", $ubic);
        if ($_SERVER['SERVER_NAME'] === '192.168.100.105') {
            $ubic = "C:\ITTEC\SAM\Dev\SistemaMantenimiento\sistema-mantenimiento-back\storage\app\\" . $ubic;
        } else {
            $ubic = "C:\inetpub\wwwroot\sam\storage\app\\" . $ubic;
        }
        $tama = filesize($ubic);
        $usac = json_encode([$user]);


        $now = $this->functionsController->now();
        $currentDate = $now->toDateTimeString();

        try {
            $validateInsert = DB::table('S002V01TAFAL')->insert([
                'AFAL_NULI' => $line,
                'AFAL_COMO' => $como,
                'AFAL_CLDO' => $cldo,
                'AFAL_FECR' => $fecr,
                'AFAL_NUSE' => $nuse,
                'AFAL_NUVE' => $nuve,
                'AFAL_NOAR' => $noar,
                'AFAL_EXTE' => $exte,
                'AFAL_TAMA' => $tama,
                'AFAL_UBIC' => $ubic,
                'AFAL_USAC' => $usac,
                'AFAL_USRE' => $user,
                'AFAL_FERE' => $currentDate,
            ]);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(
                true, 
                "ERR_PROVIDER_SHEET023: Ocurrió un error guardar los datos a la tabla final de archivos.", 
                $th->getMessage(), 
                500
            );
        }

        if ( !$validateInsert ) {
            return $this->responseController->makeResponse(
                true, 
                "ERR_PROVIDER_SHEET024: No se pudo guardar la ficha del proveedor en la base de datos.", 
                [], 
                500
            );
        }
        
        if ($_SERVER['SERVER_NAME'] === '192.168.100.105') {
            $urlPublic = 'http://192.168.100.105:8000/public_files/' . $fileName;
        } else {
            $urlPublic = $this->functionsController->getApiURI().'sam/public_files/' . $fileName;
        }

        return $this->responseController->makeResponse(false, "EXITO: Modificación Exitosa", [ 'url' => $urlPublic ]);
    }
    public function generateSheetInvoicePDF( $orderNumber, $user, $line ) {
        try {
            $idOrder = $this->encController->decrypt($orderNumber);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(
                true, 
                "ERR_ORDER_SHEET000: Ocurrió un error al obtener el número del proveedor.", 
                $th->getMessage(), 
                500
            );
        }

        try {
            $user = $this->encController->decrypt($user);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(
                true, 
                "ERR_ORDER_SHEET001: Ocurrió un error al obtener el usuario.", 
                $th->getMessage(), 
                500
            );
        }

        try {
            $arrOrder = (array) DB::table('S002V01TORCO')
                ->where('ORCO_NUOR', '=', $idOrder)
                ->where('ORCO_NULI', '=', $line)
                ->where('LINE_NULI', '=', $line)
                ->where('DESP_NULI', '=', $line)
                ->where('PROV_NULI', '=', $line)
                ->where('DESP_ESTA', '=', 'Activo')
                ->where('PROV_ESTA', '=', 'Activo')
                ->join('S002V01TLINE', 'LINE_IDLI', '=', 'ORCO_IDLI')
                ->join('S002V01TDESP', 'DESP_IDDE', '=', 'ORCO_IDDE')
                ->join('S002V01TPROV', 'PROV_NUPR', '=', 'LINE_NUPR')
                ->join('S002V01TREFI', 'REFI_CRFI', '=', 'PROV_CRFI')
                ->first([
                    'ORCO_NUOR',
                    'ORCO_ESTA',
                    'LINE_IDLI',
                    'LINE_OTPR',
                    'LINE_OTCO',
                    'LINE_ESTA',
                    'DESP_IDDE',
                    'DESP_NODE',
                    'DESP_NOMB',
                    'DESP_APPA',
                    'DESP_APMA',
                    'DESP_LADA',
                    'DESP_TELE',
                    'DESP_CORR',
                    'DESP_CALL',
                    'DESP_NUEX',
                    'DESP_NUIN',
                    'DESP_COPO',
                    'DESP_COLO',
                    'DESP_LOCA',
                    'DESP_MUNI',
                    'DESP_ENTI',
                    'DESP_PAIS',
                    'DESP_COME',
                    'PROV_NUPR',
                    'PROV_IDPS',
                    'PROV_NOCO',
                    'PROV_NOMB',
                    'PROV_APPA',
                    'PROV_APMA',
                    'PROV_CORR',
                    'PROV_LAD1',
                    'PROV_TEL1',
                    'PROV_LAD2',
                    'PROV_TEL2',
                    'PROV_XRFC',
                    'PROV_XTAX',
                    'PROV_TIPO',
                    'PROV_TICO',
                    'PROV_SIWE',
                    'PROV_MEPA',
                    'PROV_CALL',
                    'PROV_NUEX',
                    'PROV_NUIN',
                    'PROV_COPO',
                    'PROV_COLO',
                    'PROV_MUNI',
                    'PROV_LOCA',
                    'PROV_ENTI',
                    'PROV_PAIS',
                    'REFI_CRFI',
                    'REFI_DRFI',
                ]);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(
                true, 
                "ERR_ORDER_SHEET002: Ocurrió un error al obtener la información de la orden de compra.", 
                $th->getMessage(), 
                500
            );
        }


        try {
            $arrArtitle = DB::table('S002V01TARSE')
                ->where('ARSE_NULI', '=', $line)
                ->where('INAR_NULI', '=', $line)
                ->where('CAMO_NULI', '=', $line)
                ->where('DEAR_NULI', '=', $line)
                ->where('UNID_NULI', '=', $line)
                ->where('ARTI_NULI', '=', $line)
                ->where('FAMI_NULI', '=', $line)
                ->where('SUBF_NULI', '=', $line)
                ->where('ARSE_ESTA', '=', 'Activo')
                ->where('INAR_ESTA', '=', 'Activo')
                ->where('CAMO_ESTA', '=', 'Activo')
                ->where('DEAR_ESTA', '=', 'Activo')
                ->where('UNID_ESTA', '=', 'Activo')
                ->where('ARTI_ESTA', '=', 'Activo')
                ->where('FAMI_ESTA', '=', 'Activo')
                ->where('SUBF_ESTA', '=', 'Activo')
                ->where('ARSE_IDLI', '=', $arrOrder['LINE_IDLI'])
                ->where('ARSE_NUPR', '=', $arrOrder['PROV_NUPR'])
                ->join('S002V01TINAR','INAR_IDIN','=','ARSE_IDIN')
                ->join('S002V01TCAMO','CAMO_COMO','=','INAR_COMO')
                ->join('S002V01TDEAR','DEAR_IDDE','=','INAR_IDDE')
                ->join('S002V01TUNID','UNID_IDUN','=','DEAR_IDUN')
                ->join('S002V01TARTI','ARTI_IDAR','=','DEAR_IDAR')
                ->join('S002V01TFAMI','FAMI_COFA','=','ARTI_COFA')
                ->join('S002V01TSUBF','SUBF_COSU','=','ARTI_COSU')
                ->get([
                    'ARSE_IDAS',
                    'ARSE_IDLI',
                    'ARSE_CANT',
                    'ARSE_PRTO',
                    'INAR_IDIN',
                    'INAR_CODI',
                    'INAR_MODE',
                    'INAR_PREC',
                    'INAR_MOMI',
                    'INAR_CARA',
                    'CAMO_COMO',
                    'CAMO_DESC',
                    'CAMO_DECI',
                    'CAMO_POVA',
                    'CAMO_FEIN',
                    'CAMO_FEFI',
                    'DEAR_IDDE',
                    'DEAR_IMAG',
                    'DEAR_DESC',
                    'DEAR_CARA',
                    'DEAR_COWE',
                    'UNID_IDUN',
                    'UNID_NOMB',
                    'UNID_ACRO',
                    'ARTI_IDAR',
                    'ARTI_CODI',
                    'ARTI_NOMB',
                    'FAMI_COFA',
                    'FAMI_NOFA',
                    'SUBF_COSU',
                    'SUBF_NOSU',
                ]);
            $arrArtitle = json_decode( json_encode( $arrArtitle ), true );
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(
                true, 
                "ERR_ORDER_SHEET002: Ocurrió un error al obtener la información de la orden de compra.", 
                $th->getMessage(), 
                500
            );
        }

        $html = '<!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Document</title>
            <style>
                body {
                    font-family: Arial, Helvetica, sans-serif;
                    font-size: 8pt;
                }
                .section-title { 
                    margin: 20px 0;
                    font-size: 12pt;
                }

                table {
                    width: 100%;
                    font-size: 8pt;
                }

                thead tr th {
                    text-align: start;
                    padding: 0 16px;
                    height: 52px;
                    border-bottom-width: 1px;
                    border-bottom-style: solid;
                    border-bottom-color: #CCC;
                }

                tbody tr td {
                    padding: 0 16px;
                    height: 52px;
                    border-bottom-width: 1px;
                    border-bottom-style: solid;
                    border-bottom-color: #CCC;
                }

                p {
                    text-align: justify;
                }

            </style>
        </head>
        <body>
            <div class="item">
                <b>Número de Orden de Compra: </b>
                <span>'.$arrOrder['ORCO_NUOR'].'</span>
            </div>
            <div class="item">
                <b>Estado de la orden: </b>
                <span>'.$arrOrder['ORCO_ESTA'].'</span>
            </div>
            <div class="item">
                <b>Numero de línea de solicitud: </b>
                <span>'.$arrOrder['LINE_IDLI'].'</span>
            </div>
        ';

        if ( !is_null( $arrOrder['LINE_OTPR'] ) && is_null( $arrOrder['LINE_OTCO'] )  ) {
            $html.='<div class="item">
                        <b>Orden de Trabajo Preventivo: </b>
                        <span>'.$arrOrder['LINE_OTPR'].'</span>
                    </div>';
        } else if ( is_null( $arrOrder['LINE_OTPR'] ) && !is_null( $arrOrder['LINE_OTCO'] )  ) {
            $html.='<div class="item">
                        <b>Orden de Trabajo Correctivo: </b>
                        <span>'.$arrOrder['LINE_OTCO'].'</span>
                    </div>';
        } else if ( is_null( $arrOrder['LINE_OTPR'] ) && is_null( $arrOrder['LINE_OTCO'] )  ) {
            $html.='<div class="item">
                        <b>Orden de Trabajo: </b>
                        <span>No aplica</span>
                    </div>';
        } else {
            $html.='<div class="item">
                        <b>Orden de Trabajo: </b>
                        <span>No aplica</span>
                    </div>';
        }

        $html.='<div class="item">
                    <b>ID Despacho: </b>
                    <span>'.$arrOrder['DESP_IDDE'].'</span>
                </div>
                <div class="item">
                    <b>Despacho: </b>
                    <span>'.$arrOrder['DESP_NODE'].'</span>
                </div>
                <div class="item">
                    <b>Responsable del despacho: </b>
                    <span>'.$arrOrder['DESP_NOMB'] . ' ' . $arrOrder['DESP_APPA'] . ' ' . $arrOrder['DESP_APMA'].'</span>
                </div>
                <div class="item">
                    <b>Teléfono del despacho: </b>
                    <span>'.$arrOrder['DESP_LADA'] . ' ' . $arrOrder['DESP_TELE'].'</span>
                </div>
                <div class="item">
                    <b>Correo electrónico del despacho: </b>
                    <span>'.$arrOrder['DESP_CORR'].'</span>
                </div>
                <div class="item">
                    <b>Calle del despacho: </b>
                    <span>'.$arrOrder['DESP_CALL'].'</span>
                </div>
                <div class="item">
                    <b>Número exterior: </b>
                    <span>'.$arrOrder['DESP_NUEX'].'</span>
                </div>
        ';
        if ( !is_null($arrOrder['DESP_NUIN']) ) {
            $html.='<div class="item">
                        <b>Número interior: </b>
                        <span>'.$arrOrder['DESP_NUIN'].'</span>
                    </div>';
        } else {
            $html.='<div class="item">
                        <b>Número interior: </b>
                        <span>No aplica</span>
                    </div>';
        }

        $html.='<div class="item">
                    <b>Código postal: </b>
                    <span>'.$arrOrder['DESP_COPO'].'</span>
                </div>
                <div class="item">
                    <b>Colonia: </b>
                    <span>'.$arrOrder['DESP_COLO'].'</span>
                </div>
        ';


        if ( !is_null($arrOrder['DESP_LOCA']) && !empty($arrOrder['DESP_LOCA']) ) {
            $html.='<div class="item">
                        <b>Localidad: </b>
                        <span>'.$arrOrder['DESP_LOCA'].'</span>
                    </div>';
        } else {
            $html.='<div class="item">
                        <b>Localidad: </b>
                        <span>No aplica</span>
                    </div>';
        }

        $html.='<div class="item">
                    <b>Municipio: </b>
                    <span>'.$arrOrder['DESP_MUNI'].'</span>
                </div>
                <div class="item">
                    <b>Entidad Federativa: </b>
                    <span>'.$arrOrder['DESP_ENTI'].'</span>
                </div>
                <div class="item">
                    <b>País: </b>
                    <span>'.$arrOrder['DESP_PAIS'].'</span>
                </div>
                <div class="item">
                    <b>Número de proveedor: </b>
                    <span>'.$arrOrder['PROV_NUPR'].'</span>
                </div>
                <div class="item">
                    <b>Número de subcontratista: </b>
                    <span>'.$arrOrder['PROV_IDPS'].'</span>
                </div>
                <div class="item">
                    <b>Nombre comercial del proveedor: </b>
                    <span>'.$arrOrder['PROV_NOCO'].'</span>
                </div>
                <div class="item">
                    <b>Referencia fiscal del proveedor: </b>
                    <span>'.$arrOrder['REFI_DRFI'] . ' (' . $arrOrder['REFI_CRFI'] . ')'.'</span>
                </div>
                <div class="item">
                    <b>Responsable del proveedor: </b>
                    <span>'.$arrOrder['PROV_NOMB'] . ' ' . $arrOrder['PROV_APPA'] . ' ' . $arrOrder['PROV_APMA'].'</span>
                </div>
                <div class="item">
                    <b>Correo electrónico del proveedor: </b>
                    <span>'.$arrOrder['PROV_CORR'].'</span>
                </div>
                <div class="item">
                    <b>Teléfono del proveedor: </b>
                    <span>'.$arrOrder['PROV_LAD1'] . ' ' . $arrOrder['PROV_TEL1'].'</span>
                </div>
        ';

        if ( !is_null( $arrOrder['PROV_XRFC'] ) && is_null( $arrOrder['PROV_XRFC'] )) {
            $html.='<div class="item">
                        <b>R.F.C. del proveedor: </b>
                        <span>'.$arrOrder['PROV_XRFC'].'</span>
                    </div>';
        } else if ( is_null( $arrOrder['PROV_XRFC'] ) && !is_null( $arrOrder['PROV_XRFC'] )) {
            $html.='<div class="item">
                        <b>TAX ID. del proveedor: </b>
                        <span>'.$arrOrder['PROV_XTAX'].'</span>
                    </div>';            
        } else {
            $html.='<div class="item">
                        <b>R.F.C. / TAX ID: </b>
                        <span>No aplica</span>
                    </div>';
        }


        if ( !empty($arrArtitle) ) {
            $html.='
                    <div style="page-break-after:always;"></div>

                    <div class="section-title">
                        <b>Artículos</b>
                    </div>';
            $html.='<table cellspacing="0" cellpadding="0">
                        <thead>
                            <tr>
                                <th>ID Artículo</th>
                                <th>Código del artíulo</th>
                                <th>Artículo</th>
                                <th>Familia</th>
                                <th>Subfamilia</th>
                                <!-- <th>Descripción</th> -->
                                <!-- <th>Características</th> -->
                                <th>Unidad</th>
                                <th>Código</th>
                                <th>Modelo</th>
                                <th>Precio Unitario</th>
                                <th>Cantidad</th>
                                <th>Precio Total</th>
                                <th>No. de selección</th>
                            </tr>
                        </thead>
                        <tbody>';
            foreach ($arrArtitle as $keyArtitle => $artitle) {
                $html.=    '<tr>
                                <td>'.$artitle['ARTI_IDAR'].'</td>
                                <td>'.$artitle['ARTI_CODI'].'</td>
                                <td>'.$artitle['ARTI_NOMB'].'</td>
                                <td>'.$artitle['FAMI_NOFA'] . ' (' . $artitle['FAMI_COFA'] . ')'.'</td>
                                <td>'.$artitle['SUBF_NOSU'] . ' (' . $artitle['SUBF_COSU'] . ')'.'</td>
                                <!-- <td>'.$artitle['DEAR_DESC'].'</td> -->
                                <!-- <td>'.$artitle['DEAR_CARA'].'</td> -->
                                <td>'.$artitle['UNID_NOMB'] . ' (' . $artitle['UNID_IDUN'] . ')'.'</td>
                                <td>'.$artitle['INAR_CODI'].'</td>
                                <td>'.$artitle['INAR_MODE'].'</td>
                                <td>'.'$'. $artitle['INAR_PREC'] . ' ' . $artitle['CAMO_COMO'] .'</td>
                                <td>'.$artitle['ARSE_CANT'].'</td>
                                <!-- <td>'.'$'. $artitle['ARSE_PRTO'] . ' ' . $artitle['CAMO_COMO'] .'</td> -->
                                <td>'.$artitle['ARSE_IDAS'].'</td>
                            </tr>';
            }
            $html.=    '</tbody>
                    </table>';
        }


        $html.='</body></html>';

        // return $html;
        

        $nuli = $this->resourcesController->formatSecuence($line, 2);
        $como = 'GEAD';         // Código del módulo
        $cldo = 'IN';           // Código de la clasificación
        $fecr = date('ymd');    // Fecha en la se carga el archivo

        try {
            $arrSecuence = (array) DB::table('S002V01TAFAL')
                ->where('AFAL_COMO', '=', $como)
                ->where('AFAL_CLDO', '=', $cldo)
                ->where('AFAL_NULI', '=', $line)
                ->orderBy('AFAL_NUSE', 'desc')
                ->first([ 'AFAL_NUSE' ]);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(
                true, 
                "ERR_PROVIDER_SHEET020: Ocurrió un error al obtener la información de la secuencia.", 
                $th->getMessage(), 
                500
            );
        }
        $nuse = 1;              // Secuencia del documento
        if ( !empty( $arrSecuence ) && !is_null( $arrSecuence ) ) {
            $nuse = intval( $arrSecuence['AFAL_NUSE'] ) + 1; 
        }
        $nuse = $this->resourcesController->formatSecuence($nuse, 6);
        $nuve = $this->resourcesController->formatSecuence('1', 2);
        $noar = 'ficha_de_adquisición_' . $arrOrder['ORCO_NUOR'];

        $nuli = $this->resourcesController->formatSecuence($line, 2);
        $como = 'GEAD';         // Código del módulo
        $cldo = 'IN';           // Código de la clasificación
        $fecr = date('ymd');    // Fecha en la se carga el archivo
        try {
            $arrSecuence = (array) DB::table('S002V01TAFAL')
                ->where('AFAL_COMO', '=', $como)
                ->where('AFAL_CLDO', '=', $cldo)
                ->where('AFAL_NULI', '=', $line)
                ->orderBy('AFAL_NUSE', 'desc')
                ->first([ 'AFAL_NUSE' ]);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(
                true, 
                "ERR_PROVIDER_SHEET020: Ocurrió un error al obtener la información de la secuencia.", 
                $th->getMessage(), 
                500
            );
        }
        $nuse = 1;              // Secuencia del documento
        if ( !empty( $arrSecuence ) && !is_null( $arrSecuence ) ) {
            $nuse = intval( $arrSecuence['AFAL_NUSE'] ) + 1; 
        }
        $nuse = $this->resourcesController->formatSecuence($nuse, 6);
        $nuve = $this->resourcesController->formatSecuence('1', 2);
        $noar = 'ficha_de_adquisición_' . $arrOrder['ORCO_NUOR'];
        $exte = 'pdf';        
        
        
        if ($_SERVER['SERVER_NAME'] === '192.168.100.105') {
            $filePath = 'C:/ITTEC/SAM/Dev/SistemaMantenimiento/sistema-mantenimiento-back/public/public_files/';    // API JEAN
        } else {
            $filePath = 'C:\inetpub\wwwroot\sam\public_files\\';     // API QA
        }

        $fileName = $nuli.'-'.$como.'-'.$cldo.'-'.$fecr.'-'.$nuse.'='.$nuve.'='.$noar.'.'.$exte;
        
        $tempFile = $filePath . $fileName;

        $dompdf = new Dompdf();
        $dompdf ->loadHtml($html);
        $dompdf->setPaper('A4', 'landscape');
        $dompdf->render();


        $output = $dompdf->output();
        file_put_contents($tempFile, $output);
        $ubic = Storage::putFile('files', new File($tempFile));

        $ubic = str_replace("/", "\\", $ubic);
        if ($_SERVER['SERVER_NAME'] === '192.168.100.105') {
            $ubic = "C:\ITTEC\SAM\Dev\SistemaMantenimiento\sistema-mantenimiento-back\storage\app\\" . $ubic;
        } else {
            $ubic = "C:\inetpub\wwwroot\sam\storage\app\\" . $ubic;
        }
        $tama = filesize($ubic);
        $usac = json_encode([$user]);

        $now = $this->functionsController->now();
        $currentDate = $now->toDateTimeString();

        try {
            $validateInsert = DB::table('S002V01TAFAL')->insert([
                'AFAL_NULI' => $line,
                'AFAL_COMO' => $como,
                'AFAL_CLDO' => $cldo,
                'AFAL_FECR' => $fecr,
                'AFAL_NUSE' => $nuse,
                'AFAL_NUVE' => $nuve,
                'AFAL_NOAR' => $noar,
                'AFAL_EXTE' => $exte,
                'AFAL_TAMA' => $tama,
                'AFAL_UBIC' => $ubic,
                'AFAL_USAC' => $usac,
                'AFAL_USRE' => $user,
                'AFAL_FERE' => $currentDate,
            ]);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(
                true, 
                "ERR_PROVIDER_SHEET023: Ocurrió un error guardar los datos a la tabla final de archivos.", 
                $th->getMessage(), 
                500
            );
        }

        if ( !$validateInsert ) {
            return $this->responseController->makeResponse(
                true, 
                "ERR_PROVIDER_SHEET024: No se pudo guardar la ficha del proveedor en la base de datos.", 
                [], 
                500
            );
        }

        if ($_SERVER['SERVER_NAME'] === '192.168.100.105') {
            $urlPublic = 'http://192.168.100.105:8000/public_files/' . $fileName;
        } else {
            $urlPublic = $this->functionsController->getApiURI().'sam/public_files/' . $fileName;
        }

        return $this->responseController->makeResponse(false, "EXITO: Modificación Exitosa", [ 'url' => $urlPublic ]);
    }

    public function compareInvoice(Request $request) {
        $validator = Validator::make($request->all(), [
            'IDARCHIVOPDF' => 'required|string',
            'IDARCHIVOXML' => 'required|string',
            'TYPE_INVOICE' => 'required|string',
            // 'DESCRIPTION' => '',
            // 'ID_DOCUMENT' => 'required|string',
            'USER' => 'required|string',
            'LINE_NUMBER' => 'required|string',
            'REQUEST_LINE' => 'required|string',
        ]);
        if ($validator->fails()) {
            return $this->responseController->makeResponse(
                true,
                "ERR_INVOICE_COMPARE000: Se encontraron uno o más errores.",
                $this->responseController->makeErrors($validator->errors()->messages()),
                401
            );
        }

        $responseData = $request->all();
        DB::beginTransaction();

        try {
            $idArchivoPDF = $this->encController->decrypt($responseData['IDARCHIVOPDF']);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_INVOICE_COMPARE001: Ocurrió un error al recuperar el archivo PDF.", $th->getMessage(), 500);
        }
        try {
            $idArchivoXML = $this->encController->decrypt($responseData['IDARCHIVOXML']);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_INVOICE_COMPARE002: Ocurrió un error al recuperar el archivo XML.", $th->getMessage(), 500);
        }
        try {
            $user = $this->encController->decrypt($responseData['USER']);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_INVOICE_COMPARE003: Ocurrió un error al recuperar el usuario.", $th->getMessage(), 500);
        }

        try {
            $fileTempDataXML = DB::table('S002V01TARTE')
                ->where('ARTE_NULI', '=', $responseData['LINE_NUMBER'])
                ->where('ARTE_IDAR', '=', $idArchivoXML)
                ->where('ARTE_ESTA', '=', 'Activo')
                ->first([
                    'ARTE_IDAR',
                    'ARTE_NULI',
                    'ARTE_NOAR',
                    'ARTE_EXTE',
                    'ARTE_TAMA',
                    'ARTE_UBTE',
                    'ARTE_ESTA',
                    'ARTE_USRE',
                    'ARTE_FERE',
                    'ARTE_USMO',
                    'ARTE_FEMO',
                    'ARTE_FEAR',
                ]);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true,"ERR_INVOICE_COMPARE004: Ocurrió un error al obtener la información de la base de datos del documento.",$th->getMessage(),500);
        }

        if (is_null($fileTempDataXML)) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_INVOICE_COMPARE005: No se pudo obtener la información del documento.", [], 401);
        }
        if($fileTempDataXML->ARTE_ESTA == 'Eliminado'){
            return $this->responseController->makeResponse(true, 'ERR_INVOICE_COMPARE006: El archivo consultado está eliminado', [], 404);
        }

        if ( !file_exists($fileTempDataXML->ARTE_UBTE) ) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_INVOICE_COMPARE007: No se pudo obtener el documento.", [], 401);
        }

        try {
            $arrLineRequestData = DB::table('S002V01TLINE')
                ->where('LINE_NULI', '=', $responseData['LINE_NUMBER'])
                ->where('LINE_IDLI', '=', $responseData['REQUEST_LINE'])
                // ->where('LINE_ESTA', '=', 'En espera')
                ->where('ARSE_ESTA', '=', 'Activo')
                ->where('ARSE_NULI', '=', $responseData['LINE_NUMBER'])
                ->join('S002V01TARSE', 'ARSE_IDLI','=', 'LINE_IDLI')
                ->join('S002V01TINAR', 'INAR_IDIN','=', 'ARSE_IDIN')
                ->join('S002V01TCAMO', 'CAMO_COMO','=', 'INAR_COMO')
                ->join('S002V01TDEAR', 'DEAR_IDDE','=', 'INAR_IDDE')
                ->join('S002V01TARTI', 'ARTI_IDAR','=', 'DEAR_IDAR')
                ->join('S002V01TUNID', 'UNID_IDUN','=', 'DEAR_IDUN')
                ->join('S002V01TPROV', 'PROV_NUPR','=', 'ARSE_NUPR')
                ->get([
                    'LINE_IDLI',
                    // 'LINE_NUOR',
                    'LINE_OTPR',
                    'LINE_OTCO',
                    'ARSE_IDAS',
                    // 'ARSE_CANT',
                    // 'ARSE_PRTO',
                    'INAR_IDIN',
                    'INAR_CODI',
                    'INAR_MODE',
                    'INAR_COMO',
                    'INAR_PREC',
                    'INAR_MOMI',
                    'INAR_CARA',
                    'CAMO_COMO',
                    'CAMO_DESC',
                    'CAMO_DECI',
                    'CAMO_POVA',
                    'CAMO_FEIN',
                    'CAMO_FEFI',
                    'DEAR_IDDE',
                    'DEAR_IMAG',
                    'DEAR_DESC',
                    'DEAR_CARA',
                    'DEAR_COWE',
                    'ARTI_IDAR',
                    'ARTI_COFA',
                    'ARTI_COSU',
                    'ARTI_CODI',
                    'ARTI_NOMB',
                    'UNID_IDUN',
                    'UNID_NOMB',
                    'UNID_ACRO',
                    'PROV_NUPR',
                    'PROV_NOCO',
                    'PROV_NOMB',
                    'PROV_APPA',
                    'PROV_APMA',
                    'PROV_CORR',
                    'PROV_LAD1',
                    'PROV_TEL1',
                    'PROV_LAD2',
                    'PROV_TEL2',
                    'PROV_XRFC',
                    'PROV_XTAX',
                    'PROV_CRFI',
                    'PROV_TIPO',
                    'PROV_TICO',
                    'PROV_SIWE',
                    'PROV_MEPA',
                    'PROV_CALL',
                    'PROV_NUEX',
                    'PROV_NUIN',
                    'PROV_COPO',
                    'PROV_COLO',
                    'PROV_MUNI',
                    'PROV_LOCA',
                    'PROV_ENTI',
                    'PROV_PAIS',
                ]);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true,"ERR_INVOICE_COMPARE008: Ocurrió un error al obtener la información de la base de datos del documento.",$th->getMessage(),500);
        }
        $arrLineRequestData = json_decode(json_encode($arrLineRequestData),true);
        if (empty($arrLineRequestData)) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_INVOICE_COMPARE009: No se pudo obtener la información de la línea de solicitud de compra.", [], 401);
        }

        $index = 0;
        $arrArtitles = array();
        foreach ($arrLineRequestData as $keyArtitle => $artitles) {
            if ($keyArtitle === 0) {
                $arrArtitles[$index] = $artitles;
                $arrArtitles[$index]['CANTIDAD'] = 1;
            } else {
                if (
                    in_array($artitles['INAR_IDIN'], array_column($arrArtitles, 'INAR_IDIN'))
                ) {
                    $indexArtitle = array_search($artitles['INAR_IDIN'], array_column($arrArtitles, 'INAR_IDIN'));
                    $arrArtitles[$indexArtitle]['CANTIDAD'] = $arrArtitles[$indexArtitle]['CANTIDAD'] + 1;
                } else {
                    $index = $index + 1;
                    $arrArtitles[$index] = $artitles;
                    $arrArtitles[$index]['CANTIDAD'] = 1;
                }
            }
        }

        $arrLineRequestData = $arrArtitles;

        try {
            $xml = simplexml_load_file($fileTempDataXML->ARTE_UBTE, 'SimpleXMLElement', LIBXML_NOCDATA);
            $ns = $xml->getNamespaces(true);
            $xml->registerXPathNamespace('c', $ns['cfdi']);
            $xml->registerXPathNamespace('t', $ns['tfd']);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true, "ERR_INVOICE_COMPARE010: Ocurrió un error al obtener la información del documento.", $th->getMessage(), 500);
        }
        
        $arrXml = json_decode(json_encode($xml), true)['@attributes'];
        
        $arrResponseComprobante = $this->validateComprobante($xml, $arrLineRequestData, $responseData['LINE_NUMBER']);
        if ($arrResponseComprobante['error']) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_INVOICE_COMPARE011: Ocurrió un error al válidar el documento: ".$arrResponseComprobante['msg'], $arrResponseComprobante['errors'], 401);
        }
        $arrComprobante = $arrResponseComprobante['response'];


        $arrResponseEmisor = $this->validateEmisor($xml, $arrLineRequestData, $responseData['LINE_NUMBER']);
        if ($arrResponseEmisor['error']) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_INVOICE_COMPARE012: Ocurrió un error al válidar el documento: ".$arrResponseEmisor['msg'], $arrResponseEmisor['errors'], 401);
        }
        $arrEmisor = $arrResponseEmisor['response'];

        $arrResponseReceptor = $this->validateReceptor($xml, $arrLineRequestData[0], $responseData['LINE_NUMBER']);
        if ($arrResponseReceptor['error']) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_INVOICE_COMPARE013: Ocurrió un error al válidar el documento: ".$arrResponseReceptor['msg'], $arrResponseReceptor['errors'], 401);
        }
        $arrReceptor = $arrResponseReceptor['response'];

        $arrConceptos = [];
        if ($arrXml['TipoDeComprobante'] != 'P') {
            $arrResponseConceptos = $this->validateConceptos($xml, $arrLineRequestData, $responseData['LINE_NUMBER']);
            if ($arrResponseConceptos['error']) {
                DB::rollBack();
                return $this->responseController->makeResponse(true, "ERR_INVOICE_COMPARE014: Ocurrió un error al válidar el documento: ".$arrResponseConceptos['msg'], $arrResponseConceptos['errors'], 401);
            }
            $arrConceptos = $arrResponseConceptos['response'];
        }
        
        $totalPrice = 0;
        foreach ($arrConceptos as $keyConceptos => $conceptos) {
            $totalPrice += floatval($conceptos['Importe']);
        }

        $arrResponseTimbreFiscal = $this->validateTimbreFiscal($xml);
        if ($arrResponseTimbreFiscal['error']) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_INVOICE_COMPARE015: Ocurrió un error al válidar el documento: ".$arrResponseTimbreFiscal['msg'], $arrResponseTimbreFiscal['errors'], 401);
        }
        $arrTimbreFiscal = $arrResponseTimbreFiscal['response'];


        $fileResponse = $this->documentManagementController->moveFinalFile(
            intval($responseData['LINE_NUMBER']),
            'GEAD',
            'FA',
            $fileTempDataXML,
            $user,
        );
        if(!$fileResponse[0]){
            return $this->responseController->makeResponse(true, 'ERR_INVOICE_COMPARE016: '.$fileResponse[1], [], 400);
        }
        $encCodeXML = $this->encController->encrypt($fileResponse[1]);
        
        $now = $this->functionsController->now();
        $currentDate = $now->toDateTimeString();


        $versionInvoice = '';
        if ( array_key_exists('Version', $arrComprobante) ) {
            $versionInvoice = $arrComprobante['Version'];
        }
        $fechaInvoice = '';
        if ( array_key_exists('Fecha', $arrComprobante) ) {
            $fechaInvoice = $arrComprobante['Fecha'];
        }
        $folioInvoice = '';
        if( array_key_exists('Folio', $arrComprobante)) {
            $folioInvoice = $arrComprobante['Folio'];
        }
        $serieInvoice = '';
        if( array_key_exists('Serie', $arrComprobante)) {
            $serieInvoice = $arrComprobante['Serie'];
        }
        $formaPagoInvoice = '';
        if( array_key_exists('FormaPago', $arrComprobante)) {
            $formaPagoInvoice = $arrComprobante['FormaPago'];
        }
        $metodoPagoInvoice = '';
        if( array_key_exists('MetodoPago', $arrComprobante)) {
            $metodoPagoInvoice = $arrComprobante['MetodoPago'];
        }
        $tipoCambioInvoice = null;
        if( array_key_exists('TipoCambio', $arrComprobante)) {
            $tipoCambioInvoice = $arrComprobante['TipoCambio'];
        }
        $monedaInvoice = '';
        if( array_key_exists('Moneda', $arrComprobante)) {
            $monedaInvoice = $arrComprobante['Moneda'];
        }
        $condicionesDePagoInvoice = '';
        if( array_key_exists('CondicionesDePago', $arrComprobante)) {
            $condicionesDePagoInvoice = $arrComprobante['CondicionesDePago'];
        }

        try {
            $idFacturaXml = DB::table('S002V01TFALS')->insertGetId([
                'FALS_NULI' => $responseData['LINE_NUMBER'],
                'FALS_IDLI' => $responseData['REQUEST_LINE'],
                'FALS_CODO' => $encCodeXML,
                'FALS_UUID' => $arrTimbreFiscal['UUID'],
                'FALS_VERS' => $versionInvoice,
                'FALS_FEEM' => $fechaInvoice,
                'FALS_RFCE' => $arrEmisor['Rfc'],
                'FALS_RFCR' => $arrReceptor['Rfc'],
                'FALS_FOLI' => $folioInvoice,
                'FALS_SERI' => $serieInvoice,
                'FALS_FOPA' => $formaPagoInvoice,
                'FALS_MEPA' => $metodoPagoInvoice,
                'FALS_TICA' => $tipoCambioInvoice,
                'FALS_MONE' => $monedaInvoice,
                'FALS_CAAR' => count($arrConceptos),
                'FALS_PRTO' => $totalPrice,
                'FALS_COPA' => $condicionesDePagoInvoice,
                'FALS_USRE' => $responseData['LINE_NUMBER'],
                'FALS_FERE' => $currentDate,
                'FALS_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
            ]);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_INVOICE_COMPARE017: Ocurrió un error al registrar la factura.", $th->getMessage(), 401);
        }
        if (!$idFacturaXml) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_INVOICE_COMPARE018: No se pudo registrar la factura.", 401);
        }
        
        $fileTempDataPDF = DB::table('S002V01TARTE')->where([
            ['ARTE_NULI', '=', $responseData['LINE_NUMBER']],
            ['ARTE_IDAR', '=', $idArchivoPDF],
        ])->first();

        if(is_null($fileTempDataPDF)){
            return $this->responseController->makeResponse(true, 'ERR_INVOICE_COMPARE019: El archivo consultado no está registrado', [], 404);
        }else if($fileTempDataPDF->ARTE_ESTA == 'Eliminado'){
            return $this->responseController->makeResponse(true, 'ERR_INVOICE_COMPARE020: El archivo consultado está eliminado', [], 404);
        }
        $fileResponse = $this->documentManagementController->moveFinalFile(
            intval($responseData['LINE_NUMBER']),
            'GEAD',
            'FA',
            $fileTempDataPDF,
            $user,
        );
        if(!$fileResponse[0]){
            return $this->responseController->makeResponse(true, 'ERR_INVOICE_COMPARE021: '.$fileResponse[1], [], 400);
        }
        $encCodePDF = $this->encController->encrypt($fileResponse[1]);

        if (is_null($responseData['ID_DOCUMENT'])) {
            try {
                $validateInsert = DB::table('S002V01TDLSC')
                    ->insert([
                        'DLSC_NULI' => $responseData['LINE_NUMBER'],
                        'DLSC_IDLI' => $responseData['REQUEST_LINE'],
                        'DLSC_IDFA' => $idFacturaXml,
                        'DLSC_CODO' => $encCodePDF,
                        'DLSC_TIPO' => $responseData['TYPE_INVOICE'],
                        'DLSC_TIAR' => 'FA',
                        'DLSC_DESC' => $responseData['DESCRIPTION'],
                        'DLSC_USRE' => $user,
                        'DLSC_FERE' => $currentDate,
                        'DLSC_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
                    ]);
            } catch (\Throwable $th) {
                DB::rollBack();
                return $this->responseController->makeResponse(true, "ERR_INVOICE_COMPARE022: Ocurrió un error al registrar la factura.", $th->getMessage(), 401);
            }
            if (!$validateInsert) {
                DB::rollBack();
                return $this->responseController->makeResponse(true, "ERR_INVOICE_COMPARE023: No se pudo registrar la factura.", 401);
            }

            try {
                $validateUpdate = DB::table('S002V01TLINE')
                    ->where('LINE_IDLI', '=', $responseData['REQUEST_LINE'])
                    ->where('LINE_ESTA', '=', 'En espera')
                    ->where('LINE_NULI', '=', $responseData['LINE_NUMBER'])
                    ->update([
                        'LINE_ESTA' => 'Factura Cotizada',
                        'LINE_USMO' => $user,
                        'LINE_FEMO' => $currentDate,
                        'LINE_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
                    ]);
            } catch (\Throwable $th) {
                DB::rollBack();
                return $this->responseController->makeResponse(true, "ERR_INVOICE_COMPARE024: Ocurrió un error al modificar la solicitud la factura.", $th->getMessage(), 401);
            }
           

        } else {
            try {
                $validateUpdate = DB::table('S002V01TDLSC')
                    ->where('DLSC_NULI', '=', $responseData['LINE_NUMBER'])
                    ->where('DLSC_IDLI', '=', $responseData['REQUEST_LINE'])
                    ->where('DLSC_IDDO', '=', $responseData['ID_DOCUMENT'])
                    ->update([
                        'DLSC_IDFA' => $idFacturaXml,
                        'DLSC_CODO' => $encCodePDF,
                        'DLSC_TIPO' => $responseData['TYPE_INVOICE'],
                        'DLSC_DESC' => $responseData['DESCRIPTION'],
                        'DLSC_USMO' => $user,
                        'DLSC_FEMO' => $currentDate,
                        'DLSC_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
                    ]);
            } catch (\Throwable $th) {
                DB::rollBack();
                return $this->responseController->makeResponse(true, "ERR_INVOICE_COMPARE026: Ocurrió un error al registrar la factura.", $th->getMessage(), 401);
            }
            if (!$validateUpdate) {
                DB::rollBack();
                return $this->responseController->makeResponse(true, "ERR_INVOICE_COMPARE027: No se pudo registrar la factura.", 401);
            }
        }

        

        DB::commit();
        return $this->responseController->makeResponse(false, "ÉXITO: Registro Exitoso");
    }

    private function validateComprobante($xml, $arrLineRequestData, $line) {
        $arrResponseFunction = array('error' => false, 'msg' => '', 'response' => [], 'errors' => []);
        $arrComprobante = json_decode(json_encode($xml), true);
        $arrComprobante = $arrComprobante['@attributes'];

        if ($arrComprobante['Version'] != '4.0') {
            $arrResponseFunction['error'] = true;
            $arrResponseFunction['msg'] = 'Ocurrió un error al válidar los atributuos de la factura.';
            $arrResponseFunction['errors'][] = 'La versión de la factura no es 4.0.';
        }
        
        foreach ($arrLineRequestData as $keyLineRequestData => $lineRequestData) {
            if ($arrComprobante['Moneda'] != $lineRequestData['INAR_COMO']) {
                $arrResponseFunction['error'] = true;
                $arrResponseFunction['msg'] = 'Ocurrió un error al válidar los atributuos de la factura.';
                $arrResponseFunction['errors'][] = 'El tipo de moneda es diferente.';
            }
        }
        

        $arrResponseFunction['response'] = $arrComprobante;
        fin_validateComprobante:
        return $arrResponseFunction;
    }

    private function validateEmisor($xml, $arrLineRequestData, $line) {
        $arrResponseFunction = array('error' => false, 'msg' => '', 'response' => [], 'errors' => []);
        try {
            $arrEmisor = $xml->xpath('//cfdi:Comprobante//cfdi:Emisor');
            $arrEmisor = json_decode(json_encode($arrEmisor), true);
            $arrEmisor = $arrEmisor[0]['@attributes'];
        } catch (\Throwable $th) {
            $arrResponseFunction['error'] = true;
            $arrResponseFunction['msg'] = 'Ocurrió un error a obtener el contenido de la factura.';
            $arrResponseFunction['response'] = $th->getMessage();
            goto fin_validateEmisor;
        }

        try {
            $arrTaxInformation = (array) DB::table('S002V01TINFI')
                ->where('INFI_NULI', '=', $line)
                ->where('INFI_ESTA', '=', 'Activo')
                ->first([
                    'INFI_XRFC',
                    'INFI_NOFI',
                    'INFI_CORF',
                ]);
        } catch (\Throwable $th) {
            $arrResponseFunction['error'] = true;
            $arrResponseFunction['msg'] = 'Ocurrió un error a obtener los datos de la información fiscal';
            $arrResponseFunction['response'] = $th->getMessage();
            goto fin_validateEmisor;
        }

        if (empty($arrTaxInformation)) {
            $arrResponseFunction['error'] = true;
            $arrResponseFunction['msg'] = 'No existen datos fiscales registrados en el SAM.';
            goto fin_validateEmisor;
        }

        if ($arrTaxInformation['INFI_XRFC'] != $arrEmisor['Rfc']) {
            $arrResponseFunction['error'] = true;
            $arrResponseFunction['msg'] = 'Ocurrió un error al válidar los atributuos de la factura.';
            $arrResponseFunction['errors'][] = 'Ocurrió un error al válidar el R.F.C del emisor.';
        }
        if ($arrTaxInformation['INFI_NOFI'] != $arrEmisor['Nombre']) {
            $arrResponseFunction['error'] = true;
            $arrResponseFunction['msg'] = 'Ocurrió un error al válidar los atributuos de la factura.';
            $arrResponseFunction['errors'][] = 'Ocurrió un error al válidar el Nombre del emisor.';
        }
        if ($arrTaxInformation['INFI_CORF'] != $arrEmisor['RegimenFiscal']) {
            $arrResponseFunction['error'] = true;
            $arrResponseFunction['msg'] = 'Ocurrió un error al válidar los atributuos de la factura.';
            $arrResponseFunction['errors'][] = 'Ocurrió un error al válidar el Regimen Fiscal del emisor.';
        }

        $arrResponseFunction['response'] = $arrEmisor;
        fin_validateEmisor:
        return $arrResponseFunction;
    }

    private function validateReceptor($xml, $arrLineRequestData, $line) {
        $arrResponseFunction = array('error' => false, 'msg' => '', 'response' => [], 'errors' => []);
        try {
            $arrReceptor = $xml->xpath('//cfdi:Comprobante//cfdi:Receptor');
            $arrReceptor = json_decode(json_encode($arrReceptor), true);
            $arrReceptor = $arrReceptor[0]['@attributes'];
        } catch (\Throwable $th) {
            $arrResponseFunction['error'] = true;
            $arrResponseFunction['msg'] = 'Ocurrió un error a obtener el contenido de la factura.';
            $arrResponseFunction['response'] = $th->getMessage();
            goto fin_validateReceptor;
        }

        $federalRegister = '';
        if ($arrLineRequestData['PROV_TIPO']  === 'Extranjero') {
            $federalRegister = $arrLineRequestData['PROV_XTAX'];
        } else {
            $federalRegister = $arrLineRequestData['PROV_XRFC'];
        }

        if (strtoupper($arrReceptor['Rfc']) != strtoupper($federalRegister)) {
            $arrResponseFunction['error'] = true;
            $arrResponseFunction['msg'] = 'Ocurrió un error al válidar los atributuos de la factura.';
            $arrResponseFunction['errors'][] = 'Ocurrió un error al válidar el R.F.C de la factura del receptor.';
        }
        if (strtolower($arrReceptor['Nombre']) != strtolower($arrLineRequestData['PROV_NOCO'])) {
            $arrResponseFunction['error'] = true;
            $arrResponseFunction['msg'] = 'Ocurrió un error al válidar los atributuos de la factura.';
            $arrResponseFunction['errors'][] = 'Ocurrió un error al válidar Nombre de la factura del receptor.';
        }
        if ($arrReceptor['DomicilioFiscalReceptor'] != $arrLineRequestData['PROV_COPO']) {
            $arrResponseFunction['error'] = true;
            $arrResponseFunction['msg'] = 'Ocurrió un error al válidar los atributuos de la factura.';
            $arrResponseFunction['errors'][] = 'Ocurrió un error al válidar el Domicilio Fiscal de la factura del receptor.';
        }
        if ($arrReceptor['RegimenFiscalReceptor'] != $arrLineRequestData['PROV_CRFI']) {
            $arrResponseFunction['error'] = true;
            $arrResponseFunction['msg'] = 'Ocurrió un error al válidar los atributuos de la factura.';
            $arrResponseFunction['errors'][] = 'Ocurrió un error al válidar el Régimen Fiscal de la factura del receptor.';
        }

        $arrResponseFunction['response'] = $arrReceptor;
        fin_validateReceptor:
        return $arrResponseFunction;
    }

    private function validateConceptos($xml, $arrLineRequestData, $line) {
        $arrResponseFunction = array('error' => false, 'msg' => '', 'response' => [], 'errors' => []);
        try {
            $arrConceptos = $xml->xpath('//cfdi:Comprobante//cfdi:Conceptos//cfdi:Concepto');
            $arrConceptos = json_decode(json_encode($arrConceptos), true);
        } catch (\Throwable $th) {
            $arrResponseFunction['error'] = true;
            $arrResponseFunction['msg'] = 'Ocurrió un error a obtener el contenido de la factura.';
            $arrResponseFunction['response'] = $th->getMessage();
            goto fin_valdiateConcepto;
        }

        foreach ($arrConceptos as $keyConceptos => $conceptos) {
            if (array_key_exists('@attributes', $conceptos)) {
                $conceptos = $conceptos['@attributes']; 
                $arrConceptos[$keyConceptos] = $conceptos;
            }


            foreach ($arrLineRequestData as $keyLineRequestData => $lineRequestData) {
                $countErrors = 0;
                if($conceptos['Cantidad'] != $lineRequestData['CANTIDAD']){
                    $arrResponseFunction['error'] = true;
                    $arrResponseFunction['msg'] = 'Ocurrió un error al válidar los atributuos de la factura.';
                    $arrResponseFunction['errors'][] = 'Ocurrió un error al válidar la Cantidad del concepto.';
                    $countErrors++;
                }
                if($conceptos['Unidad'] != $lineRequestData['UNID_NOMB']){
                    $arrResponseFunction['error'] = true;
                    $arrResponseFunction['msg'] = 'Ocurrió un error al válidar los atributuos de la factura.';
                    $arrResponseFunction['errors'][] = 'Ocurrió un error al válidar la Unidad del concepto.';
                    $countErrors++;
                }
                if($conceptos['Descripcion'] != $lineRequestData['INAR_CODI']){
                    $arrResponseFunction['error'] = true;
                    $arrResponseFunction['msg'] = 'Ocurrió un error al válidar los atributuos de la factura.';
                    $arrResponseFunction['errors'][] = 'Ocurrió un error al válidar la Descripción del concepto.';
                    $countErrors++;
                }
                if($conceptos['ValorUnitario'] != $lineRequestData['INAR_PREC']){
                    $arrResponseFunction['error'] = true;
                    $arrResponseFunction['msg'] = 'Ocurrió un error al válidar los atributuos de la factura.';
                    $arrResponseFunction['errors'][] = 'Ocurrió un error al válidar el Valor Unitario del concepto.';
                    $countErrors++;
                }
                /* if($conceptos['Importe'] != $lineRequestData['ARSE_PRTO']){
                    $arrResponseFunction['error'] = true;
                    $arrResponseFunction['msg'] = 'Ocurrió un error al válidar los atributuos de la factura.';
                    $arrResponseFunction['errors'][] = 'Ocurrió un error al válidar el Importe del concepto.';
                    $countErrors++;
                } */
                if ($countErrors == 0) {
                    $arrResponseFunction['error'] = false;
                    $arrResponseFunction['msg'] = '';
                    $arrResponseFunction['errors'] = [];
                    break;
                }
            }

            if ($arrResponseFunction['error']) {
                goto fin_valdiateConcepto;
            }
        }
        $arrResponseFunction['response'] = $arrConceptos;
        fin_valdiateConcepto:
        return $arrResponseFunction;
    }

    private function validateTimbreFiscal($xml) {
        $arrResponseFunction = array('error' => false, 'msg' => '', 'response' => [], 'errors' => []);
        try {
            $arrTimbreFiscal = $xml->xpath('//t:TimbreFiscalDigital');
            $arrTimbreFiscal = json_decode(json_encode($arrTimbreFiscal), true);
            $arrTimbreFiscal = $arrTimbreFiscal[0]['@attributes'];
        } catch (\Throwable $th) {
            $arrResponseFunction['error'] = true;
            $arrResponseFunction['msg'] = 'Ocurrió un error a obtener el contenido de la factura.';
            $arrResponseFunction['response'] = $th->getMessage();
            goto fin_validateTimbreFiscal;
        }

        $arrResponseFunction['response'] = $arrTimbreFiscal;

        fin_validateTimbreFiscal:
        return $arrResponseFunction;
    }
}
