<?php

namespace App\Http\Controllers\Backend;

use App\Models\CompanyCategory;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Company;
use App\Models\Country;
use App\Models\Wilaya;
use App\Models\Commune;
use App\Models\Category;
use App\Models\Product;
use Illuminate\Contracts\Validation\Validator;
use App\Models\SecteurActivite;
use App\Models\NatureActivite;

class CompanyController extends Controller
{
    public function index(Request $request)
    {
        $query = !empty($request->get('q')) ? $request->get('q') : null;
        if ($query) {
            $companies = Company::search($query, null, true)->paginate(20);
        } else {
            $companies = Company::paginate(20);
        }
        return view('backend.companies.index', compact('companies'));
    }

    public function create()
    {
        $countries = Country::pluck('name_fr', 'id');
        $companies = Company::pluck('name', 'id');
        $wilayas = Wilaya::pluck('name', 'id');
        $secteurs = SecteurActivite::pluck('name', 'id');
        $natures = NatureActivite::pluck('name', 'id');
        $communes = [];
        return view('backend.companies.create', compact('countries', 'companies', 'wilayas', 'communes', 'secteurs', 'natures'));
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'company_nif' => 'required|unique:companies',
        ], [
            'company_nif.unique' => "Le numéro d'identification fiscale (NIF) est déja attribué",
        ]);
        $company = Company::create($request->except(['optionsGroupe', 'image']));
        $company->slug = str_slug($request->input('name'), '-');
        $company->save();

        if( $request->hasFile('image') ) {
            $file = $request->file('image');
            $path = 'public/companies/'. $company->id . '/';
            $path = $request->file('image')->storeAs($path, $company->id . '.' . $file->getClientOriginalExtension());
            $company->image = $company->id . '.' . $file->getClientOriginalExtension();
            $company->save();
        }

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

    public function show($id)
    {
        $company = Company::findOrFail($id);
        return view('backend.companies.show', compact('company'));
    }

    public function edit($id)
    {
        $company = Company::findOrFail($id);
        $countries = Country::pluck('name_fr', 'id');
        $companies = Company::pluck('name', 'id');
        $wilayas = Wilaya::pluck('name', 'id');
        $communes = Commune::where('wilaya_id', $company->wilaya_id)->pluck('name', 'id');
        $secteurs = SecteurActivite::pluck('name', 'id');
        $natures = NatureActivite::pluck('name', 'id');
        return view('backend.companies.edit', compact('company', 'countries', 'companies', 'wilayas', 'communes', 'secteurs', 'natures'));
    }

    public function update(Request $request, $id)
    {
        $company = Company::findOrFail($id);
        $this->validate($request, [
            'company_nif' => 'required|unique:companies,company_nif,' . $company->id
        ], [
            'company_nif.unique' => "Le numéro d'identification fiscale (NIF) est déja attribué",
        ]);

        
        $company->fill($request->except(['optionsGroupe', 'image']));
        $company->save();

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

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

    public function delete($id)
    {
        $company = Company::find($id);
        $company->delete();

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

    public function createUser($id)
    {
        $company = Company::findOrFail($id);
        return view('backend.companies.users.create', compact('company'));
    }

    public function storeUser(Request $request, $id)
    {
        $company = Company::findOrFail($id);
        $user = new User;
        $user->name = $request->input('name');
        $user->email = $request->input('email');
        $user->role_id = 2;
        $user->company_id = $id;
        $user->password = \Hash::make($request->input('password'));
        $user->save();
        return redirect()->route('backend.companies.show', $company->id);
    }

    public function showUser($id, $user_id)
    {
        $user = User::findOrFail($user_id);
    }

    public function editUser($id, $user_id)
    {
        $user = User::findOrFail($user_id);
        $company = Company::findOrFail($id);

        return view('backend.companies.users.edit', compact('company', 'user'));
    }

    public function updateUser(Request $request, $id, $user_id)
    {
        $company = Company::findOrFail($id);
        $user = User::findOrFail($user_id);
        $user->fill($request->except('password'));
        if (!empty($request->input('password'))) {
            $user->password = \Hash::make($request->input('password'));
        }
        $user->save();

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



    public function deleteUser($id, $user_id)
    {
        $company = Company::find($id);
        $user = User::findOrFail($user_id);
        $user->delete();

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

    public function categories($id)
    {
        $company = Company::find($id);
        $selected_ids = CompanyCategory::where("company_id", $id)->pluck('category_id')->all();
        $categories = Category::with(['parent', 'parent.parent'])->where('level', 2)->whereNotIN('id', $selected_ids)->get();
        $selected_categories = Category::with(['parent', 'parent.parent'])->whereIN('id', $selected_ids)->get();

        return view('backend.companies.categories.edit', compact('categories', 'company', 'selected_categories'));
    }

    public function categoriesSelect($id)
    {
        $company = Company::find($id);
        $selected_ids = CompanyCategory::where("company_id", $id)->pluck('category_id')->all();
        $categories = Category::with(['parent', 'parent.parent'])->where('level', 2)->whereIN('id', $selected_ids)->pluck('name', 'id');

        return view('backend.companies.categories.select', compact('categories', 'company'));
    }

    public function updateCategories(Request $request, $id)
    {
        $categories = $request->input('categories');
        if ($categories) {
            CompanyCategory::where('company_id', $id)->delete();
            foreach ($categories as $category) {
                CompanyCategory::create([
                    'company_id'    => $id,
                    'category_id'   => $category
                ]);
            }
        }

        return redirect()->route('backend.companies.show', $id);
    }
    public function communesSelect($wilaya_id)
    {
        $communes = Commune::where('wilaya_id', $wilaya_id)->get();

        return view('backend.companies.communes', compact('communes'));

    }

    public function products(Request $request, $id)
    {
        $query = !empty($request->get('q')) ? $request->get('q') : null;
        $company = Company::findOrFail($id);
        if ($query) {
            $products = $company->products()->with(['category', 'brand'])->search($query, null, true)->paginate(10);
        }else{
            $products = $company->products()->with(['category', 'brand'])->paginate(10);
        }
        return view('backend.companies.products.index', compact('company', 'products'));
    }

    public function productsSelect($id)
    {
        $company = Company::findOrFail($id);
        $products = Product::all();
        $categories_l0 = Category::with('subs')->where('parent_id', 0)->pluck('name', 'id');

        return view('backend.companies.products.select', compact('company', 'products', 'categories_l0'));
    }

    public function productSearch(Request $request, $id)
    {
        $query = !empty($request->get('q')) ? $request->get('q') : null;
        $company = Company::findOrFail($id);
        if ($query) {
            //$products = Product::with(['category', 'brand'])->search($query, null, true)->get();
            $products = Product::with(['category', 'brand'])->where('category_id', $query)->get();
            return view('backend.companies.products.search', compact('company', 'products'));
        }
        return null;
    }

    public function productAdd(Request $request, $id)
    {
        $company = Company::findOrFail($id);
        $ids = $request->get('id');
        foreach ($ids as $product_id) {
            try {
                $company->products()->attach($product_id);
            } catch (\Exception $e){
            }
        }
        return redirect()->route('backend.companies.products.index', $id);
    }

    public function productDelete(Request $request, $id, $product_id)
    {
        $company = Company::findOrFail($id);
        $company->products()->detach($product_id);

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