<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\BorrowTransaction;
use App\Models\Rating;
use Illuminate\Support\Facades\Auth;

class UserRatingController extends Controller
{
    public function form($id)
    {
        $transaction = BorrowTransaction::findOrFail($id);

        if ($transaction->status !== 'dikembalikan') {
            return redirect()->route('user.peminjaman.index')
                ->with('error', 'Anda hanya bisa memberi penilaian setelah pengembalian disetujui admin.');
        }

        $existingRating = Rating::where('user_id', Auth::id())
            ->where('borrow_transaction_id', $transaction->id)
            ->first();

        return view('user.rating.form', compact('transaction', 'existingRating'));
    }

    public function store(Request $request, $id)
    {
        $transaction = BorrowTransaction::findOrFail($id);

        $existingRating = Rating::where('user_id', Auth::id())
            ->where('borrow_transaction_id', $transaction->id)
            ->first();

        if ($existingRating) {
            return redirect()->route('user.peminjaman.index')
                ->with('error', 'Anda sudah memberi penilaian untuk transaksi ini.');
        }

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

        Rating::create([
            'user_id' => Auth::id(),
            'borrow_transaction_id' => $transaction->id,
            'rating' => $request->rating,
            'feedback' => $request->feedback,
        ]);

        return redirect()->route('user.peminjaman.index')
            ->with('success', 'Terima kasih! Penilaian Anda telah kami terima 🙏');
    }
}

