<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use App\Http\Requests\Backend\ReviewRequest;
use App\Models\ProductManagement\Review;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;

class ReviewController extends Controller{
    public function __construct(){

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

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

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

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

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

    }

    public function index(): View{
        $reviews = Review::with('product', 'user')
            ->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.reviews.index', compact('reviews'));
    }

    public function show(Review $review): View{
        return view('backend.reviews.show', compact('review'));
    }

    public function edit(Review $review): View{
        return view('backend.reviews.edit', compact('review'));
    }

    public function update(ReviewRequest $request, Review $review): RedirectResponse{
        $review->update($request->validated());

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

    public function destroy(Review $review): RedirectResponse{
        $review->delete();

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