<?php

namespace App\Http\Controllers\Api;

use App\listadoServicios;
use App\PolizaSt;
use App\Registro;
use App\RegistroServicio;
use App\Servicio;
use App\Status;
use App\Tramites;
use App\VentaPoliza;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Config;
use JWTAuth;
use App\Sucursales;
use App\Promotoria;
use App\General;
use App\Enteros;
use App\PagosBancarios;
use App\Cobertura;
use App\Venta;
use App\Reason;
use App\Revocations;
use App\Cobranza;
use App\Poliza;
use App\Agente;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Auth;

class SstController extends Controller
{
    public function config(){
        $user = JWTAuth::parseToken()->authenticate();
        $permissionFlag = false;
        $roles = $user -> roles() -> get();
        foreach($roles as $role){
            $permissios = $role ->  permissions() -> where('name','use-api-as-admin')-> get();
            if(! $permissios -> isEmpty())
                $permissionFlag = true;
        }
        if($permissionFlag){
            $promotoria = Promotoria::where('status',1) -> where('id',$user -> promotoria_id)-> first();
            if($promotoria){

                $sucursal = Sucursales::where('id',$user -> sucursal_id)->first();
                if($sucursal){
                    if($sucursal -> status == 1){
                        $v = $sucursal->ventanillas() -> lists('nombre');
                        return response()->json(["validates" => true, "active" => true,"promotoriaId" => $promotoria->id,
                            "promotoria" => $promotoria->razonSocial,
                            "branchId" => $sucursal->id, "urlLogo" => 'images/promotoria/'.$promotoria ->logo, "windows" => $v]);
                    }else{
                        return response()->json(["validates" => false, "active" => true, "promotoriaId" => 0, "branchId" => 0, "urlLogo" => ""]);
                    }
                }else{
                    return response()->json(["validates" => false, "active" => true, "promotoriaId" => 0, "branchId" => 0, "urlLogo" => ""]);
                }

            }else{
                return response()->json(["validates" => false, "active" => false, "promotoriaId" => 0, "branchId" => 0, "urlLogo" => ""]);
            }

        }else{
            return response()->json(['message' => "Usuario inválido.", 'code' => 404],300);

        }
    }



    public function changeConnection($promotoria_id){
        $promotoria = Promotoria::find($promotoria_id);
        if($promotoria){
        if($promotoria -> dbConnection === NULL||$promotoria -> username  === NULL|| $promotoria -> password === NULL || empty($promotoria -> dbConnection) || empty($promotoria -> username) || empty($promotoria -> password))
            return false;
        else{
            Config::set('database.connections.external',array(
                'driver'    => 'mysql',
                'host'      => $promotoria -> dbConnection,
                 'database'  => $promotoria -> clave.'_bases_expulse',
                'username'  => $promotoria -> username,
                'password'  => $promotoria -> password,
                'charset'   => 'utf8',
                'collation' => 'utf8_unicode_ci',
                'prefix'    => '',
                'strict'    => false,
            ));

            Config::set('database.connections.cobranza',array(
                'driver'    => 'mysql',
                'host'      => $promotoria -> dbConnection,
               'database'  => $promotoria -> clave.'_cobranza',
                'username'  => $promotoria -> username,
                'password'  => $promotoria -> password,
                'charset'   => 'utf8',
                'collation' => 'utf8_unicode_ci',
                'prefix'    => '',
                'strict'    => false,
            ));
            return true;
        }

        }else{
            return false;
        }
    }

    public function getProcedures(){
        $user = JWTAuth::parseToken()->authenticate();
        $permissionFlag = false;
        $roles = $user -> roles() -> get();
        foreach($roles as $role){
            $permissios = $role ->  permissions() -> where('name','use-api-as-admin')-> get();
            if(! $permissios -> isEmpty())
                $permissionFlag = true;
        }
        if($permissionFlag) {
             $response = array();
              $tramites = Tramites::where('promotoria_id',$user -> promotoria_id) -> get();

            foreach($tramites as $tramite){
                $docs = $tramite -> documentos() -> get() -> lists('nombre');
                $response[] = array('procedureId' => $tramite->id, 'procedureName' => $tramite->nombre,
                    'prefix' => $tramite->prefijo, 'documents' => $docs, 'payOrder' => $tramite->payOrder, 'is_registro' => $tramite->is_registro, );
            }
            return response() -> json($response);
        }else{
            return response()->json(['message' => "Usuario inválido.", 'code' => 404],300);
        }
    }

