<?php

namespace App\Http\Controllers\Backend;

use App\Models\Company;
use App\Models\Product;
use App\Models\Category;
use App\Models\CompanyCategory;
use App\Models\Attribute;
use App\Models\ProductAttribute;
use App\Models\Brand;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\DB;
use Excel;
use App;
use Image;

class ProductController extends Controller
{
    public function index(Request $request)
    {
        $query = !empty($request->get('q')) ? $request->get('q') : null;
        $productsQuery = Product::with(['category', 'brand']);
        if ($query) {
            $productsQuery = $productsQuery->search($query, null, true);
        }
        $products = $productsQuery->paginate(20);
        return view('backend.products.index', compact('products', 'companies'));
    }

    public function create()
    {
        $companies = Company::pluck('name', 'id');
        $brands = Brand::pluck('name', 'id');
        $selected_ids = CompanyCategory::where("company_id", auth()->user()->company_id)->pluck('category_id')->all();
        // $categories = Category::with('parent')->whereIN('id', $selected_ids)->pluck('name', 'id');
        // $categories = Category::with(['parent', 'parent.parent'])->where('level', 2)->get();
        $categories_l0 = Category::with('subs')->where('parent_id', 0)->pluck('name', 'id');

        return view('backend.products.create', compact('companies', 'categories_l0', 'brands'));
    }

    public function store(Request $request)
    {
        $product = Product::create($request->only([
            'brand_id',
            'category_id',
            'name',
            'ref',
            'code_douanier',
            'description',
            'seo_page_title',
            'seo_meta_description',
            'published',
            'production_nationale',
            'prix_achat_ht',
            'prix_achat_ttc',
            'prix_vente_ht',
            'prix_vente_ttc',
        ]));
        $product->slug = str_slug($request->input('name'), '-');
        $product->save();

        if ($request->hasFile('image')) {
            $file = $request->file('image');
            $path = 'public/brands/' . $product->brand_id . '/products/' . $product->id . '/';
            $path = $request->file('image')->storeAs($path, $product->id . '.' . $file->getClientOriginalExtension());
            $product->image = $product->id . '.' . $file->getClientOriginalExtension();
            $product->save();

            //$img = Image::make($file->getRealPath());

            // $filename = $product->id . '_thumbnail.' . $file->getClientOriginalExtension();
            // $path = storage_path('app/public/companies/'. $product->company_id . '/products/');
            // $img->resize(300, 200, function($constraint) {
            //     $constraint->aspectRatio();
            // })->save($path.''.$filename);
        }

        if ($request->hasFile('fiche_technique')) {
            $file = $request->file('fiche_technique');
            $path = 'public/brands/' . $product->brand_id . '/products/' . $product->id . '/';
            $path = $request->file('fiche_technique')->storeAs($path, 'fiche_technique_' . $product->slug . '.' . $file->getClientOriginalExtension());
            $product->fiche_technique = 'fiche_technique_' . $product->slug . '.' . $file->getClientOriginalExtension();
            $product->save();
        }

        $this->updateAttributes($request, $product);

        return redirect()->route('backend.products.show', $product->id);
    }

    public function show($id)
    {
        $product = Product::with('attributes')->findOrFail($id);
        $attributes = $product->attributes()->with('attribute')->get();
        return view('backend.products.show', compact('product', 'attributes'));
    }

    public function edit($id)
    {
        $product = Product::findOrFail($id);

        $companies = Company::pluck('name', 'id');
        $brands = Brand::pluck('name', 'id');
        $selected_ids = CompanyCategory::where("company_id", $product->company_id)->pluck('category_id')->all();
        $categories = Category::with('parent')->whereIN('id', $selected_ids)->pluck('name', 'id');

        $categories_l0 = Category::with('subs')->where('parent_id', 0)->pluck('name', 'id');
        $categories_l1 = Category::with('subs')->where('parent_id', $product->category->parent->parent->id)->pluck('name', 'id');
        $categories_l2 = Category::with('subs')->where('parent_id', $product->category->parent->id)->pluck('name', 'id');

        $attributes = Attribute::where('category_id', $product->category_id)->where('parent_id', null)->get();
        $product_attributes = $product->attributes->pluck('value', 'attribute_id');

        return view('backend.products.edit', compact('product', 'companies', 'categories', 'attributes', 'product_attributes', 'brands', 'categories_l0', 'categories_l1', 'categories_l2'));
    }

