<?php

namespace TPS\Shop\Http\Controllers;

use Webkul\Product\Repositories\ProductReviewRepository;
use Webkul\Shop\Http\Controllers\Controller;

class ReviewController extends Controller
{
    public function __construct(
        protected ProductReviewRepository $productReviewRepository,
    )
    {
        parent::__construct();
    }

    public function index($product_id){
        return $this->productReviewRepository->where('product_id', $product_id)
            ->where('status','approved')
            ->select('comment', 'rating','name', 'created_at')
            ->orderBy('created_at', 'desc')
            ->paginate(5);
    }

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

        $data = array_merge(request()->all(), [
            'status'     => 'pending',
            'product_id' => $product_id,
            'title' => 'Review'
        ]);

        if (auth()->guard('customer')->user()) {
            $data['customer_id'] = auth()->guard('customer')->user()->id;

            $data['name'] = auth()->guard('customer')->user()->first_name . ' ' . auth()->guard('customer')->user()->last_name;
        }

        if($review = $this->productReviewRepository->create($data)){
            return response()->json(['success' => true,'data'=>$review]);
        }

        return response()->json(['success' => false,'message'=>trans('shop::app.common.error')]);
    }

}