<?php

namespace App\Http\Controllers;

use App\Models\Booking;
use App\Models\Review;
use Illuminate\Http\Request;

class ReviewController extends Controller
{
    public function store(Request $request, Booking $booking)
    {
        // Only allow paid/completed bookings to be reviewed
        if ($booking->status !== 'paid' && $booking->status !== 'completed_approved') {
            return response()->json(['message' => 'Booking must be completed to leave a review'], 400);
        }

        // Determine reviewer and reviewee
        $user = $request->user();
        $isClient = $user->id === $booking->job->client_id;
        $isWorker = $user->id === $booking->worker_id;

        if (!$isClient && !$isWorker) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }

        // Check for existing review
        if (Review::where('booking_id', $booking->id)->where('reviewer_id', $user->id)->exists()) {
            return response()->json(['message' => 'You have already reviewed this booking'], 400);
        }

        $request->validate([
            'rating' => 'required|integer|min:1|max:5',
            'comment' => 'nullable|string',
        ]);

        $review = Review::create([
            'booking_id' => $booking->id,
            'reviewer_id' => $user->id,
            'reviewee_id' => $isClient ? $booking->worker_id : $booking->job->client_id,
            'rating' => $request->rating,
            'comment' => $request->comment,
        ]);

        return response()->json($review, 201);
    }
    
    public function index(Request $request)
    {
        // Get reviews FOR the current user
        return Review::with('reviewer')->where('reviewee_id', $request->user()->id)->latest()->get();
    }
}
