<?php

namespace App\Http\Controllers\Api;

use App\Models\Booking;
use App\Models\TailorRating;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class RatingController extends BaseController
{
    /**
     * Store a new rating
     */
    public function store(Request $request, Booking $booking)
    {
        $validator = Validator::make($request->all(), [
            'rating' => 'required|numeric|min:0|max:5',
            'review' => 'nullable|string|max:1000'
        ]);

        if ($validator->fails()) {
            return $this->sendError('Error validasi.', $validator->errors(), 422);
        }

        try {
            // Check if booking belongs to the authenticated user
            if ($booking->customer_id !== Auth::id()) {
                return $this->sendError('Unauthorized.', ['error' => 'Anda tidak memiliki akses untuk memberikan rating pada booking ini'], 403);
            }

            // Check if booking is completed
            if ($booking->status !== 'selesai') {
                return $this->sendError('Error validasi.', ['error' => 'Anda hanya dapat memberikan rating untuk pesanan yang telah selesai'], 422);
            }

            // Check if rating already exists
            if (TailorRating::where('booking_id', $booking->id)->where('customer_id', Auth::id())->exists()) {
                return $this->sendError('Error validasi.', ['error' => 'Anda sudah memberikan rating untuk pesanan ini'], 422);
            }

            $rating = TailorRating::create([
                'booking_id' => $booking->id,
                'customer_id' => Auth::id(),
                'tailor_id' => $booking->tailor_id,
                'rating' => $request->rating,
                'review' => $request->review
            ]);

            return $this->sendResponse($rating, 'Rating berhasil ditambahkan.');
        } catch (\Exception $e) {
            return $this->sendError('Error.', ['error' => 'Terjadi kesalahan saat menambahkan rating'], 500);
        }
    }

    /**
     * Get tailor's ratings
     */
    public function getTailorRatings($tailorId)
    {
        try {
            $ratings = TailorRating::where('tailor_id', $tailorId)
                ->with(['customer:id,name', 'booking'])
                ->orderBy('created_at', 'desc')
                ->get();

            $averageRating = $ratings->avg('rating');

            return $this->sendResponse([
                'ratings' => $ratings,
                'average_rating' => round($averageRating, 1),
                'total_ratings' => $ratings->count()
            ], 'Data rating berhasil diambil.');
        } catch (\Exception $e) {
            return $this->sendError('Error.', ['error' => 'Terjadi kesalahan saat mengambil data rating'], 500);
        }
    }

    /**
     * Update a rating
     */
    public function update(Request $request, TailorRating $rating)
    {
        $validator = Validator::make($request->all(), [
            'rating' => 'required|numeric|min:0|max:5',
            'review' => 'nullable|string|max:1000'
        ]);

        if ($validator->fails()) {
            return $this->sendError('Error validasi.', $validator->errors(), 422);
        }

        try {
            // Check if rating belongs to the authenticated user
            if ($rating->customer_id !== Auth::id()) {
                return $this->sendError('Unauthorized.', ['error' => 'Anda tidak memiliki akses untuk mengubah rating ini'], 403);
            }

            $rating->update([
                'rating' => $request->rating,
                'review' => $request->review
            ]);

            return $this->sendResponse($rating, 'Rating berhasil diupdate.');
        } catch (\Exception $e) {
            return $this->sendError('Error.', ['error' => 'Terjadi kesalahan saat mengupdate rating'], 500);
        }
    }
}
