<?php

namespace App\Http\Controllers\Administrator\product;

use App\Exports\BrandExport;
use App\Imports\BrandImport;
use App\Model\product\BrandModel;
use App\Model\setup\WarehouseModel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Validation\ValidationException;
use Maatwebsite\Excel\Facades\Excel;

class BrandController extends Controller
{
    function __construct()
    {
      $this->middleware('permission:Brand List', ['only' => ['index']]);
      $this->middleware('permission:Brand Create', ['only' => ['create','store']]);
      $this->middleware('permission:Brand Edit', ['only' => ['get_edit','update']]);
    }

    public function index()
    {
        $data=BrandModel::get();
        return view('administrator.setup-item.product-element.brand.index',compact('data'));
    }
    public function create()

    {

        return view('administrator.setup-item.product-element.brand.create');

    }

    public function edit($id)

    {
        $value = BrandModel::find($id);
        return view('administrator.setup-item.product-element.brand.edit', compact('value'));
    }
    public function store(Request $request)
    {
        return $this->update($request,null);
    }
    public function update(Request $request,$id)
    {
        $this->validate($request,[
            'brand'=>'required',
            'code'=>'required|unique:nso007_product_brand,code,'.$id
        ]);
        BrandModel::updateOrCreate (['id'=> $id],$request->all());
        return response()->json(['status'=>'success','reload'=>1]);
    }
    public function import_excel(Request $request)
    {
        if ($request->export_sample) {
            return Excel::download(new BrandExport(), 'brand.xlsx');
        }
        if ($request->method() === 'POST') {
            $this->validate($request, [
                'file' => 'required|file|max:10000|mimes:xlsx,csv',
            ]);
            if (request()->hasFile('file')) {
                $path = $request->file('file');
                Excel::import(new BrandImport(), $path);
                return response()->json(['status' => 'success', 'reload' => 1]);
            }
            try {


            } catch (\Exception $er) {
                throw ValidationException::withMessages($er->getMessage());
            }
        }
        return view('component.import-exel',['route'=>'brand-import-excel']);
    }

}
