<?php

namespace App\Http\Controllers;

use App\Models\Ulasan;
use App\Models\Pesanan;
use Illuminate\Http\Request;

class UlasanController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

public function store(Request $request)
{
    $request->validate([
        'pesanan_id' => 'required|exists:pesanan,id',
        'produk_id'  => 'required|exists:produks,id',
        'bintang'    => 'required|integer|min:1|max:5',
        'komentar'   => 'nullable|string|max:1000',
    ]);

    $pesanan = Pesanan::where('id', $request->pesanan_id)
        ->where('user_id', auth()->id())
        ->where('status', 'selesai')
        ->firstOrFail();

    // Batasi jumlah ulasan sesuai jumlah item produk yang sama di pesanan
    $jumlahProdukSama = $pesanan->detail()
        ->where('produk_id', $request->produk_id)
        ->count();

    $jumlahUlasanAda = Ulasan::where('user_id', auth()->id())
        ->where('pesanan_id', $request->pesanan_id)
        ->where('produk_id', $request->produk_id)
        ->count();

    if ($jumlahUlasanAda >= $jumlahProdukSama) {
        return back()->with('error', 'Anda sudah mengulas semua produk ini.');
    }

    Ulasan::create([
        'user_id'    => auth()->id(),
        'pesanan_id' => $request->pesanan_id,
        'produk_id'  => $request->produk_id,
        'bintang'    => $request->bintang,
        'komentar'   => $request->komentar,
    ]);

    return back()->with('success', 'Ulasan berhasil dikirim! Terima kasih.');
}
}