<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use App\Http\Requests\Backend\CouponRequest;
use App\Models\OrderManagement\Coupon;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;

class CouponController extends Controller{

    public function __construct(){

        $this->middleware('permission:coupon-list')
            ->only(["index"]);

        $this->middleware('permission:coupon-show')
            ->only(["show"]);

        $this->middleware('permission:coupon-create')
            ->only(["store"]);

        $this->middleware('permission:coupon-update')
            ->only(['update',"edit"]);

        $this->middleware('permission:coupon-delete')
            ->only(['destroy']);

    }

    public function index(): View{
        $coupons = Coupon::query()
            ->when(request()->keyword != null, function ($query) {
                $query->search(request()->keyword);
            })
            ->when(request()->active != null, function ($query) {
                $query->whereStatus(request()->active);
            })
            ->orderBy(request()->sortBy ?? 'id', request()->orderBy ?? 'desc')
            ->paginate(request()->limitBy ?? 10);

        return view('backend.coupons.index', compact('coupons'));
    }

    public function create(): View{
        return view('backend.coupons.create');
    }

    public function store(CouponRequest $request): RedirectResponse{
        Coupon::create($request->validated());

        return redirect()->route('admin.coupons.index')->with([
            'message' => action_message("create"),
            'alert-type' => 'success'
        ]);
    }

    public function show(Coupon $coupon): View{
        return view('backend.coupons.show', compact('coupon'));
    }

    public function edit(Coupon $coupon): View{
        return view('backend.coupons.edit', compact('coupon'));
    }

    public function update(CouponRequest $request, Coupon $coupon): RedirectResponse{
        $coupon->update($request->validated());
        return redirect()->route('admin.coupons.index')->with([
            'message' => action_message("update"),
            'alert-type' => 'success'
        ]);
    }

    public function destroy(Coupon $coupon): RedirectResponse{
        $coupon->delete();

        return redirect()->route('admin.coupons.index')->with([
            'message' => action_message("delete"),
            'alert-type' => 'success'
        ]);
    }
}
