<?php

namespace App\Modules\Utilitarios\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Http\Controllers\Controller;
use App\Modules\Utilitarios\Models\Tcambio;
use App\Services\CurlService;
use Yajra\Datatables\Datatables;

class TcambioController extends Controller
{
    protected $table;
    function __construct(){
        $this->table = new Tcambio();
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {

        return view('Utilitarios.views.tcambio');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }
    /**
     * Get DataTables Data
     *
     * @return Views Data
    */
    public function getTable($search=''){
        $date = !empty($search) ? explode('/',$search) : explode('-',date('m-Y'));
        $data = $this->table::whereMonth('fecha',$date[0])->whereYear('fecha',$date[1]);
        $table = Datatables::of($data);
        $table->addColumn('action', function($row){            
            $url = url()->current().'/'.$row['id'];
            return view('layouts.buttons.buttons-dinamyc',['buttons'=> array(
                array('tipe'=>'edit',
                      'id_row'=>$row['id'],
                      'modal'=>'si',
                      'url'=>$url,
                      'class'=>" btn btn-sm  fn_edit btn-primary",
                      'icon'=>"icon-compose"
                ),
                array('tipe'=>'delete',
                      'id_row'=>$row['id'],
                      'modal'=>'no',
                      'url'=>$url,
                      'class'=>"btn btn-sm btn-danger fn_delete",
                      'icon'=>"icon-trash"
                )
            )]); 
        })->rawColumns(['action']);
        return $table->make(true);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        if ($request->has('action')) {
            switch ($request->input("action")) {
                case 'showtable':
                    if (!empty($request->input("search_fecha"))) {
                        $table = $this->getTable($request->input("search_fecha"));
                    }else{
                        $table = $this->getTable();
                    }
                    return $table;    
                break;
                case 'reload':

                    $curl = new CurlService();
                    $curl->url = 'https://incared.com/api/apirest';
                    $data = array(
                        'action' => 'getdivisaunique',
                        'fecha' => !(empty($request->input('fecha'))) ? $request->input('fecha') : ''
                    );
                    $html = $curl->requestCurl($data);
                    if ($html != 'error')  {
                        $response = json_decode($html);
                        if (isset($response->data)) {
                           foreach ($response->data as $k) {
                               $cambiog = $this->table::where('fecha',$k->fecha)->first();
                               if(!empty($cambiog)){
                                  $cambiog->fecha = $k->fecha;
                                  $cambiog->compra = $k->compra;
                                  $cambiog->venta = $k->venta;
                                  $cambiog->imp_g_ventas = '18';
                                  $cambiog->imp_s_consumo = '20';
                                  $cambiog->imp_hotelero = '10';
                                  $cambiog->renta = '8';
                                  $cambiog->save();
                               }else{
                                  $cambio = new Tcambio();
                                  $cambio->fecha = $k->fecha;
                                  $cambio->compra = $k->compra;
                                  $cambio->venta = $k->venta;
                                  $cambio->imp_g_ventas = '18';
                                  $cambio->imp_s_consumo = '20';
                                  $cambio->imp_hotelero = '10';
                                  $cambio->renta = '8';
                                  $cambio->save();
                               }
                                unset($cambiog);
                           }
                          return response()->json(['success'=>'Tipos de cambios sincronizados con exito']);
                        }else{
                           return response()->json(['error'=>$response->error]);
                        }
                    }
                break;
                case 'getcambio':
                    $fecha = !empty($request->input('fecha')) ?  $request->input('fecha') : '';
                    $cambio = $this->table::where('fecha',$fecha)->first();
                    if (!empty($cambio)) {
                        return response()->json(['cambio'=>$cambio->compra]);
                    }else{
                        return response()->json(['error'=>'No hay cambios disponibles para esta fecha '.$fecha]);
                    }
                break;
                default:

                break;
            }
        }else{
             return response()->json(['error'=>'No existe ningun token por favor no borre nuesto codigo html']);
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $data = $this->table::find($id);
        if (!empty($data)) {
            return view('Utilitarios.views.edit.cambio')->with('data',['tcambio'=>$data]);
        }else{

        }
    }

    /**
     * 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)
    {
        $data = $this->table::find($id);
        if (!empty($data)) {
            $data->fill($request->except(['action']))->save();
            return response()->json(['success'=>'Registro actualizado con exito','tablereload'=>'1']);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $data = $this->table::find($id);
        if (!empty($data)) {
            $data->delete();
            return response()->json(['success'=>'Registro eliminado con exito']);
        }
    }
}
