<?php

namespace App\Http\Controllers\Administrator\product;

use App\Exports\UnitExport;
use App\Imports\UnitImport;
use App\Model\product\UnitModel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Validation\ValidationException;
use Maatwebsite\Excel\Facades\Excel;

class UnitController extends Controller
{
    function __construct()
    {
      $this->middleware('permission:Unit List', ['only' => ['index']]);
      $this->middleware('permission:Unit Create', ['only' => ['create','store']]);
      $this->middleware('permission:Unit Edit', ['only' => ['get_edit','update']]);
    }
    public function index()
    {
        $data=UnitModel::get();
        return view('administrator.setup-item.product-element.unit.index',compact('data'));
    }
    public function create()
    {
        return view('administrator.setup-item.product-element.unit.create');
    }
    public function store(Request $request)
    {
        return $this->update($request,null);
    }
    public function edit($id)
    {
        $master = UnitModel::find($id);
        return view('administrator.setup-item.product-element.unit.edit',compact('master'));
    }
    public function update(Request $request,$id)
    {
        $this->validate($request,[
            'unit'=>'required',
            'type'=>'required',
        ]);
        $master = UnitModel::updateOrCreate(['id'=>$id],$request->all());
        if ($request['input_name']) {
            return response()->json(['value' => $master->id, 'text' => $master->unit, 'input_name' => $request['input_name']]);
        }
        return response()->json(['status'=>'success','reload'=>1]);
    }

    public function import_excel(Request $request)
    {
        if ($request->export_sample) {
            return Excel::download(new UnitExport(), 'unit.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 UnitImport(), $path);
                    return response()->json(['status' => 'success', 'reload' => 1]);
                }
            } catch (\Exception $er) {
                throw ValidationException::withMessages($er->getMessage());
            }
        }
        return view('component.import-exel',['route'=>'Unit-import-excel']);
    }
}
