<?php

namespace App\Http\Controllers\Administrator\product;

use App\Exports\SizeExport;
use App\Imports\SizeImport;
use App\Model\product\SizeModel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Validation\ValidationException;
use Maatwebsite\Excel\Facades\Excel;

class SizeController extends Controller
{
    function __construct()
    {
      $this->middleware('permission:Size Create', ['only' => ['create','store']]);
      $this->middleware('permission:Size List', ['only' => ['index']]);
      $this->middleware('permission:Size List', ['only' => ['get_edit','update']]);
    }
    public function index()
    {
        $data=SizeModel::get();
        return view('administrator.setup-item.product-element.size.index',compact('data'));
    }
    public function store(Request $request)
    {
        $this->validate($request,[
            'size'=>'required|unique:nso007_product_size,size,',
            'code'=>'required|unique:nso007_product_size,code,',
        ]);
        $size = new SizeModel();
        $size->size = $request->size;
        $size->code = $request->code;
        $size->note = $request->note;
        $size->save();
        session()->put('success','Size created successful');
        return response()->json('success');
    }
    public function get_edit($id)
    {
        $data = SizeModel::find($id);
        return response()->json($data);
    }
    public function update(Request $request)
    {
        $this->validate($request,[
            'size'=>'required|unique:nso007_product_size,size,'.$request->id,
            'code'=>'required|unique:nso007_product_size,code,'.$request->id,
        ]);
        $size = SizeModel::find($request->id);
        $size->code = $request->code;
        $size->size = $request->size;
        $size->note = $request->note;
        $size->save();
        session()->put('success','Size update successful');
        return response()->json('success');
    }

    public function import_excel(Request $request)
    {
        if ($request->export_sample) {
            return Excel::download(new SizeExport(), 'size.xlsx');
        }
        if ($request->method() === 'POST') {
            $this->validate($request, [
                'file' => 'required|file|max:10000|mimes:xlsx,csv',
            ]);

            try {
                if (request()->hasFile('file')) {
                    $path = $request->file('file');
                    Excel::import(new SizeImport(), $path);
                    return response()->json(['status' => 'success', 'reload' => 1]);
                }
            } catch (\Exception $er) {
                throw ValidationException::withMessages($er->getMessage());
            }
        }
        return view('component.import-exel',['route'=>'size-import-excel']);
    }
}