    public function getPayOrderData($policie){

        $user = JWTAuth::parseToken()->authenticate();
        if(!$this->changeConnection($user -> promotoria_id))
            return response()->json(['message' => "Error de conexión."],404);

        $permissionFlag = false;
        $roles = $user -> roles() -> get();
        foreach($roles as $role){
            $permissios = $role ->  permissions() -> where('name','use-api-as-admin')-> get();
            if(! $permissios -> isEmpty())
                $permissionFlag = true;
        }

        if($permissionFlag) {
            $poliza  =  Poliza::select('NOMBRE','AP_PATERNO','AP_MATERNO') ->where('POLIZA',$policie) -> first();
            $servicio =Servicio::select('num_cheque') ->where('poliza',$policie)  -> where('con_cheque',3) -> orderBy('fecha_sol','DESC') -> first();
            if($poliza && $servicio){
                 return response()->json('Estimado '.str_replace(' ', '', $poliza -> NOMBRE) .' '.str_replace(' ', '', $poliza -> AP_PATERNO) . ' '. str_replace(' ', '', $poliza -> AP_MATERNO) .' \r\n SU ORDEN DE PAGO ESTÁ LISTA \r\n por favor acuda a su sucursal Banamex más \r\n cercana \r\n\r\n  - ' . $servicio -> num_cheque . '   \r\n Es necesario presentar su identificación \r\n oficial \r\n  Este trámite fue realizado en su póliza '.$policie);
            }else{
                return response()->json(['message' => "La póliza ". $policie. " no cuenta con una orden de pago por el momento."],410);
            }
        }else{
            return response()->json(['message' => "Usuario inválido."],404);
        }
    }

    public function startProcedureAttention(Request $request){
        $user = JWTAuth::parseToken()->authenticate();
        $permissionFlag = false;
        $roles = $user -> roles() -> get();
        foreach($roles as $role){
            $permissios = $role ->  permissions() -> where('name','use-api-as-agent')-> get();
            if(! $permissios -> isEmpty())
                $permissionFlag = true;
        }
        if($permissionFlag) {

            $params = $request->only('procedureId', 'date', 'turnId','promotoriaId','externalTurn','policy');
            if($params['procedureId'] === NULL || $params['date'] === NULL || $params['externalTurn'] === NULL)
                return response()->json(['message' => 'erroro']);
            else{
                $registro = Registro::with('usuarios') -> where('id',$params['externalTurn'])  ->   where('sucursal_id',$user -> sucursal_id) ->first();
                if($registro){
                    if(!$registro-> usuarios -> contains($user -> id)){
                        $registro-> usuarios() -> attach($user -> id);

                    }
       	 return response()->json(['message' => 'success','externalTurn' => $registro -> id]);
                }else{
                    $data = Registro::create([
                        'sucursal_id' => $user -> sucursal_id,
                        'order_id' => $params['turnId'].date('Ymd'),
 	                    'tramite_id' => $params['procedureId'],
                        'date'       => $params['date'],
                        'policy_id' => $params['policy'],
                    ]);

                    $data-> usuarios() -> attach($user -> id);
                   return response()->json(['message' => 'success','externalTurn' => $data -> id]);
                }




            }
        }else{
            return response()->json(['message' => "Usuario inválido.", 'code' => 404],404);
        }
    }

    public function stopProcedureAttention(Request $request){
        $user = JWTAuth::parseToken()->authenticate();
        $permissionFlag = false;
        $roles = $user -> roles() -> get();
        foreach($roles as $role){
            $permissios = $role ->  permissions() -> where('name','use-api-as-agent')-> get();
            if(! $permissios -> isEmpty())
                $permissionFlag = true;
        }

        if($permissionFlag) {
            $params = $request->only('procedureId', 'date', 'turnId', 'time','externalTurn','policy');
            if($params['externalTurn'] === NULL || $params['time'] === NULL || $params['time']=='') {
                return response()->json(['message' => 'error']);
            }else{
                $registro = Registro::where('id',$params['externalTurn']) ->   where('sucursal_id',$user -> sucursal_id) -> orderBy('id','DESC') -> first();


                if($registro){
                    $registro->update([
                        'service_time' =>  date('H:i:s',$this->sum_the_time($registro -> service_time,$params['time']))
                    ]);
                    return response()->json(['message' => 'success']);

                }else{
                    return response()->json(['message' => 'error'],404);
                }
            }
        }else{
            return response()->json(['message' => "Usuario inválido.", 'code' => 404],404);
        }
    }