    public function update(Request $request, $id)
    {
        $product = Product::findOrFail($id);
        $product->fill($request->only([
            'company_id',
            'brand_id',
            'category_id',
            'name',
            'ref',
            'code_douanier',
            'description',
            'seo_page_title',
            'seo_meta_description',
            'published',
            'production_nationale',
            'prix_achat_ht',
            'prix_achat_ttc',
            'prix_vente_ht',
            'prix_vente_ttc',
        ]));
        $product->save();

        if ($request->hasFile('image')) {
            // Delete old file
            $path = 'public/brands/' . $product->brand_id . '/products/' . $product->id . '/' . $product->image;
            if (!empty($product->image) && File::exists(storage_path('app/' . $path))) {
                Storage::delete($path);
            }
            // Upload new file
            $file = $request->file('image');
            $path = 'public/brands/' . $product->brand_id . '/products/' . $product->id . '/';
            $path = $request->file('image')->storeAs($path, $product->id . '.' . $file->getClientOriginalExtension());
            $product->image = $product->id . '.' . $file->getClientOriginalExtension();
            $product->save();
        }

        if ($request->hasFile('fiche_technique')) {
            // Delete old file
            $path = 'public/brands/' . $product->brand_id . '/products/' . $product->id . '/' . $product->fiche_technique;
            if (!empty($product->fiche_technique) && File::exists(storage_path('app/' . $path))) {
                Storage::delete($path);
            }
            // Upload new file
            $file = $request->file('fiche_technique');
            $path = 'public/brands/' . $product->brand_id . '/products/' . $product->id . '/';
            $path = $request->file('fiche_technique')->storeAs($path, 'fiche_technique_' . $product->slug . '.' . $file->getClientOriginalExtension());
            $product->fiche_technique = 'fiche_technique_' . $product->slug . '.' . $file->getClientOriginalExtension();
            $product->save();
        }


        $this->updateAttributes($request, $product);

        return redirect()->route('backend.products.show', $product->id);
    }

    public function delete($id)
    {
        $product = Product::find($id);

        // Delete image
        $path = 'public/brands/' . $product->brand_id . '/products/' . $product->id . '/' . $product->image;
        if (!empty($product->image) && File::exists(storage_path('app/' . $path))) {
            Storage::delete($path);
        }

        // Delete fiche technique
        $path = 'public/brands/' . $product->brand_id . '/products/' . $product->id . '/' . $product->fiche_technique;
        if (!empty($product->fiche_technique) && File::exists(storage_path('app/' . $path))) {
            Storage::delete($path);
        }
        Storage::deleteDirectory('public/brands/' . $product->brand_id . '/products/' . $product->id);

        $product->delete();

        return redirect()->route('backend.products.index');
    }

    public function attributes($category_id)
    {
        $attributes = Attribute::where('category_id', $category_id)->whereNull('parent_id')->get();

        // Pour ne pas dupliquer les vue
        return view('clients.products.attributes.index', compact('attributes'));
    }

