<?php

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

class DivisasController extends Controller
{    
    protected $table;
    function __construct(){
        $this->middleware('auth');
        $this->table = new Divisa();
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('Utilitarios.views.divisas')->with('title','hola');
    }
    /**
     * Display a listing of the datatables list.
     *
     */
    public function getTable()
    {   
        $table = Datatables::of($this->table::all());
        $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"
                ),
                array('tipe'=>'edit',
                      'id_row'=>$row['id'],
                      'modal'=>'no',
                      'url'=>$url,
                      'class'=>"btn btn-sm btn-warning fn_divisa",
                      'icon'=>"icon-coin-dollar"
                )
            )]); 
        })->rawColumns(['action']);
        return $table->make(true);
    }
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {

    }

    /**
     * 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':
                   return $this->getTable();
                break;
                case 'add':     
                    $validator = Validator::make($request->all(),[
                        'divisa' => 'required',
                        'venta' => 'required',
                        'compra' => 'required',
                    ]);
                   if ($validator->fails()) {
                       return response()->json(['error'=>$validator->errors()->all()]);
                    }else{
                        if ($this->table::where('divisa', '=', $request->input("divisa"))->count() > 0) {
                           return response()->json(['error'=>'Esta divisa ya existe']);
                        }else{
                            $this->table->fill($request->except(['action']))->save();
                            return response()->json(['success'=>'Registro agregado con exito','tablereload'=>'reload']);
                        }
                    }
                break;
                case 'reload_divisa':
                    $curl = new CurlService();
                    $curl->url = 'https://incared.com/api/apirest';
                    $data = array(
                        'action' => 'getdivisa',
                        'fecha' => date('Y/m/d'),
                    );
                    $html = $curl->requestCurl($data);
                    if ($html != 'error')  {
                        $response = json_decode($html);
                        return response()->json(['success'=>'Solicitud aceptada con exito','divisa'=>$response]);
                    }
                break;
                default:
                    # code...
                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.divisa')->with('data',['divisa'=>$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)
    {
        if ($request->has('action')) {
            $divisa = $this->table::find($id);
            switch ($request->input('action')) {
                case 'view':
                    $curl = new CurlService();
                    $curl->url = 'https://incared.com/api/apirest';
                    $data = array(
                        'action' => 'getdivisa',
                        'fecha' => date('Y/m/d'),
                    );
                    $html = $curl->requestCurl($data);
                    $data = json_decode($html);
                    if ($html != 'error')  {
                        if (!empty($data->error)) {
                            return response()->json(['error'=>$data->error]);
                        }else{
                            if (!empty($divisa)) {
                                $divisa->venta = $data->venta;
                                $divisa->compra = $data->compra;
                                $divisa->save();
                            }   
                            return response()->json(['success'=>'Registro actualizado con exito','tablereload'=>'1']);
                        }
                    }
                break;
                case 'form':
                    if(!empty($divisa)){
                        $divisa->fill($request->except(['action']))->save();
                        return response()->json(['success'=>'Registro actualizado con exito','tablereload'=>'1']);
                    }
                break;
            }
        }
    }

    /**
     * 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']);
        }
    }
}
