<?php


namespace App\Http\Controllers\Administrator\setup;


use App\Fun\Fun;
use App\Model\setup\PackerModel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DataTables;
use Auth;
use Illuminate\Support\Facades\Gate;

class PackerController extends Controller

{
    function __construct()
    {
        $this->middleware('permission:Packer List', ['only' => ['index']]);
        $this->middleware('permission:Packer Create', ['only' => ['create', 'store']]);
        $this->middleware('permission:Packer Edit', ['only' => ['edit', 'update']]);
    }

    public function index(Request $request)
    {
        if ($request->ajax()) {
            Fun::lang();
            $data = PackerModel::latest();
            return Datatables::of($data)
                ->addIndexColumn()
                ->addColumn('action', function ($data) {
                    $btn = '';
                    if (Gate::check('Packer Show')) {
                        $btn .= '<button title="' . __('administrator.show') . '"
                        class="button_warning" >' . __('administrator.show') . '</button>';
                    }
                    if (Gate::check('Packer Edit')) {
                        $btn .= '<button class="button_warning getHtmlForm" data-href="' . route('packers.edit', $data->id) . '">' . __('administrator.edit') . '</button>';
                    }
                    return $btn;
                })

                ->editColumn('fee', function ($data) {
                    $cur = findCurrency($data->currency_id)->symbol??'';
                    return "$data->fee $cur";
                })

                ->rawColumns(['action', 'logo', 'main'])
                ->make(true);
        }
        return view('administrator.setup.packer.index');
    }

    public function create()
    {
        return view('administrator.setup.packer.create');
    }

    public function store(Request $request)
    {
        $this->update($request, null);
        return response()->json(['status' => 'success']);
    }

    public function edit($id)
    {
        $master = PackerModel::find($id);
        return view('administrator.setup.packer.edit', compact('master'));
    }

    public function update(Request $request, $id)

    {
        $this->validate($request, [
            'name' => 'required|max:100|unique:nso007_packer,name,' . $id,
            'currency_id' => 'required',
            'fee' => 'required',
        ]);
        $data = $request->all();
        $data['user_id'] = auth()->id();
        PackerModel::updateOrCreate(['id' => $id], $data);
        return response()->json(['status' => 'success']);
    }
}
