<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Review;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;

class ReviewController extends Controller
{
    public function addReview(Request $request)
    {
        try {
            $request->validate([
                'title' => 'required|string|max:255',
                'content' => 'required|string|max:1000',
                'rating' => 'required|integer|min:1|max:5',
                'course_id' => 'required|exists:courses,id',
            ]);
        } catch (ValidationException $e) {
            return sendCustomResponse(false, '', $e->getMessage(), $e->errors(), 422);
        }

        $user_id = Auth::guard('sanctum')->id();
        $check = Review::where(['user_id'=>$user_id,'course_id'=>$request->course_id])->count();

        if($check):
            return sendCustomResponse(false, '', "This course has already been Reviewed.", "", 422);
        endif;
        $review = new Review();
        $review->title = $request->title;
        $review->content = $request->content;
        $review->rating = $request->rating;
        $review->user_id = $user_id;
        $review->course_id = $request->course_id;
        $review->save();
        return sendCustomResponse(true, '', "Review has been added successfully", '', 200);
    }
}
