<?php

namespace App\Modules\Utilitarios\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Modules\Utilitarios\Models\Articulo;
use App\Modules\Utilitarios\Models\Art_familia;
use App\Modules\Utilitarios\Models\Tag_art;
use App\Modules\Utilitarios\Controllers\Files_contableController;
use Illuminate\Support\Facades\Validator;
use Yajra\Datatables\Datatables;
use DB;
use Storage;
class ArticulosController extends Controller
{
    protected $table;
    protected $table_a;
    protected $table_t;
    protected $files;
    protected $familia_relation ='familia_relation';
    protected $tag_relation ='tag_relation';
    protected $table_files = 'files_contables';
    function __construct(){
        $this->table = new Articulo();
        $this->table_a = new Art_familia();
        $this->table_t = new Tag_art();
        $this->files = new Files_contableController();
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {

        return view('Utilitarios.views.articulos');
    }
    /**
     * 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'=>'no',
                      'url'=>$url.'/edit',
                      'class'=>" btn btn-sm  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('automattic'),
                      'class'=>"btn btn-sm btn-warning fn_automattic",
                      'icon'=>"icon-reload-alt"
                )
            )]); 


        })->rawColumns(['action']);
        return $table->make(true);
    }
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $familia = $this->table_a::all();
        $tags = $this->table_t::all();
        return view('Utilitarios.views.add.articulos')->with('data',['familia'=>$familia,'tags'=>$tags]);
    }

    /**
     * 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':
                    $articulo = $this->table::where('nombre', 'like', '%' . $request->input('search') . '%')->get();
                    if ($articulo->count()) {
                        return $articulo;
                    }else{
                        return response()->json(['error'=>'Resultados vacios para:'.$request->input('search')]);
                    }
                break;
                case 'add':
                    $validator = Validator::make($request->all(),[
                        'nombre' => 'required',
                        'codigo' => 'required',
                        'precio' => 'required',
                        'cantidad' => 'required',
                        'um' => 'required',
                    ]);

                   if ($validator->fails()) {
                       return response()->json(['error'=>$validator->errors()->all()]);
                    }else{
                        if ($this->table::where('codigo', '=', $request->input("codigo"))->count() > 0) {
                           return response()->json(['error'=>'Este articulo ya existe']);
                        }else{
                            $this->table->fill($request->except(['action','family','tag','file','carpeta_file']))->save();
                            $id_last = $this->table->id;
                            if ($request->hasFile('file')) {
                                $this->files->addfile($request->file('file'),$id_last,$request->input('carpeta_file'));
                            }
                           if ($request->filled('family')) {
                                for ($i=0; $i <count($request->input('family')) ; $i++) { 
                                   $familia = new Art_familia();
                                   $familia->articulos_id = $id_last;
                                   $familia->art_familias_id = $request->input('family')[$i];
                                   $familia->add_relation();
                                }
                            }
                            if ($request->filled('tag')) {
                                for ($i=0; $i <count($request->input('tag')) ; $i++) { 
                                   $tag = new Tag_art();
                                   $tag->articulos_id = $id_last;
                                   $tag->tag_id = $request->input('tag')[$i];
                                   $tag->add_relation();
                                }
                            }
                            $request->session()->flash('create_success', 'Registro agregado con exito!');
                            return response()->json(['success'=>'Registro agregado con exito','url'=>url("articulos/")]);
                        }
                    }
                break;
                case 'update':
                    $id = $request->input('id_articulo');
                    $articulo = $this->table::find($id);
                    $data = $request->all();
                    if (!empty($articulo)) {
                        $articulo->nombre = $data['nombre'];
                        $articulo->codigo = $data['codigo'];
                        $articulo->precio = $data['precio'];
                        $articulo->pvprebaja = $data['pvprebaja'];
                        $articulo->cantidad = $data['cantidad'];
                        $articulo->um = $data['um'];
                        $articulo->descripcion = $data['descripcion'];
                        $articulo->status = (!empty($request->has('status')) ? $data['status'] : 0);
                        $articulo->status_sincronization = 0;
                        $articulo->save();
                        if ($request->hasFile('file')) {
                            $this->files->updatefile(
                                $request->file('file'),
                                $request->input('id_file'),
                                $id,
                                'Articulos'
                            );
                        }
                        if ($request->filled('family')) {
                            for ($i=0; $i <count($request->input('family')) ; $i++) {
                                if(DB::table($this->familia_relation)->where('art_familias_id', $request->input('family')[$i])->where('articulos_id',$id)->exists()){

                                }else{
                                    $familia = new Art_familia();
                                    $familia->articulos_id = $id;
                                    $familia->art_familias_id = $request->input('family')[$i];
                                    $familia->add_relation();
                                }
                            }
                        }
                        if ($request->filled('tag')) {
                            for ($i=0; $i <count($request->input('tag')) ; $i++) {
                                if(DB::table($this->tag_relation)->where('tag_arts_id', $request->input('tag')[$i])->where('articulos_id',$id)->exists()){

                                }else{
                                    $tag = new Tag_art();
                                    $tag->tag_id = $request->input('tag')[$i];
                                    $tag->articulos_id = $id;
                                    $tag->add_relation();
                                }
                            }
                        }
                        //$request->session()->flash('update_success', 'Registro actualizado con exito!');
                        return response()->json(['success'=>'Registro actualizado con exito','updateprocess'=>'updateprocess']);
                    }else{
                        return response()->json(['error'=>'El registro no existe']);
                    }
                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)
    {
        $articulo = $this->table::find($id);
        if (!empty($articulo)) {
            return view('Utilitarios.views.edit.editarticulos')->with('data',['articulo'=>$articulo]);
        }else{

        }
    }
    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $articulos = $this->table::find($id);
        $familias = $this->table_a::all();
        $tags = $this->table_t::all();
        $file = $this->files->get_files(array('tipe_archivos'=>'Articulos','id_files'=>$id));
        $articulo = $this->table_a->relation_has($id);
        $tag = $this->table_t->relation_has($id);
        if (!empty($articulos)) {
            return view('Utilitarios.views.edit.articulos')->with(
                'data',
                ['articulo'=>$articulos,
                'familia'=>$familias,
                'art_relation'=>$articulo,
                'tags'=>$tags,
                'tag_relation'=>$tag,
                'file'=>$file
                ]
            );
        }else{

        }
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $articulo = $this->table::find($id);
        if (!empty($articulo)) {
            $articulo->fill($request->except(['family','tag','file','id_file']))->save();
            if ($request->hasFile('file')) {
                $this->files->updatefile($request->file('file'),$request->input('id_file'),$request->input('carpeta_file'));
            }
            if ($request->filled('family')) {
                for ($i=0; $i <count($request->input('family')) ; $i++) {
                    if(DB::table($this->familia_relation)->where('art_familias_id', $request->input('family')[$i])->where('articulos_id',$id)->exists()){

                    }else{
                        $familia = new Art_familia();
                        $familia->articulos_id = $id;
                        $familia->art_familias_id = $request->input('family')[$i];
                        $familia->add_relation();
                    }
                }
            }
            if ($request->filled('tag')) {
                for ($i=0; $i <count($request->input('tag')) ; $i++) {
                    if(DB::table($this->tag_relation)->where('tag_arts_id', $request->input('tag')[$i])->where('articulos_id',$id)->exists()){

                    }else{
                        $tag = new Tag_art();
                        $tag->tag_id = $request->input('tag')[$i];
                        $tag->articulos_id = $id;
                        $tag->add_relation();
                    }
                }
            }
            $request->session()->flash('update_success', 'Registro actualizado con exito!');
            return response()->json(['success'=>'Registro actualizado con exito','url'=>url("articulos/".$id."/edit")]);
        }else{
            return response()->json(['error'=>'El registro no existe']);
        }    
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $articulo = $this->table::find($id);
        if (!empty($articulo)) {
            $articulo->delete();
            if (is_dir(base_path().'/public/storage/Articulos/'.$id)) {
                Storage::disk('public_uploads')->deleteDirectory('Articulos/'.$id);
            }
            DB::table($this->familia_relation)->where('articulos_id', '=', $id)->delete();
            DB::table($this->tag_relation)->where('articulos_id', '=', $id)->delete();
            DB::table($this->table_files)->where('tipe_modulo', '=', 'Articulos')->where('id_files',$id)->delete();
            return response()->json(['success'=>'Registro eliminado con exito']);
        }
    }
}