    public function startResumenReasons(Request $request){
        $user = JWTAuth::parseToken()->authenticate();
        $permissionFlag = false;
        $roles = $user -> roles() -> get();
        foreach($roles as $role){
            $permissios = $role ->  permissions() -> where('name','use-api-as-admin')-> get();
            if(! $permissios -> isEmpty())
                $permissionFlag = true;
        }

        if ($permissionFlag)
        {
            //var_dump($request["tabla"]);
            $Revocation = array();
            $Revocations = json_decode($request["tabla"]);
            for ($i=0;$i<sizeof($Revocations);$i++)
            {
                $Revocation[$i]=json_encode($Revocations[$i]);
            }

            for ($i=0;$i<sizeof($Revocation);$i++) {

                $RevocationData = json_decode($Revocation[$i], true);
                //echo "SERVER ".$i;
                Revocations::create($RevocationData);
            }
            /*foreach ($RevocationData as $data){
                $relacionMotivo = new Revocations;
                $relacionMotivo -> idReason = $data['idReason'];
                $relacionMotivo -> dateTime_create = $data['dateTime_create'];
                $relacionMotivo -> action = $data['action'];
                $relacionMotivo -> turn = $data['turn'];
                $relacionMotivo -> idTramite = $data['idTramite'];
                $relacionMotivo -> adviser = $data['adviser'];
                $relacionMotivo -> save();
            }*/
            //dd($RevocationData);
            //
            //DB::table('revocations')->insert($Revocations);

            /*foreach($Revocations as $clave => $vl)
            {*/
                /*foreach($valor as $vl){
                    dd($vl);*/
                        /*$relacionMotivo = new Revocations;
                        $relacionMotivo -> setAttribute($vl);
                        $relacionMotivo -> dateTime_create = $vl->dateTime_create;
                        $relacionMotivo -> action = $vl->action;
                        $relacionMotivo -> turn = $vl->turn;
                        $relacionMotivo -> idTramite = $vl->idTramite;
                        $relacionMotivo -> adviser = $vl->adviser;
                        $relacionMotivo -> save();*/
                    //}
            //}

            /*if (!empty($relacionMotivo))
            {
                return response()->json($relacionMotivo);
            }else {
                return response() -> json(['message' => 'error'],500);
            }*/
        }

    }

    public function sum_the_time($time1, $time2) {
        $times = array($time1, $time2);
        $seconds = 0;
        foreach ($times as $time)
        {
            list($hour,$minute,$second) = explode(':', $time);
            $seconds += $hour*3600;
            $seconds += $minute*60;
            $seconds += $second;
        }
        $hours = floor($seconds/3600);
        $seconds -= $hours*3600;
        $minutes  = floor($seconds/60);
        $seconds -= $minutes*60;
         return strtotime($hours.':'.$minutes.':'.$seconds);
     }

    public function getCustomersByName($name){
        $user = JWTAuth::parseToken()->authenticate();
        if(!$this->changeConnection($user -> promotoria_id))
                 return response()->json(['message' => "Error de conexión."],404);
        $permissionFlag = false;
        $roles = $user -> roles() -> get();
        foreach($roles as $role){
            $permissios = $role ->  permissions() -> where('name','use-api-as-admin')-> get();
            if(! $permissios -> isEmpty())
                $permissionFlag = true;
        }
        if($permissionFlag) {
            $clientes = General::select('nombre','rfc')
                ->where('nombre','LIKE','%'.$name.'%')
                ->orWhere('rfc','LIKE','%'.$name.'%')
                ->orWhere('poliza','LIKE','%'.$name.'%')
                ->groupBy(DB::raw('SUBSTRING(rfc,1,10)'))
                ->orderBy('nombre','desc')->get();
            $response = array();
            foreach($clientes as $cliente){
              $polizas = Poliza::select('POLIZA as policie','PLAN as plan','cartera_ml_pol.ESTATUS as vigente',DB::raw('CONCAT(cartera_ml_pol.ESTATUS, ".", st_desc) AS status'),DB::raw('"'. $cliente -> nombre .'" AS customerName'))
                -> where('RFC','LIKE','%'.substr($cliente -> rfc,0,10).'%')
                -> leftJoin('status','status.cve_st','=','cartera_ml_pol.ESTATUS')
                -> groupBy('POLIZA')  ->get();
                $response[] =  array('RFC' => $cliente -> rfc, 'customerName' => $cliente -> nombre,'policies' => $polizas);
            }
            return response() -> json($response);

        }else{
            return response()->json(['message' => "Usuario inválido.", 'code' => 404]);
        }
    }

