<?php

namespace App\Modules\Catalogo\Controllers;
use App\Modules\Catalogo\Models\Entidad;
use App\Modules\Catalogo\Models\Entidad_service;
use App\Modules\Utilitarios\Models\Departamento;
use App\Modules\Utilitarios\Models\Distrito;
use App\Modules\Utilitarios\Models\Provincia;
use App\Modules\Utilitarios\Models\Identidad_document;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Yajra\Datatables\Datatables;
use Illuminate\Support\Collection as Collection;
use Illuminate\Support\Facades\Validator;

class EntidadController extends Controller
{
    protected $table;
    protected $table_s;
    protected $table_d;
    protected $table_di;
    protected $table_p;
    protected $table_i;
    function __construct(){
        $this->middleware('auth');
        $this->table = new Entidad();
        $this->table_s = new Entidad_service();
        $this->table_d = new Departamento();
        $this->table_di = new Distrito();
        $this->table_p = new Provincia();
        $this->table_i  = new Identidad_document();
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {   
        return view('Catalogo.views.entidad')->with('title','hola');
    }
     /**
     * Display a listing of the datatables list.
     *
     */
    public function getTable()
    {   
        $entidad = $this->table->show_all_entidad();
        $entidades = new Collection;
        foreach ($entidad as $k) {
            $names = $k->nombre1.' '.$k->nombre2;
            if (empty($k->nombre1) AND empty($k->nombre2)) {
               $names = $k->nsocial;
            }
            if (!empty($k->identidad_document)) {
                $ruc = $k->identidad_document->descripcion;
            }
            $entidades->push([
                'id'         => $k->id,
                'identidad_document' => $ruc,
                'numero'      => $k->numero,
                'nombre1' => $names,
            ]);
        }
        $table = Datatables::of($entidades);
        $table->addColumn('action', function($row){
            $url = url('entidad/'.$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'=>'delete',
                      'id_row'=>$row['id'],
                      'modal'=>'no',
                      'url'=>$url,
                      'class'=>"btn btn-danger btn-sm fn_delete",
                      'icon'=>"icon-trash"
                )
            )]);
        })->rawColumns(['action']);
        return $table->make(true);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $entidad_services = $this->table_s::all();
        $departamentos = $this->table_d::all();
        $provincias =$this->table_p::all();
        $distrito = $this->table_di::all();
        $identidad = $this->table_i::all();
        return view('Catalogo.views.add.entidad')
               ->with('identidad',$identidad)
               ->with('services',$entidad_services)
               ->with('localidad',
                    ['departamentos'=>$departamentos,
                    'provincias'=>$provincias,
                    'distritos'=>$distrito
                   ]);
    }

    /**
     * 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 'search':
                    $entidades = $this->table::where('nombre1', 'like', '%' . $request->input('search') . '%')
                    ->orWhere('nsocial', 'like', '%' . $request->input('search') . '%')->get();
                        if ($entidades->count()) {
                            return $entidades;
                        }else{
                            return response()->json(['error'=>'Resultados vacios para:'.$request->input('search')]);
                        }
                    exit();
                break;
                case 'add':
                    $required = '';
                    if ($request->has('active_ciudadano')) {
                        $required = 'required';
                    }
                    $validator = Validator::make($request->all(),[
                        'identidad_document_id' => 'required',
                        'persona_nacionalidad' => 'required',
                        'persona_tipe' => 'required',
                        'numero' => 'required',
                        'nsocial' => 'required',
                    ]);

                   if ($validator->fails()) {
                       return response()->json(['error'=>$validator->errors()->all()]);

                    }else{
                        if ($this->table::where('numero', '=', $request->input("numero"))->count() > 0) {
                           return response()->json(['error'=>['El ruc o email ya existe']]);
                        }else{

                            $this->table->fill($request->except(['action','active_ciudadano','active_services','entidad_table25_id','entidad_table31_id','entidad_table32_id','entidad_table33_id','active_services']))->save();

                            if ($request->has('active_services')) {
                                $this->table_s->entidad_id = $entidad->id;
                                $this->table_s->tables = array('table25'=> $request->input('entidad_table25_id'),'table31'=>$request->input('entidad_table31_id'),'table32'=>$request->input('entidad_table32_id'),'table33'=>$request->input('entidad_table33_id'));
                                $this->table_s->Create_services_has();
                            }
                            $request->session()->flash('create_entidad', 'Registro agregado con exito!');
                            return response()->json(['success'=>'Registro agregado con exito','url'=>url("entidad/")]);
                        }
                    }
                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)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $entidad = $this->table->show_by_id($id);
        $services = $this->table_s->get_excerpt_entidad($id);
        $distrito = $this->table_di::all();
        $provincia = $this->table_p::all();
        $departamento = $this->table_d::all();
        $identidad = $this->table_i::all();

        return view('Catalogo.views.edit.entidad')
            ->with('data',
                ['entidad'=>$entidad,
                'provincias'=>$provincia,
                'departamentos'=>$departamento,
                'distritos'=>$distrito,
                'identidad'=>$identidad
                ])
            ->with('services',$services);
    }

    /**
     * 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)) {
            $validator = Validator::make($request->all(),[
                'identidad_document_id' => 'required',
                'persona_nacionalidad' => 'required',
                'persona_tipe' => 'required',
                'numero' => 'required',
                'nsocial' => 'required',
            ]);

           if ($validator->fails()) {
               return response()->json(['error'=>$validator->errors()->all()]);
            }else{
                $data->fill($request->except(['active_services','active_ciudadano','action','entidad_table25_id','entidad_table31_id','entidad_table32_id','entidad_table33_id']))->save();
                if ($request->has('active_services')) {
                    $this->table_s->tables =array(
                        'table25'=>$request->input('entidad_table25_id'),
                        'table31'=>$request->input('entidad_table31_id'),
                        'table32'=>$request->input('entidad_table32_id'),
                        'table33'=>$request->input('entidad_table33_id')
                    );
                    $this->table_s->entidad_id = $id;
                    $this->table_s->Update_services_has();
                }
                return response()->json(['success'=>'Registro actualizado con exito','animation'=>'up']);
            }
        }
    }

    /**
     * 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();
            $this->table_s->destroy_services_has($id);
            return response()->json(['success'=>'Registro eliminado con exito']);
        }
    }
}