    /**
     * @param Request $request
     * @param $product
     * @throws \Exception
     */
    public function updateAttributes(Request $request, $product)
    {
        $attributes = array_filter($request->input(), function ($key) {
            return strpos($key, 'attr-') === 0;
        }, ARRAY_FILTER_USE_KEY);

        // Ajout d'attributs
        // Delete All Attributes
        ProductAttribute::where('product_id', $product->id)->delete();
        foreach ($attributes as $key => $attribute) {
            if (strpos($key, "attr-interval-") !== false) {
                $attr_id = str_replace("attr-interval-", "", $key);
                $value = implode(":", $attribute);
            } elseif (strpos($key, "attr-multi-") !== false) {
                $attr_id = str_replace("attr-multi-", "", $key);
                $value = implode("|", $attribute);
            } else {
                $attr_id = str_replace("attr-", "", $key);
                $value = $attribute;
            }

            $productAttribute = ProductAttribute::create([
                'category_id' => $product->category_id,
                'product_id' => $product->id,
                'attribute_id' => $attr_id,
                'value' => $value
            ]);
        }
    }

    public function categoriesSelect($id)
    {
        $category = Category::findOrFail($id);
        $level = $category->level + 1;

        $categories = Category::with('subs')->where('parent_id', $id)->pluck('name', 'id');
        return view('backend.products.importation._select', compact('categories', 'level'));
    }

    public function import()
    {
        $categories = Category::where('level', 0)->pluck('name', 'id');
        //$companies = Company::pluck('name', 'id');
        $brands = Brand::pluck('name', 'id');
        return view('backend.products.importation.index', compact('categories', 'brands', 'companies'));
    }

    public function importStore(Request $request)
    {
        $category_id = $request->input('category_id_l2');
        //$company_id = $request->input('company_id');
        $brand_id = $request->input('brand_id');
        $published = $request->input('publish');
        // Récuperer une liste des attributs nom : id
        $attributes = Attribute::where('category_id', $category_id)->pluck('id', 'name');
        //dd($attributes);
        DB::beginTransaction();
        if ($request->hasFile('fileimport')) {
            $path = $request->file('fileimport')->getRealPath();
            $excel = App::make('excel');
            $data = $excel->load($path, function ($reader) { })->get();

            if (!empty($data) && $data->count()) {
                foreach ($data->toArray() as $key => $value) {
                    if (!empty($value)) {
                        $product = Product::create([
                            'name'          => $value['Nom'],
                            'slug'          => str_slug($value['Nom'], '-'),
                            'ref'           => $value['Ref'],
                            'description'   => $value['Description'],
                            'image'         => null,
                            'category_id'   => $category_id,
                            'brand_id'      => $brand_id,
                            'published'     => $published
                        ]);
                        // Récupérer les attributs dynamiques
                        $attributes_values = array_slice($value, 4);
                        foreach ($attributes_values as $attribute => $value) {
                            $attribute_id = $attributes->get($attribute);
                            if (!empty($attribute_id)) {
                                ProductAttribute::create([
                                    'category_id'   => $category_id,
                                    'attribute_id'  => $attribute_id,
                                    'product_id'    => $product->id,
                                    'value'         => $value
                                ]);
                            } else {
                                DB::rollback();
                                return redirect()->route('backend.products.import.index')->with('flash_danger', 'Fichier Excel non conforme');
                            }
                        }
                    }
                }
            }
            DB::commit();
            return redirect()
                ->route('backend.products.import.index')
                ->with('flash_success', ' Importation Excel exécuté avec succès, (' . $data->count() . ') produits ');
        }
    }

    public function export(Request $request)
    {
        $data = ['Nom', 'Ref', 'Description', 'Image'];

        $category_id = $request->input('category_id_l2');
        $category = Category::findOrFail($category_id);
        $attributes = Attribute::where('category_id', $category_id)->get();

        foreach ($attributes as $attribute) {
            $data[] = $attribute->name;
        }
        $filename = str_slug($category->name, '-') . '-' . date('d-m-Y');

        Excel::create($filename, function ($excel) use ($data, $category) {
            $excel->sheet($category->name, function ($sheet) use ($data) {
                $sheet->fromArray($data);
            });
        })->export('xlsx');
    }
}