    public function reasonDeclined(){
        $data = Reason::select('id','name')->get();
        if(!empty($data)){
            return response() -> json($data);
        }else{
            return response() -> $this->json([]);
        }
    }



    public function url(){
        $user = JWTAuth::parseToken()->authenticate();
        if(!$this->changeConnection($user -> promotoria_id))
                   return response()->json(['message' => "Error de conexión."],404);
        $permissionFlag = false;
        $roles = $user -> roles() -> get();
        foreach($roles as $role){
            $permissios = $role ->  permissions() -> where('name','use-api-as-admin')-> orWhere('name','use-api-as-agent') -> get();
            if(! $permissios -> isEmpty())
                $permissionFlag = true;
        }
        if($permissionFlag){
            $data = Input::all();
            $servicio  = listadoServicios::all();
            $servicios = $servicio -> lists('descripcion','clave');
            return view('cartera.main',compact('servicios'));
        }else{
            return response()->json(['message' => "Usuario inválido.", 'code' => 404]);

        }
    }




    public function results(){
        $data = Input::all();
        $user = JWTAuth::parseToken()->authenticate();
        if(!$this->changeConnection($user -> promotoria_id))
                    return response()->json(['message' => "Error de conexión."],404);
        if(!empty($data['searchParameter'])){

            $results =PolizaSt::where('POLIZA','LIKE','%'.$data['searchParameter'].'%')
                -> orWhere('RFC','LIKE','%'.$data['searchParameter'].'%')
                -> orWhere('NOMBRE','LIKE','%'.$data['searchParameter'].'%')
                -> get();
            return view('cartera.results',compact('results'));
        }

    }

    public function storeService(){
        $data = Input::all();
        $user = JWTAuth::parseToken()->authenticate();
        $registroServicio = new RegistroServicio();
        $registroServicio -> observacion = $data['observations'];
        $registroServicio -> clave = $data['clave'];
        $registroServicio -> servicio = $data['servicio'];
        $registroServicio -> record_id= $data['record_id'].date('Ymd');
        $registroServicio -> sucursal_id = $user -> sucursal_id;
        $registroServicio -> save();
    }


