<?php

namespace App\Http\Controllers;

use App\Models\Order;
use App\Models\ProductReview;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class ReviewController extends Controller
{
    public function create($orderId)
    {
        $order = Order::with('orderItems.product')->findOrFail($orderId);

        if ($order->user_id != Auth::id() && $order->customer_email != Auth::user()->email) {
            abort(403, 'Akses ditolak.');
        }

        if (strtolower($order->status) !== 'completed') {
            return redirect()->route('front.orders')->with('error', 'Pesanan belum selesai, tidak bisa memberi ulasan.');
        }

        return view('front.review_form', compact('order'));
    }

    public function store(Request $request, $orderId)
    {
        $order = Order::with('orderItems', 'product')->findOrFail($orderId);

        if ($order->user_id != Auth::id() && $order->customer_email != Auth::user()->email) {
            abort(403);
        }

        // Validate multiple inputs per product
        $request->validate([
            'reviews.*.product_id' => 'required|exists:products,id',
            'reviews.*.rating' => 'required|integer|min:1|max:5',
            'reviews.*.review' => 'nullable|string',
            'reviews.*.photo' => 'nullable|image|max:2048',
        ]);

        $reviewsData = $request->input('reviews', []);
        $files = $request->file('reviews', []);

        foreach ($reviewsData as $index => $item) {
            // Cek apakah sudah pernah direview agar tidak double
            $existing = ProductReview::where('order_id', $orderId)
                ->where('product_id', $item['product_id'])
                ->first();

            if (! $existing) {
                $photoPath = null;
                if (isset($files[$index]['photo'])) {
                    $photoPath = $files[$index]['photo']->store('reviews', 'public');
                }

                ProductReview::create([
                    'user_id' => Auth::id(),
                    'product_id' => $item['product_id'],
                    'order_id' => $orderId,
                    'rating' => $item['rating'],
                    'review' => $item['review'],
                    'photo' => $photoPath,
                ]);
            }
        }

        return redirect()->route('front.orders')->with('success', 'Terima kasih atas ulasan Anda!');
    }

    public function destroy($id)
    {
        $review = ProductReview::findOrFail($id);

        // Hanya pembuat atau admin
        if ($review->user_id == Auth::id() || (Auth::check() && Auth::user()->is_admin)) {
            if ($review->photo) {
                \Illuminate\Support\Facades\Storage::disk('public')->delete($review->photo);
            }
            $review->delete();
            return back()->with('success', 'Ulasan berhasil dihapus.');
        }

        abort(403);
    }
}
