<?php

namespace App\Modules\Visitas\Controllers;
use App\Modules\Visitas\Models\Visita;
use App\Modules\Visitas\Models\Empleado;
use App\Modules\Visitas\Models\Oficina;
use App\Modules\Visitas\Models\Motivo;
use App\Modules\Visitas\Models\Sede;
use App\Modules\Catalogo\Models\Entidad;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Yajra\Datatables\Datatables;
use Storage;
use DB;
use Auth;
class VisitasController extends Controller
{
    protected $table;
    protected $table_e;
    protected $table_o;
    protected $table_en;
    protected $table_pivot = 'herramientas';
    function __construct(){
        $this->table = new Visita();
        $this->table_e = new Empleado();
        $this->table_o = new Oficina();
        $this->table_m = new Motivo();
        $this->table_s = new Sede();
        $this->table_en = new Entidad();
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {   
      return view('Visitas.views.visitas');
    }

    public function index_public()
    {   
      return view('Visitas.views.visitas_public');
    }
    /**
     * Display a listing of the datatables list.
     *
     */
    public function getTable($data)
    {     
        $bettwen = $this->table->show_all_full($data);
        $table = Datatables::of($bettwen);
        $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'=>'no',
                      'url'=>$url.'/edit',
                      'class'=>" btn btn-primary  btn-sm",
                      'icon'=>"icon-compose"
                ),
                array('tipe'=>'view',
                      'id_row'=>$row['id'],
                      'modal'=>'no',
                      'url'=>$url,
                      'class'=>" btn btn-info  btn-sm",
                      'icon'=>"icon-eye"
                ),
                array('tipe'=>'delete',
                      'id_row'=>$row['id'],
                      'modal'=>'no',
                      'url'=>$url,
                      'class'=>"btn btn-danger fn_delete btn-sm",
                      'icon'=>"icon-trash"
                )
            )]);
        })->addColumn('marcar', function($row){
            if (empty($row['hora_salida'])) {
               return '<a href="#" class="btn btn-primary btn-sm" data-id="'.$row['id'].'" onclick="marcar_salida(this); return false">Marcar</a>';
            }else{
                return $row['hora_salida'];
            }
        })->addColumn('foto',function($row){
            if (!empty($row['src_foto'])) {
                return '<a href="#" id="modal_foto" data-id="'.$row['id'].'" onclick="ajax_modal(this); return false"><i class="icon-image4"></i></a>';
            }
        })->rawColumns(['action','marcar','foto']);
        return $table->make(true);
    }
        public function getTable_public($data)
    {     
        $bettwen = $this->table->show_all_full($data);
        $table = Datatables::of($bettwen);
        $table->addColumn('marcar', function($row){
            return $row['hora_salida'];
            
        })->addColumn('foto',function($row){
            if (!empty($row['src_foto'])) {
                return '<a href="#" id="modal_foto" data-id="'.$row['id'].'" onclick="ajax_modal(this); return false"><i class="icon-image4"></i></a>';
            }
        })->rawColumns(['action','marcar','foto']);
        return $table->make(true);
    }
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $empleados = $this->table_e::all();
        $entidad = $this->table_en::all();
        $oficinas = $this->table_o::all();
        $motivo = $this->table_m::all();
        $sedes = $this->table_s::all();
        return view('Visitas.views.add.visita')->with('data',[
          'empleados'=>$empleados,
          'oficinas'=>$oficinas,
          'entidad'=>$entidad,
          'motivos'=>$motivo,
          'sedes'=>$sedes
        ]);
    }

    /**
     * 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 (Auth::check()) {
                 
                    return $this->getTable($request->all());
                  }else{
                    return $this->getTable_public($request->all());
                  }
                break;
                case 'add':
                    $validator = Validator::make($request->all(),[
                        'nombre' => 'required',
                        'dni' => 'required',
                        'entidad_id'=> 'required',
                        'motivos_id'=> 'required'
                    ]);
                     if ($validator->fails()) {
                       return response()->json(['error'=>$validator->errors()->all()]);
                    }else{
                        $visita =$request->except(['action','herramienta','htrabajo','mtrabajo','strabajo']);
                        if ($request->has('src_foto')) {
                            if(!Storage::disk('public_uploads')->has('Visitas')){
                                Storage::disk('public_uploads')->makeDirectory('Visitas');
                            }
                            $img = $visita['src_foto'];
                            $img = str_replace('data:image/png;base64,', '', $img);
                            $img = str_replace(' ', '+', $img);
                            $data = base64_decode($img);
                            $im = imagecreatefromstring($data);  //convertir text a imagen
                            if ($im !== false) {
                                imagejpeg($im, public_path().'/storage/Visitas/'.$visita['dni'].time().'.jpg'); //guardar a server 

                                imagedestroy($im); //liberar memoria  
                                $visita['src_foto'] = $visita['dni'].time().'.jpg';
                            }else {
                                //echo "Error al subir la imagen";
                            }
                        }
                        $visita['fecha'] = now();
                        $this->table->fill($visita)->save();
                        if ($request->has('herramienta')) {
                           $herramienta = $request->all();
                            if ($herramienta['herramienta'] != 'no') {                
                                for ($i=0; $i <count($herramienta['htrabajo']) ; $i++) { 
                                    $this->table->nombre = $herramienta['htrabajo'][$i];
                                    $this->table->marca = $herramienta['mtrabajo'][$i];
                                    $this->table->serial = $herramienta['strabajo'][$i];
                                    $this->table->insert_utilitarios();
                                }
                            }
                        }

                        $request->session()->flash('create', 'Registro agregado con exito!');
                        return response()->json(['success'=>'Registro agregado con exito','url'=>url('visitas')]);
                    }
                break;
                case 'marcar':
                   $datos = $request->all();
                   $data = $this->table::find($datos['id']);
                   if (!empty($data)) {
                       $data->hora_salida = date('h:i:s A');
                       $data->save();
                       return response()->json(['success'=>'Visita agregada con exito']);
                   }
                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)
    {

        if (substr($id, 0,5) == 'modal') {   
            $modal = explode('&', $id);
            $data = $this->table::find($modal[1]);
            if (!empty($data)) {
                return view('Visitas.views.utilitarios.foto')->with('data',$data);
            }
        }else{
            $visita = $this->table->show_all($id);
            $herramienta = $this->table->get_by_id_utilitarios($id);
            return view('Visitas.views.view.visitas',['visita'=>$visita,'herramientas'=>$herramienta]);
        }

    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {   
        $empleados = $this->table_e::all();
        $entidad = $this->table_en::all();
        $oficinas = $this->table_o::all();
        $visita = $this->table::find($id);
        $motivo = $this->table_m::all();
        $sedes = $this->table_s::all();

        $herramientas = $this->table->get_utilitarios($id);
        return view('Visitas.views.edit.visitas')->with('data',
        ['empleados'=> $empleados,
         'entidad' => $entidad,
         'oficinas' => $oficinas,
         'visita' => $visita,
         'herramientas' => $herramientas,
         'motivos'=>$motivo,
         'sedes'=>$sedes
        ]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
       $validator = Validator::make($request->all(),[
                      'nombre' => 'required',
                      'dni' => 'required',
                      'entidad_id'=> 'required',
                      'motivos_id'=> 'required'
                  ]);
        if ($validator->fails()) {
           return response()->json(['error'=>$validator->errors()->all()]);
        }else{
          $visita = $this->table::find($id);
          $data = $request->except(['action','herramienta','htrabajo','mtrabajo','strabajo','idherramienta']);
          if ($request->has('src_foto')) {
              if(!Storage::disk('public_uploads')->has('Visitas')){
                  Storage::disk('public_uploads')->makeDirectory('Visitas');
              }
              if (Storage::disk('public_uploads')->exists('Visitas/'.$visita->src_foto)) {
                  Storage::disk('public_uploads')->delete('Visitas/'.$visita->src_foto);
              }
              $img = $data['src_foto'];
              $img = str_replace('data:image/png;base64,', '', $img);
              $img = str_replace(' ', '+', $img);
              $result = base64_decode($img);
              $im = imagecreatefromstring($result);  //convertir text a imagen
              if ($im !== false) {
                  imagejpeg($im, public_path().'/storage/Visitas/'.$data['dni'].time().'.jpg'); //guardar a server 
                  imagedestroy($im); //liberar memoria  
                  $data['src_foto'] = $data['dni'].time().'.jpg';
              }else {
                  //echo "Error al subir la imagen";
              }
          }
          $data['fecha'] = now();
          $visita->fill($data)->save();
          if ($request->has('herramienta')) {
              $herramienta = $request->all();
              if ($herramienta['herramienta'] != 'no' AND $request->has('htrabajo')) {    
                  for ($i=0; $i <count($herramienta['htrabajo']) ; $i++) { 
                      $this->table->nombre = $herramienta['htrabajo'][$i];
                      $this->table->marca = $herramienta['mtrabajo'][$i];
                      $this->table->serial = $herramienta['strabajo'][$i];
                      $this->table->idherramienta = (!empty($herramienta['idherramienta'][$i])) ? $herramienta['idherramienta'][$i] : false;
                      $this->table->id = $id;
                      $this->table->update_utilitarios($id);
                  }
              }
          }
          $request->session()->flash('update', 'Registro actualizado con exito!');

          return response()->json(['success'=>'Registro actualizado con exito','url'=>url('visitas/'.$id.'/edit')]);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        if (substr($id, 0,5) == 'herra') {
            $dato = explode('&', $id);
            DB::table($this->table_pivot)->where('id',$dato[1])->delete();
        }else{
            $data = $this->table::find($id);
            if (!empty($data)) {
                $data->delete();
                DB::table($this->table_pivot)->where('visitas_id',$id)->delete();
                if (Storage::disk('public_uploads')->exists('Visitas/'.$data->src_foto)) {
                    Storage::disk('public_uploads')->delete('Visitas/'.$data->src_foto);
                }
                return response()->json(['success'=>'Registro eliminado con exito']);
            }
        }
    }
}
