<?php

namespace TPS\API\Http\Controllers;

use Illuminate\Http\Request;
use TPS\API\Http\Resources\Customer\ReviewResource;
use Webkul\RestApi\Http\Controllers\V1\Shop\Catalog\ProductReviewController;

class Reviews extends ProductReviewController
{
    /**
     * Resource class name.
     *
     * @return string
     */
    public function resource()
    {
        return ReviewResource::class;
    }

    public function store(Request $request, int $productId){
        $this->validate($request, [
            'comment' => 'required',
            'rating'  => 'required|numeric|min:1|max:5',
//            'title'   => 'required',
        ]);

        $customer = $request->user();

        $productReview = $this->getRepositoryInstance()->create([
            'customer_id' => $customer->id,
            'name'        => $customer->name,
            'status'      => 'pending',
            'product_id'  => $productId,
            'comment'     => $request->comment,
            'rating'      => $request->rating,
            'title'       => $customer->name.' review',
        ]);

        return response([
            'data'    => new ReviewResource($productReview),
            'message' => 'Your review submitted successfully.',
        ]);
    }

    public function productReviews($productId){
        $query = $this->getRepositoryInstance()->scopeQuery(function ($query) use ($productId) {
            $query = $query->where('product_id', $productId)->where('status','approved');

            foreach (request()->except($this->requestException) as $input => $value) {
                $query = $query->whereIn($input, array_map('trim', explode(',', $value)));
            }

            if ($sort = request()->input('sort')) {
                $query = $query->orderBy($sort, request()->input('order') ?? 'desc');
            } else {
                $query = $query->orderBy('id', 'desc');
            }

            return $query;
        });

        if (is_null(request()->input('pagination')) ||request()->input('pagination')) {
            $results = $query->paginate(request()->input('limit') ?? 10);
        } else {
            $results = $query->get();
        }

        return $this->getResourceCollection($results);
    }

}