<?php

namespace App\Http\Controllers\Inside;

use PDF;
use DateTime;
use App\LADET;
use App\LAMTRO;
use App\LFMTRO;
use App\LFGIROS;
use App\DETPAGOS;
use App\ErrorLog;
use App\LFDETLIC;
use App\MAEPAGOS;
use App\Community;
use App\LFAUXMTRO;
use Dompdf\Dompdf;
use App\LAMTROGIRO;
use App\LAPortador;
use App\AccountStatement;
use Illuminate\Support\Str;
use iio\libmergepdf\Merger; 
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\View;
use SimpleSoftwareIO\QrCode\Facades\QrCode;
use Symfony\Component\HttpFoundation\Response;

class MainController extends Controller
{
    public function index(){    
        return view('Outside.searching'); 
    }

    public function generateTicket(Request $request){
        if($request->tlicence != null){
            switch($request->input('tlicence')){
                case "LFM":
                    $accNumber = trim($request->accountNumber);
                    if($accNumber != null){
                        $lfMtro = LFMTRO::where('LFM_CVELIC', '=', $request['accountNumber'])->first();
                        if($lfMtro != null){
                            $lfAuxMtro = LFAUXMTRO::where('LFA_CVELIC','=',$request['accountNumber'])->first();
                            if($lfAuxMtro != null){
                                $lfGiros = LFGIROS::where('LFG_CLAVE','=',$lfAuxMtro->LFA_CVEGIRO)->first();
                                // $lfGiros = LFGIROS::where('LFG_CLAVE','=', "2023")->first();
                                if($lfGiros != null){
                                    $folderPath = public_path('assets/images/');                                    
                                    $today = getdate();
                                    $monthName = array("void","Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre");
                                    $month = $monthName[$today['mon']];
                                    $tday = $today['mday'];
                                    $tyear = $today['year'];
                                    $fullDate = strtotime($lfMtro['LFM_FECALT']);
                                    $year = date('Y', $fullDate);
                                    $monthNumber = date('m', $fullDate);
                                    $day = date('d', $fullDate);
                                    $createdAt = $day.'/'.$monthNumber.'/'.$year;
                                    $token = Str::random(50);
                                    $qrcode = base64_encode(QrCode::format('svg')->size(100)->errorCorrection('H')->generate('estadoscuentamgp.gomezpalacio.gob.mx/historial/'.$request->tlicence.'_'.$request->accountNumber.'_'.$token));
                                    $data = array(
                                        'lfMtro' => $lfMtro,
                                        'lfAuxMtro' => $lfAuxMtro,
                                        'lfGiros' => $lfGiros,
                                        'today' => $today,
                                        'month' => $month,
                                        'createdAt' => $createdAt,
                                        'qr' => $qrcode,
                                        'tday' => $tday,
                                        'tyear' => $tyear,
                                        'folderPath' => $folderPath
                                    );

                                    $accStatement = AccountStatement::create([
                                        'nCuenta' => $request['accountNumber'],
                                        'type' => $request->tlicence, 
                                        'token' => $token, 
                                        'annualPeriod' => $tyear
                                    ]);

                                    $pdf = PDF::loadView('PDF.LFM', $data);
                                    $pdf->setPaper('letter', 'portrait');
                                    return $pdf->stream('pdf_file.pdf');
                                    // return view('PDF.test', $data);
                                }
                                else{
                                    $errors = ErrorLog::create([
                                        'users_id' => session('user_id'),
                                        'owner' => session('user'),
                                        'description' => 'Se ha ingresado un número de cuenta inválido.'
                                    ]);
                                    $errors->save();
                                    return redirect()->back()->with('message', 'Favor de ingresar un número de cuenta válido');
                                }
                            }
                            else{
                                $errors = ErrorLog::create([
                                    'users_id' => session('user_id'),
                                    'owner' => session('user'),
                                    'description' => 'Se ha ingresado un número de cuenta inválido.'
                                ]);
                                $errors->save();
                                return redirect()->back()->with('message', 'Favor de ingresar un número de cuenta válido');
                            }
                        }
                        else{
                            $errors = ErrorLog::create([
                                'users_id' => session('user_id'),
                                'owner' => session('user'),
                                'description' => 'Se ha ingresado un número de cuenta inválido.'
                            ]);
                            $errors->save();
                            return redirect()->back()->with('message', 'Favor de ingresar un número de cuenta válido');
                        }
                    }
                    else{ 
                        $errors = ErrorLog::create([
                        'users_id' => session('user_id'),
                        'owner' => session('user'),
                        'description' => 'Se ha ingresado un número de cuenta inválido.'
                        ]);
                        $errors->save();
                        return redirect()->back()->with('message','El número de cuenta está erróneo');
                    }
                break;

                case "LAL":
                    switch($request->typeSearch){
                        case "acountN":
                            $accNumber = trim($request->accountNumber);
                            if($accNumber != null){
                                $explode = explode(',',$accNumber);
                                if($explode != null && count($explode) > 0){
                                    $merger = new Merger();
                                    $names = array();
                                    for ($i=0; $i < count($explode) ; $i++) { 
                                        $laMtro = LAMTRO::where('LAM_CVELA', '=', $explode[$i])->first();
                                        if($laMtro != null){
                                            $laGiro = LAMTROGIRO::where('AMG_CLAVE', '=', $laMtro->LAM_GIRO)->first();
                                            $laMtro->LAM_COLEST = ctype_space($laMtro->LAM_COLEST) || $laMtro->LAM_COLEST == "" || $laMtro->LAM_COLEST == null ? 0 : $laMtro->LAM_COLEST; 
                                            $colonia = Community::where('COL_CVECOLONIA', '=', $laMtro->LAM_COLEST)->first();
                                            if($laGiro->count()>0 && $laGiro != null){
                                                if($colonia->count()>0 && $colonia!=null){
                                                    $folderPath = public_path('assets/images/');    
                                                    $date = new DateTime($laMtro->LAM_FECALTA);                             
                                                    $laMtro->date = $date->format('d/m/Y');
                                                    $today = getdate();
                                                    $monthName = array("void","Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre");
                                                    $month = $monthName[$today['mon']];
                                                    $tday = $today['mday'];
                                                    $tyear = $today['year'];
                                                    $token = Str::random(50);
                                                    $qrcode = base64_encode(QrCode::format('svg')->size(100)->errorCorrection('H')->generate('estadoscuentamgp.gomezpalacio.gob.mx/historial/'.$request->tlicence.'_'.$explode[$i].'_'.$token));
                                                    $qrcode2 = base64_encode(QrCode::format('svg')->size(150)->errorCorrection('H')->generate('estadoscuentamgp.gomezpalacio.gob.mx/historial/'.$request->tlicence.'_'.$explode[$i].'_'.$token));
                                                    $data = array(
                                                        'laMtro' => $laMtro,
                                                        'qr' => $qrcode,
                                                        'laGiro' => $laGiro,
                                                        'community' => $colonia,
                                                        'folderPath' => $folderPath,
                                                        'month' => $month,
                                                        'tday' => $tday,
                                                        'tyear' => $tyear
                                                    );

                                                    $data2 = array(
                                                        'laMtro' => $laMtro,
                                                        'qr' => $qrcode2,
                                                        'laGiro' => $laGiro,
                                                        'community' => $colonia,
                                                        'folderPath' => $folderPath,
                                                        'month' => $month,
                                                        'tday' => $tday,
                                                        'tyear' => $tyear
                                                    );
                        
                                                    $accStatement = AccountStatement::create([
                                                        'nCuenta' => $explode[$i],
                                                        'type' => $request->tlicence, 
                                                        'token' => $token, 
                                                        'annualPeriod' => $tyear
                                                    ]);
                                                    $accStatement->save();
                                                    
                                                    $view =  \View::make('PDF.LAL', $data)->render();
                                                    $dompdf = \App::make('dompdf.wrapper');
                                                    $dompdf->loadHTML($view);
                                                    $dompdf->setPaper('letter','portrait');
                                                    $namepdf = "LAL".$i.".pdf";
                                                    file_put_contents($namepdf,$dompdf->output());
                                                    unset($dompdf);
                                                    array_push($names, $namepdf);
    
                                                    $view =  \View::make('PDF.LALH', $data2)->render();
                                                    $dompdf = \App::make('dompdf.wrapper');
                                                    $dompdf->setPaper('letter', 'landscape');
                                                    $dompdf->loadHtml($view);
                                                    $namepdf = "LALH".$i.".pdf";
                                                    file_put_contents($namepdf,$dompdf->output());
                                                    array_push($names, $namepdf);
                                                }
                                                else{
                                                    $errors = ErrorLog::create([
                                                        'users_id' => session('user_id'),
                                                        'owner' => session('user'),
                                                        'description' => 'la colonia del número de cuenta ingresado tiene un error.'
                                                    ]);
                                                    $errors->save();
                                                    return redirect()->back()->with('message', 'la colonia del número de cuenta ingresado tiene un error');
                                                }
                                            }
                                            else{
                                                $errors = ErrorLog::create([
                                                    'users_id' => session('user_id'),
                                                    'owner' => session('user'),
                                                    'description' => 'El giro del número de cuenta ingresado tiene un error.'
                                                ]);
                                                $errors->save();
                                                return redirect()->back()->with('message', 'El giro del número de cuenta ingresado tiene un error');
                                            }
                                        }
                                    }
                                    $merger->addIterator($names);
                                    $createdPdf = $merger->merge();
                                }
                                return new Response($createdPdf, 200, array('Content-Type' => 'application/pdf'));
                            }
                            else{
                                $errors = ErrorLog::create([
                                    'users_id' => session('user_id'),
                                    'owner' => session('user'),
                                    'description' => 'Se ha ingresado un número de cuenta inválido.'
                                ]);
                                $errors->save();
                                return redirect()->back()->with('message', 'Favor de ingresar un número de cuenta valido');
                            }
                        break;
                        case "range":
                            $accNumberD = trim($request->accountNumberD);
                            $accNumberH = trim($request->accountNumberH);
                            if($accNumberD != null && $accNumberH != null){
                                if($accNumberD <= $accNumberH) {
                                    $merger = new Merger();
                                    $names = array();
                                    for ($i=$accNumberD; $i <= $accNumberH ; $i++) { 
                                        $laMtro = LAMTRO::where('LAM_CVELA', '=', $i)->first();
                                        if($laMtro != null){
                                            $laGiro = LAMTROGIRO::where('AMG_CLAVE', '=', $laMtro->LAM_GIRO)->first();
                                            $laMtro->LAM_COLEST = ctype_space($laMtro->LAM_COLEST) || $laMtro->LAM_COLEST == "" || $laMtro->LAM_COLEST == null ? 0 : $laMtro->LAM_COLEST; 
                                        
                                            $colonia = Community::where('COL_CVECOLONIA', '=', $laMtro->LAM_COLEST)->first();
                                            if($laGiro->count()>0 && $laGiro != null){
                                                if($colonia->count()>0 && $colonia!=null){
                                                    
                                                    $folderPath = public_path('assets/images/');
                                                    $date = new DateTime($laMtro->LAM_FECALTA);
                                                    $laMtro->date = $date->format('d/m/Y');
                                                    $today = getdate();
                                                    $monthName = array("void","Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre");
                                                    $month = $monthName[$today['mon']];
                                                    $tday = $today['mday'];
                                                    $tyear = $today['year'];
                                                    $token = Str::random(50);
                                                    $qrcode = base64_encode(QrCode::format('svg')->size(100)->errorCorrection('H')->generate('estadoscuentamgp.gomezpalacio.gob.mx/historial/'.$request->tlicence.'_'.$i.'_'.$token));
                                                    $data = array(
                                                        'laMtro' => $laMtro,
                                                        'laGiro' => $laGiro,
                                                        'qr' => $qrcode,
                                                        'community' => $colonia,
                                                        'folderPath' => $folderPath,
                                                        'month' => $month,
                                                        'tday' => $tday,
                                                        'tyear' => $tyear
                                                    );
                        
                                                    $accStatement = AccountStatement::create([
                                                        'nCuenta' => $i,
                                                        'type' => $request->tlicence, 
                                                        'token' => $token, 
                                                        'annualPeriod' => $tyear
                                                    ]);
                                                    $accStatement->save();
                                                    
                                                    $view =  \View::make('PDF.LAL', $data)->render();
                                                    $dompdf = \App::make('dompdf.wrapper');
                                                    $dompdf->loadHTML($view);
                                                    $dompdf->setPaper('letter','portrait');
                                                    $namepdf = "LAL".$i.".pdf";
                                                    file_put_contents($namepdf,$dompdf->output());
                                                    unset($dompdf);
                                                    array_push($names, $namepdf);

                                                    $view =  \View::make('PDF.LALH', $data)->render();
                                                    $dompdf = \App::make('dompdf.wrapper');
                                                    $dompdf->setPaper('letter', 'landscape');
                                                    $dompdf->loadHtml($view);
                                                    $namepdf = "LALH".$i.".pdf";
                                                    file_put_contents($namepdf,$dompdf->output());
                                                    array_push($names, $namepdf);
                                                }
                                                else{
                                                    $errors = ErrorLog::create([
                                                        'users_id' => session('user_id'),
                                                        'owner' => session('user'),
                                                        'description' => 'la colonia del número de cuenta ingresado tiene un error.'
                                                    ]);
                                                    $errors->save();
                                                    return redirect()->back()->with('message', 'la colonia del número de cuenta ingresado tiene un error');
                                                }
                                            }
                                            else{
                                                $errors = ErrorLog::create([
                                                    'users_id' => session('user_id'),
                                                    'owner' => session('user'),
                                                    'description' => 'El giro de la solicitud no se ha encontrado.'
                                                ]);
                                                $errors->save();
                                                return redirect()->back()->with('message', 'Favor de ingresar un número de cuenta correcto.');
                                            }

                                        }
                                    }
                                    $merger->addIterator($names);
                                    $createdPdf = $merger->merge();
                                    return new Response($createdPdf, 200, array('Content-Type' => 'application/pdf'));
                                }
                                else{
                                    $errors = ErrorLog::create([
                                        'users_id' => session('user_id'),
                                        'owner' => session('user'),
                                        'description' => 'El valor de rango de inicio es mayor al de termino.'
                                    ]);
                                    $errors->save();
                                    return redirect()->back()->with('message', 'Favor de ingresar un valor de inicio menor al de termino.');
                                }
                            }
                            else{
                                $errors = ErrorLog::create([
                                    'users_id' => session('user_id'),
                                    'owner' => session('user'),
                                    'description' => 'El número de cuenta no corresponde con ninguna existente.'
                                ]);
                                $errors->save();
                                return redirect()->back()->with('message', 'Favor de ingresar cuentas oficiales');
                            }
                        break;
                        case "conc":
                            $conc = trim($request->conc);
                            $concName = '%'.$conc.'%';
                            if($conc != null && $conc != ""){
                                $laMtro = LAMTRO::where('LAM_NOMCONC', 'like', $concName)->get();
                                if($laMtro->count() > 0 && $laMtro != null){
                                    $merger = new Merger();
                                    $names = array();
                                    foreach($laMtro as $key => $element){
                                        $laGiro = LAMTROGIRO::where('AMG_CLAVE', '=', $element->LAM_GIRO)->first();
                                        $element->LAM_COLEST = ctype_space($element->LAM_COLEST) || $element->LAM_COLEST == "" || $element->LAM_COLEST == null ? 0 : $element->LAM_COLEST; 
                                        $colonia = Community::where('COL_CVECOLONIA', '=', $element->LAM_COLEST)->first();
                                        if($laGiro->count()>0 && $laGiro != null){
                                            if($colonia!=null && $colonia->count()>0){
                                                $folderPath = public_path('assets/images/');    
                                                $date = new DateTime($element->LAM_FECALTA);                             
                                                $element->date = $date->format('d/m/Y');
                                                $today = getdate();
                                                $monthName = array("void","Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre");
                                                $month = $monthName[$today['mon']];
                                                $tday = $today['mday'];
                                                $tyear = $today['year'];
                                                $token = Str::random(50);
                                                $qrcode = base64_encode(QrCode::format('svg')->size(100)->errorCorrection('H')->generate('estadoscuentamgp.gomezpalacio.gob.mx/historial/'.$request->tlicence.'_'.$element->LAM_CVELA.'_'.$token));
                                                $data = array(
                                                    'laMtro' => $element,
                                                    'qr' => $qrcode,
                                                    'laGiro' => $laGiro,
                                                    'community' => $colonia,
                                                    'folderPath' => $folderPath,
                                                    'month' => $month,
                                                    'tday' => $tday,
                                                    'tyear' => $tyear
                                                );
                    
                                                $accStatement = AccountStatement::create([
                                                    'nCuenta' => $element->LAM_CVELA,
                                                    'type' => $request->tlicence, 
                                                    'token' => $token, 
                                                    'annualPeriod' => $tyear
                                                ]);
                                                $accStatement->save();
                                                
                                                $view =  \View::make('PDF.LAL', $data)->render();
                                                $dompdf = \App::make('dompdf.wrapper');
                                                $dompdf->loadHTML($view);
                                                $dompdf->setPaper('letter','portrait');
                                                $namepdf = "LAL".$key.".pdf";
                                                file_put_contents($namepdf,$dompdf->output());
                                                unset($dompdf);
                                                array_push($names, $namepdf);

                                                $view =  \View::make('PDF.LALH', $data)->render();
                                                $dompdf = \App::make('dompdf.wrapper');
                                                $dompdf->setPaper('letter', 'landscape');
                                                $dompdf->loadHtml($view);
                                                $namepdf = "LALH".$key.".pdf";
                                                file_put_contents($namepdf,$dompdf->output());
                                                array_push($names, $namepdf);
                                            }
                                            else{
                                                $errors = ErrorLog::create([
                                                    'users_id' => session('user_id'),
                                                    'owner' => session('user'),
                                                    'description' => 'la colonia del número de cuenta ingresado tiene un error.'
                                                ]);
                                                $errors->save();
                                                return redirect()->back()->with('message', 'la colonia del número de cuenta ingresado tiene un error');
                                            }
                                        }
                                    }
                                    $merger->addIterator($names);
                                    $createdPdf = $merger->merge();
                                    return new Response($createdPdf, 200, array('Content-Type' => 'application/pdf'));
                                }
                                else{
                                    $errors = ErrorLog::create([
                                        'users_id' => session('user_id'),
                                        'owner' => session('user'),
                                        'description' => 'el concesionario es inválido.'
                                    ]);
                                    $errors->save();
                                    return redirect()->back()->with('message', 'el concesionario ingresado tiene un error o es inválido');
                                }
                            }
                            else{
                                $errors = ErrorLog::create([
                                    'users_id' => session('user_id'),
                                    'owner' => session('user'),
                                    'description' => 'Se ha ingresado un concesionario inválido.'
                                ]);
                                $errors->save();
                                return redirect()->back()->with('message', 'Favor de ingresar un concesionario válido');
                            }
                        break;
                    }
                break;

                case "LAM":
                    $accNumber = trim($request->accountNumber);
                    if($accNumber != null){
                        $lfMtro = LFMTRO::where('LFM_CVELIC', '=', $request['accountNumber'])->first();
                        if($lfMtro != null){
                            $lfAuxMtro = LFAUXMTRO::where('LFA_CVELIC','=',$request['accountNumber'])->first();
                            if($lfAuxMtro != null){
                                $lfGiros = LFGIROS::where('LFG_CLAVE','=',$lfAuxMtro->LFA_CVEGIRO)->first();
                                if($lfGiros != null){
                                    switch($lfAuxMtro->LFA_GRUPO){
                                        case 'F':
                                            $lfAuxMtro->Group = 'Fijo';
                                            break;
                                        case 'S':
                                            $lfAuxMtro->Group = 'SemiFijo';
                                            break;
                                        case 'A':
                                            $lfAuxMtro->Group = 'Ambulante';
                                            break;
                                        default:
                                            break;            
                                    }
                                    $folderPath = public_path('assets/images/');                                    
                                    $today = getdate();
                                    $monthName = array("void","Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre");
                                    $month = $monthName[$today['mon']];
                                    $tday = $today['mday'];
                                    $tyear = $today['year'];
                                    $fullDate = strtotime($lfMtro['LFM_FECALT']);
                                    $year = date('Y', $fullDate);
                                    $monthNumber = date('m', $fullDate);
                                    $day = date('d', $fullDate);
                                    $createdAt = $day.'/'.$monthNumber.'/'.$year;
                                    $token = Str::random(50);
                                    $qrcode = base64_encode(QrCode::format('svg')->size(100)->errorCorrection('H')->generate('estadoscuentamgp.gomezpalacio.gob.mx/historial/'.$request->tlicence.'_'.$request->accountNumber.'_'.$token));
                                    $data = array(
                                        'lfMtro' => $lfMtro,
                                        'lfAuxMtro' => $lfAuxMtro,
                                        'lfGiros' => $lfGiros,
                                        'today' => $today,
                                        'month' => $month,
                                        'createdAt' => $createdAt,
                                        'qr' => $qrcode,
                                        'tday' => $tday,
                                        'tyear' => $tyear,
                                        'folderPath' => $folderPath
                                    );

                                    $accStatement = AccountStatement::create([
                                        'nCuenta' => $request['accountNumber'],
                                        'type' => $request->tlicence, 
                                        'token' => $token, 
                                        'annualPeriod' => $tyear
                                    ]);

                                    $pdf = PDF::loadView('PDF.LFAM', $data);
                                    $pdf->setPaper('letter', 'portrait');
                                    return $pdf->stream('pdf_file.pdf');
                                }
                                else{
                                    $errors = ErrorLog::create([
                                        'users_id' => session('user_id'),
                                        'owner' => session('user'),
                                        'description' => 'Se ha ingresado un número de cuenta inválido.'
                                        ]);
                                        $errors->save();
                                    return redirect()->back()->with('message', 'Favor de ingresar un número de cuenta válido');
                                }
                            }
                            else{
                                $errors = ErrorLog::create([
                                    'users_id' => session('user_id'),
                                    'owner' => session('user'),
                                    'description' => 'Se ha ingresado un número de cuenta inválido.'
                                    ]);
                                    $errors->save();
                                return redirect()->back()->with('message', 'Favor de ingresar un número de cuenta válido');
                            }
                        }
                        else{
                            $errors = ErrorLog::create([
                                'users_id' => session('user_id'),
                                'owner' => session('user'),
                                'description' => 'Se ha ingresado un número de cuenta inválido.'
                                ]);
                                $errors->save();
                            return redirect()->back()->with('message', 'Favor de ingresar un número de cuenta válido');
                        }
                    }
                    else{
                        $errors = ErrorLog::create([
                            'users_id' => session('user_id'),
                            'owner' => session('user'),
                            'description' => 'Se ha ingresado un número de cuenta inválido.'
                            ]);
                            $errors->save();
                        return redirect()->back()->with('message','El número de cuenta está erróneo');
                    }
                break;

                case "LPO":
                    $accNumber = trim($request->accountNumber);
                    if($accNumber != null){
                        $laPortador = LAPortador::where('LAP_RECIBOOFICIAL', '=', $request['accountNumber'])->first();
                        if($laPortador != null){
                            $folderPath = public_path('assets/images/');                                    
                            $today = getdate();
                            $tyear = $today['year'];
                            $token = Str::random(50);
                            $qrcode = base64_encode(QrCode::format('svg')->size(100)->errorCorrection('H')->generate('estadoscuentamgp.gomezpalacio.gob.mx/historial/'.$request->tlicence.'_'.$request->accountNumber.'_'.$token));
                            $qrcode2 = base64_encode(QrCode::format('svg')->size(150)->errorCorrection('H')->generate('estadoscuentamgp.gomezpalacio.gob.mx/historial/'.$request->tlicence.'_'.$request->accountNumber.'_'.$token));
                            $data = array(
                                'laPortador' => $laPortador,
                                'qr' => $qrcode,
                                'folderPath' => $folderPath
                            );
                            $data2 = array(
                                'laPortador' => $laPortador,
                                'qr' => $qrcode2,
                                'folderPath' => $folderPath
                            );

                            $accStatement = AccountStatement::create([
                                'nCuenta' => $request['accountNumber'],
                                'type' => $request->tlicence, 
                                'token' => $token, 
                                'annualPeriod' => $tyear
                            ]);
                            $accStatement->save();
                            
                            $view =  \View::make('PDF.LPO', $data)->render();
                            $dompdf = \App::make('dompdf.wrapper');
                            $dompdf->loadHTML($view);
                            $dompdf->setPaper('letter','portrait');
                            $m = new Merger();
                            file_put_contents('LPO.pdf',$dompdf->output());
                            unset($dompdf);

                            $view =  \View::make('PDF.LPOH', $data2)->render();
                            $dompdf = \App::make('dompdf.wrapper');
                            $dompdf->setPaper('letter', 'landscape');
                            $dompdf->loadHtml($view);
                            file_put_contents('LPOH.pdf',$dompdf->output());
                            $m->addIterator(['LPO.pdf', 'LPOH.pdf']);
                            $createdPdf = $m->merge();
                            return new Response($createdPdf, 200, array('Content-Type' => 'application/pdf'));
                        }
                        else{
                            $errors = ErrorLog::create([
                                'users_id' => session('user_id'),
                                'owner' => session('user'),
                                'description' => 'Se ha ingresado un número de cuenta inválido.'
                                ]);
                                $errors->save();
                            return redirect()->back()->with('message', 'Favor de ingresar un número de recibo oficial válido');
                        }
                    }
                    else{
                        $errors = ErrorLog::create([
                            'users_id' => session('user_id'),
                            'owner' => session('user'),
                            'description' => 'Se ha ingresado un número de cuenta inválido.'
                            ]);
                            $errors->save();
                        return redirect()->back()->with('message','El número del recibo oficial está erróneo');
                    }
                break;

                default:
                    return array();
                break;
            }
        }
    }


