<?php

namespace App\Http\Controllers;
use Validator;
use Illuminate\Http\Request;
use App\Models\Document;
use Illuminate\Support\Facades\Http;
use SimpleXMLElement;
use Illuminate\Support\Str;
class DocumentController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }
    public function registerData(Request $request)
    {

        $rules = [
            'nombres' => 'required',
            'apellido_paterno'    => 'required',
            'apellido_materno' => 'required',
            'dni' => 'required',
            'date_create' => '',
            'time_create' => '',
            'valid'=>''
            
        ];
    
        $input     = $request->only('nombres', 'apellido_paterno','apellido_materno','dni');
        $validator = Validator::make($input, $rules);
    
        if ($validator->fails()) {
            return response()->json(['success' => false, 'error' => $validator->messages()]);
        }else{
     
        $document     = Document::create(['names' => $request->nombres, 'first_lastname' => $request->apellido_paterno,'second_lastname'=>$request->apellido_materno,'dni'=>$request->dni,'date_create'=>$request->date_create,'time_create'=>$request->time_create,'valid'=>$request->valid]);
        return response()->json(['success' => true, 'data' => array("id"=>$document->id)]);
        }
    }


    public function listtable(Request $request)
    {
        $document=Document::select('documents.*','usuarios.name as nameuser','usuarios.dni as dniuser')
                            ->join('usuarios','usuarios.id_user','=','documents.fk_user')
                            ->orderBy('id', 'desc')
                            ->get();
        
     
        //$document     = Document::orderBy('id', 'desc')->get();
        return response()->json($document);
        }

        public function listtablefilter(Request $request)
        {
            $document=Document::select('documents.*','usuarios.name as nameuser','usuarios.dni as dniuser')
                                
                                ->join('usuarios','usuarios.id_user','=','documents.fk_user')
                                ->whereRaw("
                                IF($request->iduser='0',fk_user,fk_user=$request->iduser)  and  IF($request->valido='2',valid=valid,valid=$request->valido)")
                                //->where(['usuarios.id_user',$request->iduser,'documents.valid',$request->estado])
                                ->orderBy('id', 'desc')
                                ->get();
            
         
            //$document     = Document::orderBy('id', 'desc')->get();
            return response()->json($document);
            }
            public function listdnifilter(Request $request)
        {
            if($request->admin){
                $document=Document::select('documents.*','usuarios.name as nameuser','usuarios.dni as dniuser')
                                
                ->join('usuarios','usuarios.id_user','=','documents.fk_user')
                ->where('documents.dni',$request->dni)
                ->orderBy('id', 'desc')
                ->get();
            }else{
                $document=Document::select('documents.*','usuarios.name as nameuser','usuarios.dni as dniuser')
                                
                ->join('usuarios','usuarios.id_user','=','documents.fk_user')
                ->where('fk_user',$request->iduser)
                ->where('documents.dni',$request->dni)
                ->orderBy('id', 'desc')
                ->get();
            }
           
            
         
            //$document     = Document::orderBy('id', 'desc')->get();
            return response()->json($document);
            }

          public function listtabledate(Request $request){
             $rules = [
                    'fechaini' => 'required',
                    'fechafin' => '',
                    'range' => 'required',
                    'admin'=>'',
                    'userid'=>''
                     ];
    
                      $input     = $request->only('fechaini','range');
                        $validator = Validator::make($input, $rules);
    
                          if ($validator->fails()) {
                         return response()->json(['success' => false, 'error' => $validator->messages()]);
                    }else{
                     if($request->range){
                         if($request->admin){
                            $document     = Document::select('documents.*','usuarios.name as nameuser','usuarios.dni as dniuser')                       
                            ->join('usuarios','usuarios.id_user','=','documents.fk_user')
                            ->whereBetween('date_create', [$request->fechaini, $request->fechafin])->orderBy('id', 'desc')->get();
                            return response()->json($document);
                         }else{
                            $document     = Document::select('documents.*','usuarios.name as nameuser','usuarios.dni as dniuser')                       
                            ->join('usuarios','usuarios.id_user','=','documents.fk_user')
                            ->where('fk_user',$request->userid)
                            ->whereBetween('date_create', [$request->fechaini, $request->fechafin])->orderBy('id', 'desc')->get();
                            return response()->json($document);
                         }
                       
                     }else{
                         if($request->admin){
                            $document     = Document::select('documents.*','usuarios.name as nameuser','usuarios.dni as dniuser')                       
                            ->join('usuarios','usuarios.id_user','=','documents.fk_user')
                         ->where('date_create', $request->fechaini)->orderBy('id', 'desc')->get();
                return response()->json($document);
                         }else{
                            $document     = Document::select('documents.*','usuarios.name as nameuser','usuarios.dni as dniuser')                       
                            ->join('usuarios','usuarios.id_user','=','documents.fk_user')
                         ->where('date_create', $request->fechaini)
                         ->where('fk_user',$request->userid)
                         ->orderBy('id', 'desc')->get();
                return response()->json($document);
                         }
                    //     $document     = Document::select('documents.*','usuarios.name as nameuser','usuarios.dni as dniuser')                       
                    //             ->join('usuarios','usuarios.id_user','=','documents.fk_user')
                    //          ->where('date_create', $request->fechaini)->orderBy('id', 'desc')->get();
                    // return response()->json($document);
                     }
                     
                  }
    }

    public function registerMobil(Request $request)
    {
        $timezone  = -5; //(GMT -5:00) EST (U.S. & Canada)
        $hora= gmdate("H:i:s", time() + 3600*($timezone+date("I")));   
        $rules = [
            'dni' => 'required',
            'foto' => '',
            'date_create'=>'',
            'time_create'=>'',
            'iduser'=>'',
            'latitude'=>'',
            'longitude'=>''
        ];
    
        $input     = $request->only('dni');
        $validator = Validator::make($input, $rules);
        
        if ($validator->fails()) {
            return response()->json(['success' => false, 'error' => $validator->messages()]);
        }else{
            $file=base64_decode($request->foto);
            $safeName = Str::random(15).'.'.'JPEG';
            
          file_put_contents(public_path().'/images/'.$safeName, $file);

            $array = array("nuRuc" => "10082439060", "coUsuario" => "09257509","nuDni" =>$request->dni,"capturaFacial" =>$request->foto,"ipCliente" =>"72.167.84.163","macCliente" => "40-8A-5C-9B-2C-77");
             


            $url = 'https://wsbiometricofacial.reniec.gob.pe/bioFacial/jaxrs-facial/verificarIdentidadFacial';
            //$myvars = '{"nuRuc":"10082439060","coUsuario":"09257509","nuDni":$request->dni,"capturaFacial":"$fotopro","ipCliente":"72.167.84.163","macCliente":"40-8A-5C-9B-2C-77"}';
            try{
            $ch = curl_init( $url );
            curl_setopt( $ch, CURLOPT_POST, 1);
            curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode($array));
            curl_setopt($ch, CURLOPT_USERPWD, "userAppNORIFEFEBAFacial:mf98Pxk0hd6gQ2021");
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, TRUE);
            //curl_setopt($ch, CURLOPT_CAINFO, '/home/i2zj71i4r01d/public_html/apireniec/certificados/devsvb.reniec.gob.pe.crt');
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            //curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
           $resulta=curl_exec($ch);
            if($resulta=== false)
            {
                echo 'Curl error: ' . curl_error($ch);
            }
            else
            {
                //echo 'Operaci贸n completada sin errores';
              
               // $resultado;
               //echo $resulta;
                $resultado = new SimpleXMLElement($resulta);
 
         if ($resultado->datos[0]=="hit") {
        //  $response = Http::withoutVerifying()->withHeaders([
        // 'Content-Type' => 'application/json;chartset=utf-8',
        // 'Requestverificationtoken' => 'Dmfiv1Unnsv8I9EoXEzbyQExSD8Q1UY7viyyf_347vRCfO-1xGFvDddaxDAlvm0cZ8XgAKTaWclVFnnsGgoy4aLlBGB5m-E8rGw_ymEcCig1:eq4At-H2zqgXPrPnoiDGFZH0Fdx5a-1UiyVaR4nQlCvYZzAhzmvWxLwkUk6-yORYrBBxEnoG5sm-Hkiyc91so6-nHHxIeLee5p700KE47Cw1'
        // ])->post('https://aplicaciones007.jne.gob.pe/srop_publico/Consulta/api/AfiliadoApi/GetNombresCiudadano',
        // [
        //     'CODDNI' => $request->dni
        // ]);
        // $data=$response['data'];
        // $nombres=explode("|", $data)[2];
        // $apellidoma=explode("|", $data)[1];
        // $apellidopa=explode("|", $data)[0];
        
        $response2["dato"]=array(
            'estado'=>strip_tags($resultado->datos[0]),
            'dni'=>strip_tags($resultado->datos[1]),
            'nombres'=>strip_tags($resultado->datos[2]),
            'apaterno'=>strip_tags($resultado->datos[3]),
            'amaterno'=>strip_tags($resultado->datos[4]),
            'fechaca'=>strip_tags($resultado->datos[5]),
             );

        $document     = Document::create(['names' => strip_tags($resultado->datos[2]), 'first_lastname' =>strip_tags($resultado->datos[3]),'second_lastname'=>strip_tags($resultado->datos[4]),'dni'=>strip_tags($resultado->datos[1]),
        'date_create'=>$request->date_create,'time_create'=>$hora,'valid'=>1,'result_reniec'=>json_encode($resultado),'fk_user'=>$request->iduser,'urlimage'=>$safeName,'latitude'=>$request->latitude,'longitude'=>$request->longitude]);
        
       
             return response()->json($response2);
        
         //echo $resultado->datos[0];
                }else{
                    // $response = Http::withoutVerifying()->withHeaders([
                    //     'Content-Type' => 'application/json;chartset=utf-8',
                    //     'Requestverificationtoken' => 'Dmfiv1Unnsv8I9EoXEzbyQExSD8Q1UY7viyyf_347vRCfO-1xGFvDddaxDAlvm0cZ8XgAKTaWclVFnnsGgoy4aLlBGB5m-E8rGw_ymEcCig1:eq4At-H2zqgXPrPnoiDGFZH0Fdx5a-1UiyVaR4nQlCvYZzAhzmvWxLwkUk6-yORYrBBxEnoG5sm-Hkiyc91so6-nHHxIeLee5p700KE47Cw1'
                    //     ])->post('https://aplicaciones007.jne.gob.pe/srop_publico/Consulta/api/AfiliadoApi/GetNombresCiudadano',
                    //     [
                    //         'CODDNI' => $request->dni
                    //     ]);
                    //     $data=$response['data'];
                    //     $nombres=explode("|", $data)[2];
                    //     $apellidoma=explode("|", $data)[1];
                    //     $apellidopa=explode("|", $data)[0];
                    $response2["dato"]=array(
                        'estado'=>strip_tags($resultado->datos[0]),
                          'dni'=>strip_tags($resultado->datos[1]),
                        // 'nombres'=>$resultado->datos[2],
                        // 'apaterno'=>$resultado->datos[3],
                        // 'amanterno'=>$resultado->datos[4],
                        // 'fechaca'=>$resultado->datos[5],
                         );
                        $document     = Document::create(['names' => '', 'first_lastname' =>'','second_lastname'=>'','dni'=>strip_tags($resultado->datos[1]),'date_create'=>$request->date_create,
                        'time_create'=>$hora,'valid'=>0,'result_reniec'=>json_encode($resultado),'fk_user'=>$request->iduser,'urlimage'=>$safeName,'latitude'=>$request->latitude,'longitude'=>$request->longitude]);
                
//echo $resultado->datos[0];
                
                
             return response()->json($response2);
                }
            }
             
            // Cerrar recurso
            curl_close($ch);
            
            }catch(Exception $e){
                echo $e;
            }      
        }
    }


    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
