<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Compras;
use App\Tipodoccompra;
use App\Tmoneda;

class ComprasCtrl extends Controller
{
    public function list() {
        $compras = Compras::with('tipodoccompra')->orderBy('id','DESC')->get();
        return $compras;
    }

   
    public function parameters() {
        $tipodoccompra = Tipodoccompra::where('enabled', '1')->orderBy('id')->get();
        //$vehiculos =Vehiculo::where('enabled', '1')->orderBy('placa')->get();
        //$remolques =Remolque::where('enabled', '1')->orderBy('placa')->get();
        return [
            'tipodoccompra' => $tipodoccompra
            //,'vehiculos' => $vehiculos,
            //'remolques'=>$remolques
        ];
    }

    public function delete($id) {
        try
        {
            $compra = Compras::find($id);

            if (is_null($compra)) {
                return [
                    'success' => false,
                    'message' => "Documento no existe!"
                ];
            } 

        
            $compra->delete();

            //Cambiar estado a 1        
            return [
                'success' => true,
                'message' => "Documento eliminado correctamente"
            ];
        }
        catch(\Exception $e)
        {
            return [
                'success' => false,
                'message' => 'Ocurrio un error al intentar eliminar el Documento',
                'error'   => $e->getMessage()
            ];
        }
    }


    public function save(Request $request) {
        try
        {
            $rules = [
                //'password' => 'required|min:8',
                'id_tipo' => 'required',
                'moneda' => 'required'
            ];

            $validator = \Validator::make($request->all(),$rules);

            if($validator->fails())
                return ['fails' => $validator->errors()->getMessages()];

                Compras::create($request->all());

            return [
                'success' => true,
                'message' => "Compra registrada correctamente"
            ];
        }
        catch(\Exception $e)
        {
            return [
                'success' => false,
                'message' => 'Ocurrio un error al intentar registrar la Compra',
                'error'   => $e->getMessage()
            ];
        }
    }

    public function savetwo(Request $request) {
        try
        {
            $v_ruc = $request->get('param1');
            $v_serie = $request->get('param2');
            $v_num = $request->get('param3');
            $usuario = $request->get('param4');

            $curl = curl_init();
            curl_setopt_array($curl, array(
                //CURLOPT_URL => 'https://api.smart-datamen.com/v2/sunat/cpe/20610087851-01-F001-00006107/json',
                CURLOPT_URL => 'https://api.smart-datamen.com/v2/sunat/cpe/'. $v_ruc.'-01-'.$v_serie.'-'.$v_num.'/json',
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => '',
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 0,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => 'GET',
                CURLOPT_HTTPHEADER => array(
                    'Authorization: Bearer O4zjLoURZtPsZHyn9bBqrwjSLdaToroypDiEclpb24ebb98c'
                ),
            ));
          
            $response_p = curl_exec($curl);
            // Check HTTP status code
            if (!curl_errno($curl)) {
                switch ($http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE)) {
                case 200:  # OK
                    $decoded_json = json_decode($response_p, true); 
                    curl_close($curl);
                   
                    if ($decoded_json['success']==true){

                        if ($decoded_json['data']['receptor']['num_doc'] == '20525787100')
                        {
                            //Seteo variables 
                            $datai = [
                                'id_tipo'=>1,
                                'fecha'=>$decoded_json['data']['comprobante']['fecha_emision'],
                                'serie'=>$decoded_json['data']['comprobante']['serie'],
                                'numero'=>$decoded_json['data']['comprobante']['correlativo'],
                                'ruc'=>$v_ruc,
                                'razonsocial'=>$decoded_json['data']['emisor']['raz_soc'],
                                'moneda'=>$decoded_json['data']['comprobante']['moneda'],
                                'baseimponible'=>$decoded_json['data']['totales']['valor'],
                                'igv'=>$decoded_json['data']['impuesto']['IGV']['total'],
                                'total'=>$decoded_json['data']['totales']['importe'],
                                'tipo_ingreso'=>'Automatico',
                                'usuario_ingreso'=>$usuario
                            ];

                            /*
                            // Validación
                            $query = Compras::where('id_tipo',1)->where('ruc',$v_ruc)->where('serie',$v_serie)->where('numero',$v_num);
                            $found = $query->first();
                            if($found) throw new \Exception("Compra ya esta registrada");
                            */

                            $query = Compras::where('id_tipo',1)->where('ruc',$v_ruc)->where('serie',$decoded_json['data']['comprobante']['serie'])->where('numero',$decoded_json['data']['comprobante']['correlativo']);
                            $found = $query->first();
                            if(!$found){
                                Compras::create($datai);
                                return [
                                'success' => true,
                                'message' => "Compra registrada correctamente " 
                                ];
                            }else{
                                return [
                                    'success' => false,
                                    'message' => "Compra ya esta registrada" 
                                    ];
                            }
                        }else{
                            return [
                                'success' => false,
                                'message' => "Documento de compra no fue emitido para TRANS CARRFRANKS EIRL"
                            ];
                        }    
                    }else{
                        return [
                            'success' => false,
                            'message' => "Documento de compra no encontrado"
                        ];
                    }          
                default:
                    return [
                        'success' => false,
                        'message' => "Ocurrio un error al intentar registrar la Compra "  . 'Unexpected HTTP code: '. $http_code
                    ];
                   
                }
            }
        }
        catch(\Exception $e)
        {
            return [
                'success' => false,
                'message' => 'Ocurrio un error al intentar registrar la Compra',
                'error'   => $e->getMessage()
            ];
        }
    }

}