    public function generateHistory($url){
        if($url != null){
            $explode = explode("_", $url);
            if(count($explode) == 3){
                $tlicence = $explode[0];
                $accountNumber = $explode[1];
                $token = $explode[2];
                switch($tlicence){
                    case "LFM":
                        $accountStatement = AccountStatement::where('type','=',$tlicence)->where('nCuenta','=',$accountNumber)->where('token','=',$token)->get();
                        if($accountStatement->count() > 0){
                            $lfDetLic = LFDETLIC::where('LFD_CVELIC', '=', $accountNumber)->orderBy('LFD_ANIO')->get();
                            foreach($lfDetLic as $element){
                                $date = new DateTime($element->LFD_FECPAGO);
                                $element->LFD_FECHPAGO = $date->format('Y-m-d');
                                $element->LFD_RECARGOS = $element->LFD_RECARGOS == '0.00' ? "0.00" : $element->LFD_RECARGOS; 
                                $element->LFD_BONIF = $element->LFD_BONIF == '0.00' ? "0.00" : $element->LFD_BONIF; 
                                $element->LFD_SALDOS = $element->LFD_SALDOS == '0.00' ? "0.00" : $element->LFD_SALDOS; 
                                $element->LFD_IMPORTE = $element->LFD_IMPORTE == '0.00' ? "0.00" : $element->LFD_IMPORTE; 
                                $element->LFD_COSTORCB = $element->LFD_COSTORCB == '0.00' ? "0.00" : $element->LFD_COSTORCB; 
                                $element->LFD_RECRCB = $element->LFD_RECRCB == '0.00' ? "0.00" : $element->LFD_RECRCB; 
                                $element->LFD_BONIFRCB = $element->LFD_BONIFRCB == '0.00' ? "0.00" : $element->LFD_BONIFRCB; 
                                $element->LFD_MULTA = $element->LFD_MULTA == '0.00' ? "0.00" : $element->LFD_MULTA; 
                                $element->LFD_RECMUL = $element->LFD_RECMUL == '0.00' ? "0.00" : $element->LFD_RECMUL; 
                                $element->LFD_BONIFMUL = $element->LFD_BONIFMUL == '0.00' ? "0.00" : $element->LFD_BONIFMUL; 
                            }
                            $lfMtro = LFMTRO::where('LFM_CVELIC', '=', $accountNumber)->first();
                            $lfAuxMtro = LFAUXMTRO::where('LFA_CVELIC','=',$accountNumber)->first();
                            $lfGiros = LFGIROS::where('LFG_CLAVE','=',$lfAuxMtro->LFA_CVEGIRO)->first();
                            $folderPath = public_path('assets/images/');                                    
                            $today = getdate();
                            $monthName = array("void","Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre");
                            $month = $monthName[$today['mon']];
                            $tday = $today['mday'];
                            $tyear = $today['year'];
                            $fullDate = strtotime($lfMtro['LFM_FECALT']);
                            $year = date('Y', $fullDate);
                            $monthNumber = date('m', $fullDate);
                            $day = date('d', $fullDate);
                            $createdAt = $day.'/'.$monthNumber.'/'.$year;
                            $data = array(
                                'lfMtro' => $lfMtro,
                                'lfAuxMtro' => $lfAuxMtro,
                                'lfGiros' => $lfGiros,
                                'today' => $today,
                                'month' => $month,
                                'createdAt' => $createdAt,
                                'tday' => $tday,
                                'tyear' => $tyear,
                                'folderPath' => $folderPath,
                                'lfDetLic' => $lfDetLic
                            );
                            $pdf = PDF::loadView('History.funcionamiento', $data);
                            $pdf->setPaper('A4', 'portrait');
                            return $pdf->stream('LFM-'.$accountNumber.'.pdf');
                                           
                        }
                        else{
                            $errors = ErrorLog::create([
                                'users_id' => 0,
                                'owner' => 'Error',
                                'description' => 'Se ha tratado de generar un historial de un número de cuenta inválido, ya que el tipo:' . $tlicence.', el número de cuenta: '.$accountNumber.' o el token: '.$token.' no es o son válidos.'
                            ]);
                            $errors->save();
                            return redirect('error');
                        }
                    break;
                    case "LAL":
                        $accountStatement = AccountStatement::where('type','=',$tlicence)->where('nCuenta','=',$accountNumber)->where('token','=',$token)->get();
                        if($accountStatement->count() > 0){
                            $laDet = LADET::where('LAD_CVELA', '=', $accountNumber)->orderBy('LAD_FECALTA')->get();
                            foreach($laDet as $element){
                                $date = new DateTime($element->LAD_FECPAG);
                                $element->LAD_FECPAG = $date->format('Y-m-d');
                                $date = new DateTime($element->LAD_FECALTA);
                                $element->LAD_FECALTA = $date->format('Y-m-d');
                                $date = new DateTime($element->LAD_FECVEN);
                                $element->LAD_FECVEN = $date->format('Y-m-d');
                                $element->LAD_IMPORTE = $element->LAD_IMPORTE == '0' ? "0.00" : $element->LAD_IMPORTE; 
                                $element->LAD_RECARGOS = $element->LAD_RECARGOS == '0' ? "0.00" : $element->LAD_RECARGOS; 
                                $element->LAD_SALDO = $element->LAD_SALDO == '0' ? "0.00" : $element->LAD_SALDO; 
                                $element->LAD_TOTPAGAR = $element->LAD_TOTPAGAR == '0' ? "0.00" : $element->LAD_TOTPAGAR; 
                                $element->LAD_BONIFICA = $element->LAD_BONIFICA == '0' ? "0.00" : $element->LAD_BONIFICA; 
                                $element->LAD_PAGADO = $element->LAD_PAGADO == '0' ? "0.00" : $element->LAD_PAGADO; 
                            }
                            $laMtro = LAMTRO::where('LAM_CVELA', '=', $accountNumber)->first();
                            $laGiro = LAMTROGIRO::where('AMG_CLAVE', '=', $laMtro->LAM_GIRO)->first();
                            $laMtro->LAM_COLEST = ctype_space($laMtro->LAM_COLEST) || $laMtro->LAM_COLEST == "" || $laMtro->LAM_COLEST == null ? 0 : $laMtro->LAM_COLEST; 
                            $colonia = Community::where('COL_CVECOLONIA', '=', $laMtro->LAM_COLEST)->first();
                            $folderPath = public_path('assets/images/');                                    
                            $today = getdate();
                            $monthName = array("void","Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre");
                            $month = $monthName[$today['mon']];
                            $tday = $today['mday'];
                            $tyear = $today['year'];
                            $fullDate = strtotime($laMtro['LFM_FECALTA']);
                            $year = date('Y', $fullDate);
                            $monthNumber = date('m', $fullDate);
                            $day = date('d', $fullDate);
                            $createdAt = $day.'/'.$monthNumber.'/'.$year;
                            $data = array(
                                'laMtro' => $laMtro,
                                'laGiro' => $laGiro,
                                'community' => $colonia,
                                'today' => $today,
                                'month' => $month,
                                'createdAt' => $createdAt,
                                'tday' => $tday,
                                'tyear' => $tyear,
                                'folderPath' => $folderPath,
                                'laDet' => $laDet
                            );
                            $pdf = PDF::loadView('History.alcoholes', $data);
                            $pdf->setPaper('A4', 'portrait');
                            return $pdf->stream('LAL-'.$accountNumber.'.pdf');
                        }
                        else{
                            $errors = ErrorLog::create([
                                'users_id' => 0,
                                'owner' => 'Error',
                                'description' => 'Se ha tratado de generar un historial de un número de cuenta inválido, ya que el tipo:' . $tlicence.', el número de cuenta: '.$accountNumber.' o el token: '.$token.' no es o son válidos.'
                            ]);
                            $errors->save();
                            return redirect('error');
                        }
                    break;
        
                    case "LAM":
                        $accountStatement = AccountStatement::where('type','=',$tlicence)->where('nCuenta','=',$accountNumber)->where('token','=',$token)->get();
                        if($accountStatement->count() > 0){
                            $lfDetLic = LFDETLIC::where('LFD_CVELIC', '=', $accountNumber)->orderBy('LFD_ANIO')->get();
                            foreach($lfDetLic as $element){
                                $date = new DateTime($element->LFD_FECPAGO);
                                $element->LFD_FECHPAGO = $date->format('Y-m-d');
                                $element->LFD_RECARGOS = $element->LFD_RECARGOS == '0.00' ? "0.00" : $element->LFD_RECARGOS; 
                                $element->LFD_BONIF = $element->LFD_BONIF == '0.00' ? "0.00" : $element->LFD_BONIF; 
                                $element->LFD_SALDOS = $element->LFD_SALDOS == '0.00' ? "0.00" : $element->LFD_SALDOS; 
                                $element->LFD_IMPORTE = $element->LFD_IMPORTE == '0.00' ? "0.00" : $element->LFD_IMPORTE; 
                                $element->LFD_COSTORCB = $element->LFD_COSTORCB == '0.00' ? "0.00" : $element->LFD_COSTORCB; 
                                $element->LFD_RECRCB = $element->LFD_RECRCB == '0.00' ? "0.00" : $element->LFD_RECRCB; 
                                $element->LFD_BONIFRCB = $element->LFD_BONIFRCB == '0.00' ? "0.00" : $element->LFD_BONIFRCB; 
                                $element->LFD_MULTA = $element->LFD_MULTA == '0.00' ? "0.00" : $element->LFD_MULTA; 
                                $element->LFD_RECMUL = $element->LFD_RECMUL == '0.00' ? "0.00" : $element->LFD_RECMUL; 
                                $element->LFD_BONIFMUL = $element->LFD_BONIFMUL == '0.00' ? "0.00" : $element->LFD_BONIFMUL; 
                            }
                            $lfMtro = LFMTRO::where('LFM_CVELIC', '=', $accountNumber)->first();
                            $lfAuxMtro = LFAUXMTRO::where('LFA_CVELIC','=',$accountNumber)->first();
                            $lfGiros = LFGIROS::where('LFG_CLAVE','=',$lfAuxMtro->LFA_CVEGIRO)->first();
                            $folderPath = public_path('assets/images/');                                    
                            $today = getdate();
                            $monthName = array("void","Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre");
                            $month = $monthName[$today['mon']];
                            $tday = $today['mday'];
                            $tyear = $today['year'];
                            $fullDate = strtotime($lfMtro['LFM_FECALT']);
                            $year = date('Y', $fullDate);
                            $monthNumber = date('m', $fullDate);
                            $day = date('d', $fullDate);
                            $createdAt = $day.'/'.$monthNumber.'/'.$year;
                            $data = array(
                                'lfMtro' => $lfMtro,
                                'lfAuxMtro' => $lfAuxMtro,
                                'lfGiros' => $lfGiros,
                                'today' => $today,
                                'month' => $month,
                                'createdAt' => $createdAt,
                                'tday' => $tday,
                                'tyear' => $tyear,
                                'folderPath' => $folderPath,
                                'lfDetLic' => $lfDetLic
                            );
                            $pdf = PDF::loadView('History.ambulante', $data);
                            $pdf->setPaper('A4', 'portrait');
                            return $pdf->stream('LFAM-'.$accountNumber.'.pdf');
                                           
                        }
                        else{
                            $errors = ErrorLog::create([
                                'users_id' => 0,
                                'owner' => 'Error',
                                'description' => 'Se ha tratado de generar un historial de un número de cuenta inválido, ya que el tipo:' . $tlicence.', el número de cuenta: '.$accountNumber.' o el token: '.$token.' no es o son válidos.'
                            ]);
                            $errors->save();
                            return redirect('error');
                        }
                    break;
        
                    case "LPO":
                        $accountStatement = AccountStatement::where('type','=',$tlicence)->where('nCuenta','=',$accountNumber)->where('token','=',$token)->get();
                        if($accountStatement->count() > 0){
                            $detPagos = DETPAGOS::where('DPA_RECIBO_OFICIAL', '=', $accountNumber)->orderBy('DPA_FECHA_DOC')->get();
                            if($detPagos != null){
                            foreach($detPagos as $key=>$element){
                                $maePagos = MAEPAGOS::where('MPA_FOLIO','=',$element->DPA_FOLIO)->get();
                                foreach($maePagos as $value){
                                    if($value->MPA_FOLCANCELA != 0 && !ctype_space($value->MPA_CANCELADA)){
                                        unset($detPagos[$key]);
                                    }
                                }
                            }
                            $laPortador = LAPortador::where('LAP_RECIBOOFICIAL', '=', $accountNumber)->first();
                            $fullDate = strtotime($laPortador['LAP_FECALT']);
                            $year = date('Y', $fullDate);
                            $monthNumber = date('m', $fullDate);
                            $day = date('d', $fullDate);
                            $createdAt = $day.'/'.$monthNumber.'/'.$year;
                            if($detPagos->count() > 0){
                                foreach($detPagos as $element){
                                    $date = new DateTime($element->DPA_FECHA_DOC);
                                    $element->DPA_FECHPAGO = $date->format('Y-m-d');
                                    $element->DPA_TOTAL = $element->DPA_TOTAL == '0.00' ? "0.00" : $element->DPA_TOTAL; 
                                    $element->DPA_PAGO = $element->DPA_PAGO == '0.00' ? "0.00" : $element->DPA_PAGO; 
                                    $element->DPA_IMPORTE = $element->DPA_IMPORTE == '0.00' ? "0.00" : $element->DPA_IMPORTE; 
                                    $element->DPA_RECARGOS = $element->DPA_RECARGOS == '0.00' ? "0.00" : $element->DPA_RECARGOS; 
                                    $element->DPA_SANCIONES = $element->DPA_SANCIONES == '0.00' ? "0.00" : $element->DPA_SANCIONES; 
                                    $element->DPA_GASTOS = $element->DPA_GASTOS == '0.00' ? "0.00" : $element->DPA_GASTOS; 
                                }
                            }
                            $folderPath = public_path('assets/images/');                                    
                            $today = getdate();
                            $monthName = array("void","Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre");
                            $month = $monthName[$today['mon']];
                            $tday = $today['mday'];
                            $tyear = $today['year'];
                            $data = array(
                                'detPagos' => $detPagos,
                                'laPortador' => $laPortador,
                                'today' => $today,
                                'month' => $month,
                                'tday' => $tday,
                                'tyear' => $tyear,
                                'createdAt' => $createdAt,
                                'folderPath' => $folderPath
                            );
                            $pdf = PDF::loadView('History.porteador', $data);
                            $pdf->setPaper('A4', 'portrait');
                            return $pdf->stream('LPO-'.$accountNumber.'.pdf');               
                            }
                        }
                        else{
                            $errors = ErrorLog::create([
                                'users_id' => 0,
                                'owner' => 'Error',
                                'description' => 'Se ha tratado de generar un historial de un número de cuenta inválido, ya que el tipo:' . $tlicence.', el número de cuenta: '.$accountNumber.' o el token: '.$token.' no es o son válidos.'
                            ]);
                            $errors->save();
                            return redirect('error');
                        }
                    break;
                    default:
                        return array();
                    break;
                }
            }
            else{
                $errors = ErrorLog::create([
                    'users_id' => 0,
                    'owner' => 'Error',
                    'description' => 'Se ha tratado de generar un historial con datos insuficientes.'
                ]);
                $errors->save();
                return redirect('error');
            }
        }
        else{
            $errors = ErrorLog::create([
                'users_id' => 0,
                'owner' => 'Error',
                'description' => 'la dirección a ingresar esta vacia y no cuenta con los valores necesarios.'
            ]);
            $errors->save();
            return redirect('error');
        }
    }
}
