<?php

    namespace App\Http\Controllers\Administrator\setup;

    use App\Fun\Fun;
    use App\Exports\MemberPackageExport;
    use App\Imports\MemberPackageImport;
    use App\Model\product\ProductUnitModel;
    use App\Model\product\UnitModel;
    use App\Model\setup\MemberTypeModel;
    use Illuminate\Http\Request;
    use App\Http\Controllers\Controller;
    use App\Model\setup\MemberModel;
    use Carbon\Carbon;
    use Illuminate\Support\Facades\Auth;
    use Illuminate\Validation\ValidationException;
    use Maatwebsite\Excel\Facades\Excel;
    use Yajra\DataTables\Facades\DataTables;

    class MemberPackageController extends Controller
    {
        function __construct()
        {
//        $this->middleware('permission:Package System List', ['only' => ['index']]);
//        $this->middleware('permission:Package System Create', ['only' => ['create', 'store']]);
//        $this->middleware('permission:Package System Edit', ['only' => ['edit', 'update']]);
            Fun::lang();
        }

        public function index(Request $request)
        {
            if ($request->ajax()) {
                $member_type = $request->member_type;
                $data = MemberModel::join('nso007_products as p','p.id','nso007_member.product_id')
                    ->join('nso007_member_type as mt','mt.id','nso007_member.member_type')
                    ->when($member_type,function ($q) use ($member_type){
                        $q->where('nso007_member.member_type',$member_type);
                    })
                    ->selectRaw('nso007_member.*,p.product_name,mt.name as member_type_name,p.barcode')->orderBy('nso007_member.created_at','DESC');
                return DataTables::of($data)
                    ->addColumn('action', function ($action) {
                        return '<button  data-width="1000px" type="button" data-href = "' . route("member-package.edit", $action->id) . '"  class="button_warning getHtmlForm" title="Edit"><i class="fa fa-pencil"></i></button>';
                    })
                    ->editColumn('created_at', function ($action) {
                        return myDate($action->created_at);
                    })
                    ->editColumn('product_id', function ($action) {
                        return "$action->id-$action->product_id";
                    })

                    ->addIndexColumn()
                    ->rawColumns(['action'])
                    ->make(true);
            }

            return view('administrator.setup.member-package.index');
        }

        public function create()
        {
            return view('administrator.setup.member-package.create');
        }

        public function store(Request $request)
        {
            return $this->update($request, null);
        }

        public function edit($id)
        {
            $master = MemberModel::find($id);
            return view('administrator.setup.member-package.edit', compact('master', 'id'));
        }

        public function update(Request $request, $id)
        {
            $this->validate($request, [
                'product_id' => 'required',
                'product_id.*' => 'required',
                'member_type.*' => 'required',
                'price_riel.*' => 'required',
                'price_usd.*' => 'required',
            ]);

            $product = $request['product_id'];
            $price_riel = $request['price_riel'];
            $price_usd = $request['price_usd'];
            $member_type = $request['member_type'];

            foreach ($product as $key => $item) {
                MemberModel::updateOrCreate(
                    [
                        'product_id' => $item, 'member_type' => $member_type[$key]],
                    [
                        'user_id' => Auth::id(),
                        'product_id' => $item,
                        'member_type' => $member_type[$key],
                        'price_riel' => $price_riel[$key],
                        'price_usd' => $price_usd[$key],
                    ]);
            }
            return response()->json(['status' => 'success']);
        }

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