    public function cartera(){
        $data = Input::all();
        $subret = '';
         $user = JWTAuth::parseToken()->authenticate();
        if(!$this->changeConnection($user -> promotoria_id))
                  return response()->json(['message' => "Error de conexión."],404);

        if(!empty($data['policy'])){
            //busqueda por nombre

            $token = $data['token'];



            $general =  General::select('*') -> leftJoin('cartera_ml_polst','cartera_ml_polst.POLIZA','=','datosgrals.poliza') ->where('datosgrals.poliza',$data['policy']) -> first();
            $poliza = PolizaSt::select('*',DB::raw('PRIMA_COBRO/FORMA_PAGO/2 AS PRIMA_Q')) -> where('poliza',$data['policy']) -> first();
            $status = Status::where('cve_st',$poliza -> ESTATUS) -> first();
            $coberturas = Cobertura::where('poliza',$data['policy']) -> get();
            $afeccion_primas = Poliza::where('poliza',$data['policy']) -> where('CLAVE_SERV','<>','2216')  ->orderBy('FECHA_EMI', 'desc')  ->  get();
            $ventaPolizas = DB::connection('external')  -> table('solypol') ->  select('*',DB::raw('CONVERT(fol_envio,char) as fo')) -> where('poliza',$data['policy'])  ->join('estatusmet', 'solypol.estatusmet', '=', 'estatusmet.estatusmet');
            $incrementos =  DB::connection('external') ->table('inc_2208') ->  select('*',DB::raw('CONVERT(fol_envio,char) as fo')) -> where('poliza',$data['policy'])  ->join('estatusmet', 'inc_2208.estatusmet', '=', 'estatusmet.estatusmet');
            $inclusiones = DB::connection('external') ->table('inc_2240') ->  select('*',DB::raw('CONVERT(fol_envio,char) as fo')) -> where('poliza',$data['policy'])    ->join('estatusmet', 'inc_2240.estatusmet', '=', 'estatusmet.estatusmet');
            $ventas = $ventaPolizas -> union($inclusiones) -> union($incrementos)  -> orderBy('fe_emision', 'desc') -> get();
            $servicios_internos = DB::connection('external') -> table('servicio')
                -> join('agentes','agentes.Agente','=','servicio.agente')
                -> where('poliza',$data['policy'])
                -> orderBy('fecha_cap','desc')
                -> get();
            $serv =Servicio::where('poliza',$data['policy']) -> get() -> lists('no_solicitud') -> toArray();

            $serv_pendientes = DB::connection('external')  ->table('folios_desgloce') -> select('folios_desgloce.fe_captura','folios_desgloce.clave_serv','listado_serv.descripcion','agentes.nombre as nombre','folios.agente','folios_desgloce.nombre as asegurado')
                -> join('folios','folios.folio','=','folios_desgloce.folio')
                -> leftJoin('agentes','agentes.agente','=','folios.agente')
                -> leftJoin('listado_serv','listado_serv.clave','=','folios_desgloce.clave_serv')
                -> where('folios.tipo','3')
                -> where('folios_desgloce.poliza',$data['policy'])
                -> whereNotIn('folios_desgloce.no_solicitud',$serv)
                -> get();
            $enteros = Enteros::select(DB::raw('Poliza','Prima','RFC','sum(Prima) AS primatotal','COUNT(Prima) AS totalmovi')) ->where('poliza',$data['policy']) -> get();
            $pagos_cobranza = PagosBancarios::select(DB::raw('poliza','importe','sum(importe) AS primatotal','COUNT(importe) AS totalmovi'),'tarjeta','status') -> where('poliza',$data['policy']) -> get();
            $historico_cancelaciones = DB::connection('cobranza') ->  table('polizas_canceladas') -> where('poliza',$data['policy']) -> get();
            $cobranza = Cobranza::where('poliza',$data['policy'])-> first();
            if($cobranza)
                $subret = DB::connection('external') -> table('subret') ->  select('Descripcion') -> where('subret',$cobranza -> Subret) -> first();
            $ultima_carga = DB::connection('external')  -> table('cartera_archivos') -> select(DB::raw('DATE_FORMAT(`fechahora`,"%m-%Y") as fecha')) -> where('status',1) -> orderBy('fechahora','desc') -> first();
            switch ($poliza -> FORMA_PAGO)
            {
                case 1:$forma_pago="Mensual";break;
                case 3:$forma_pago="Trimestral";break;
                case 6:$forma_pago="Semestral";break;
                case 12:$forma_pago="Anual";break;
                default:$forma_pago="";break;
            }
            return view('cartera.cartera',compact('token','general','status','poliza','coberturas',
                'afeccion_primas','ventas','servicios_internos',
                'serv_pendientes','enteros','pagos_cobranza',
                'cobranza','forma_pago','ultima_carga','historico_cancelaciones','subret'));
        }else{
            return view('cartera.error');
        }
    }

