<?php

namespace Onestartup\ProductPrimerPlano\Controller;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Yajra\Datatables\Datatables;
use Onestartup\ProductPrimerPlano\Model\ProductCategory as Category;
use Onestartup\ProductPrimerPlano\Model\ProductSubCategory as SubCategory;
use Onestartup\ProductPrimerPlano\Model\ProductImage as Gallery;
use Onestartup\ProductPrimerPlano\Model\Product;
use Onestartup\ProductPrimerPlano\Model\Variable as Variable;
use Onestartup\ProductPrimerPlano\Model\Asesor;

use Onestartup\ProductPrimerPlano\Requests\RequestProduct;
use Onestartup\ProductPrimerPlano\Requests\RequestVariables;
use Onestartup\ProductPrimerPlano\Requests\RequestGallery;

class AdminProductController extends Controller
{
    public function index()
    {
        return view('product::product.index');
    }

    /**
     * Show the form for creating a new resource.
     * @return Response
     */
    public function create()
    {
        $categories = Category::pluck('name', 'id');
        $variable = Variable::first();
        $asesores = Asesor::pluck('nombre', 'id');
        $subcategories = [];

        return view('product::product.create')
            ->with('asesores', $asesores)
            ->with('categories', $categories)
            ->with('subcategories', $subcategories)
            ->with('variable', $variable);
    }

    /**
     * Store a newly created resource in storage.
     * @param  Request $request
     * @return Response
     */
    public function store(RequestProduct $request)
    {
        
        $product = new Product($request->all());
        \Auth::user()->products()->save($product);
        if (isset($request->cover)) {
            
            $file = $request->file('cover');
            $nombre = $file->getClientOriginalName();
            $nombre_file = str_replace(' ', '_', $nombre);
            $ubicacion_donde_guarda ='products/cover/'.$product->id."/".$nombre_file;
            \Storage::disk('local')->put($ubicacion_donde_guarda,  \File::get($file));
            $product->cover = $ubicacion_donde_guarda;
            $product->save();
        } 


        

        return redirect()
                ->route('admin.product.edit', $product->id)
                ->with('message_success', "Producto guardado correctamente, continua agregando las imagenes correspondientes");
    }

    /**
     * Show the form for editing the specified resource.
     * @return Response
     */
    public function edit($id)
    {
        $product = Product::find($id);
        $categories = Category::pluck('name', 'id');
        $subcategories = SubCategory::where("category_id", $product->category_id)->pluck('name', 'id');
        $variable = Variable::first();
        $asesores = Asesor::pluck('nombre', 'id');

        return view('product::product.edit')
            ->with('asesores', $asesores)
            ->with('categories', $categories)
            ->with('subcategories', $subcategories)
            ->with('product', $product)
            ->with('variable', $variable);
    }

    /**
     * Update the specified resource in storage.
     * @param  Request $request
     * @return Response
     */
    public function update(RequestProduct $request, $id)
    {
        $product = Product::find($id);
        $product->fill($request->all());
        $product->save();

        if (isset($request->cover)) {
            
            $file = $request->file('cover');
            $nombre = $file->getClientOriginalName();
            $nombre_file = str_replace(' ', '_', $nombre);
            $ubicacion_donde_guarda ='products/cover/'.$product->id."/".$nombre_file;
            \Storage::disk('local')->put($ubicacion_donde_guarda,  \File::get($file));
            $product->cover = $ubicacion_donde_guarda;
            $product->save();
        } 


        return redirect()
            ->back()
            ->with('message_info', 'Información actualizada correctamente');
    }

    /**
     * Remove the specified resource from storage.
     * @return Response
     */
    public function destroy($id)
    {
        $product = Product::find($id);
        $product->delete();

        return redirect()
            ->back()
            ->with('message_danger', 'Producto eliminada correctamente');
    }

    public function getProducts()
    {

        $products = Product::select([
            'id',
            'name',
            'slug', 
            'category_id', 
            'created_at', 
            'description', 
            'features', 
            'specifications'
        ]);

        return Datatables::of($products)
            ->addColumn('main', function ($product) {
                return 
                        "<p class='mb0'>Nombre: <b>$product->name</b></p>".
                        "<p class='mb0'>Slug: <b>$product->slug</b></p>".
                        "<p class='mb0'>Categoría: <b>".$product->category->name."</b></p>".
                        "<p class='mb0'>Fecha de creación: <b>".$product->created_at->format('d/m/Y')."</b></p>";
            })
            ->addColumn('form', function ($product) {

                return "<center><form method='POST' action='".route('admin.product.destroy',$product->id)."'>".
                "<input name='_method' type='hidden' value='DELETE' class='has-value'>".
                csrf_field() .
                "<button class='btn btn-danger btn-xs button-mb' onclick='return confirm();' type='submit'>".
                "<i class='fas fa-trash-alt icon-special-size'></i>Eliminar</button>".
                "</form>".
                "<a href='".route('show.product', $product->slug)."' class='btn btn-xs info button-mb' target='new'>".
                "<i class='fas fa-eye icon-special-size'></i>Ver</a>".
                "<br><a href='".route('admin.product.edit', $product->id)."' class='btn btn-xs accent mb0'>".
                "<i class='fas fa-edit icon-special-size'></i>Editar</a></center>";
            })
            ->rawColumns(['main', 'description', 'features', 'specifications', 'form'])
            ->make();
        
    }

    public function storeGallery(RequestGallery $request, $product_id)
    {
        $product = Product::find($product_id);

        $asset = '/storage/product/'.$product->id.'/gallery/';
        $path = public_path().$asset;
        $files = $request->file('file');

        foreach($files as $file){
            $fileName = $file->getClientOriginalName();
            $nombre_file = str_replace(' ', '_', $fileName);
            $file->move($path, $nombre_file);
            $gallery = new Gallery([
                'path'=>$asset.$nombre_file
            ]);

            $product->images()->save($gallery);
        }


        return $product;
    }

    public function deleteImage($id)
    {
        $gallery = Gallery::find($id);

        if (file_exists(public_path().$gallery->path)) {
            unlink(public_path().$gallery->path);
        }
        
        $gallery->delete();

        return redirect()
            ->back()
            ->with('message_danger', 'Imagen eliminada correctamente');

    }

    public function deleteCover($id)
    {
        $product = Product::find($id);
        
        if (file_exists(public_path().'/storage/'.$product->cover)) {
            unlink(public_path().'/storage/'.$product->cover);
        }
        
        $product->cover = null;
        $product->save();

        
        //$gallery->delete();

        return redirect()
            ->back()
            ->with('message_danger', 'Imagen eliminada correctamente');

    }

    public function showVars()
    {

        $variable = Variable::first();

        if ($variable == null) {
            $variable = new Variable();
        }

        return view('product::variable.edit')
            ->with('variable', $variable);
    }

    public function postVars(RequestVariables $request)
    {

        $variable = Variable::first();

        if ($variable == null) {
            $variable = new Variable();
        }

        $variable->fill($request->all());

        $variable->save();

        return redirect()
            ->back()
            ->with('message_success', 'Información actualizada');
    }

}