    public function detalle(){
        $data = Input::all();
        $user = JWTAuth::parseToken()->authenticate();
        if(!$this->changeConnection($user -> promotoria_id))
                   return response()->json(['message' => "Error de conexión."],404);
        if(!empty($data['venta'])){
            $token = $data['token'];
         //   return response() -> json($data);
            $ventaPolizas = DB::connection('external') -> table('solypol') -> select('*',DB::raw('CONVERT(fol_envio,char) as fo')) ->  where('poliza',$data['policy'])  -> where('id_venta',$data['venta'])  ->join('estatusmet', 'solypol.estatusmet', '=', 'estatusmet.estatusmet');
            $incrementos =  DB::connection('external') ->table('inc_2208') ->  select('*',DB::raw('CONVERT(fol_envio,char) as fo')) ->where('poliza',$data['policy'])  -> where('id_venta',$data['venta'])  ->join('estatusmet', 'inc_2208.estatusmet', '=', 'estatusmet.estatusmet');
            $inclusiones = DB::connection('external') ->table('inc_2240') -> select('*',DB::raw('CONVERT(fol_envio,char) as fo')) -> where('poliza',$data['policy'])   -> where('id_venta',$data['venta'])  ->join('estatusmet', 'inc_2240.estatusmet', '=', 'estatusmet.estatusmet');
            $venta = $ventaPolizas -> union($inclusiones) -> union($incrementos)   -> orderBy('fe_emision', 'desc');
            $venta =$venta -> first();
            $status = Status::where('cve_st',$venta -> estatus) -> first();
            $agente = Agente::where('Agente',$venta -> num_agente) -> first();
            $coberturas = DB::connection('external') ->table('historico_cob') -> where('historico_cob.folio',$venta -> fo) -> get();
            $general =  General::where('poliza',$venta -> poliza) -> first();
            $ult_agente = Agente::where('Agente',$general ->ult_agente) -> first();
            $cuestionarios = DB::connection('external') -> table('historico_cuest') -> select('historico_cuest.id_pregunta','cuest_preguntas.pregunta','historico_cuest.respuesta','historico_cuest.rol')
                -> join('cuest_preguntas','cuest_preguntas.id_pregunta','=','historico_cuest.id_pregunta')
                -> where('historico_cuest.folio_des',$venta -> fo)
                -> orderBy('historico_cuest.id_pregunta','asc')
                -> get();
            switch ($general -> estado_civil)
            {
                case 'C':$estado_civil="CASADO";break;
                case 'D':$estado_civil="DIVORCIADO";break;
                case 'S':$estado_civil="SOLTERO";break;
                case 'v':$estado_civil="VIUDO";break;
                case 'U':$estado_civil="UNION LIBRE";break;
                default:$estado_civil="";break;
            }
            return view('cartera.detalle_venta.main',compact('venta','agente','status','coberturas','cuestionarios','general','ult_agente','token','estado_civil'));
        }else{
            return response() -> json(['message' => 'parameters missing']);
        }
    }

    public function detalleServicio(){
        $data = Input::all();
        $user = JWTAuth::parseToken()->authenticate();
        if(!$this->changeConnection($user -> promotoria_id))
                  return response()->json(['message' => "Error de conexión."],404);
        $servicio = DB::connection('external') -> table('servicio')
            -> select('*',DB::raw('date(fecha_carga) as fe_carga'))
            -> join('agentes','agentes.Agente','=','servicio.agente')
            -> where('id_servicio',$data['id_servicio'])
            -> orderBy('fecha_cap','desc')
            -> first();
        $servicio_com = DB::connection('external') -> table('servicio_comentarios') -> where('id_servicio',$servicio -> id_servicio) -> first();

        return view('cartera.servicio.detalle_servicio',compact('servicio','servicio_com'));
    }

    public function getPayOrderDataDemo($policie){
        $user = JWTAuth::parseToken()->authenticate();
        if(!$this->changeConnection($user -> promotoria_id))
            return response()->json(['message' => "Error de conexión."],404);

        $permissionFlag = false;
        $roles = $user -> roles() -> get();
        foreach($roles as $role){
            $permissios = $role ->  permissions() -> where('name','use-api-as-admin')-> get();
            if(! $permissios -> isEmpty())
                $permissionFlag = true;
        }

        if($permissionFlag) {
            $poliza  =  Poliza::select('NOMBRE','AP_PATERNO','AP_MATERNO') ->where('POLIZA',$policie) -> first();
            $servicio =Servicio::select('num_cheque') ->where('poliza',$policie)  -> where('con_cheque',3) -> orderBy('fecha_sol','DESC') -> first();
            if($poliza && $servicio){
                return response()->json(array(
                                               'customer'     =>str_replace(' ', '', $poliza -> NOMBRE) .' '.str_replace(' ', '', $poliza -> AP_PATERNO) . ' '. str_replace(' ', '', $poliza -> AP_MATERNO),
                                               'check_number' =>'1ORD'.' '.$servicio -> num_cheque,
                                               'policy'       =>$policie
                                             )

                                        );
            }else{
                return response()->json(['message' => "La póliza ". $policie. " no cuenta con una orden de pago por el momento."],410);
            }
        }else{
            return response()->json(['message' => "Usuario inválido."],404);
        }
    }

}
