<?php

namespace App\Http\Controllers;

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

class ReviewController extends Controller
{
    public function create(Order $order)
    {
        if (Auth::user()->role !== 'user') abort(403, 'Akses ditolak.');
        if ($order->user_id !== Auth::id()) abort(403, 'Bukan pesananmu.');
        if ($order->status !== 'completed') abort(403, 'Pesanan belum selesai.');

        $order->load('items.product');

        $reviewedProductIds = Review::where('order_id', $order->id)
            ->where('user_id', Auth::id())
            ->pluck('product_id')
            ->toArray();

        return view('reviews.create', compact('order', 'reviewedProductIds'));
    }

    public function store(Request $request, Order $order)
    {
        if (Auth::user()->role !== 'user') abort(403, 'Akses ditolak.');
        if ($order->user_id !== Auth::id()) abort(403, 'Bukan pesananmu.');
        if ($order->status !== 'completed') abort(403, 'Pesanan belum selesai.');

        $request->validate([
            'reviews'              => 'required|array',
            'reviews.*.product_id' => 'required|exists:products,id',
            'reviews.*.rating'     => 'required|integer|min:1|max:5',
            'reviews.*.comment'    => 'nullable|string|max:500',
            'reviews.*.image'      => 'nullable|image|mimes:jpg,jpeg,png,webp|max:2048',
        ]);

        // Ambil semua file uploaded secara eksplisit
        // $request->file('reviews') returns array seperti ['0' => ['image' => UploadedFile]]
        $uploadedFiles = $request->file('reviews') ?? [];

        foreach ($request->reviews as $index => $r) {
            $belongsToOrder = $order->items->contains('product_id', $r['product_id']);
            if (!$belongsToOrder) continue;

            // Ambil file dari array yang sudah di-resolve Laravel
            $uploadedFile = $uploadedFiles[$index]['image'] ?? null;

            // Ambil review lama jika ada
            $existing = Review::where('user_id', Auth::id())
                               ->where('product_id', $r['product_id'])
                               ->where('order_id', $order->id)
                               ->first();

            $imagePath = $existing?->image; // default: pakai foto lama

            if ($uploadedFile && $uploadedFile->isValid()) {
                // Hapus foto lama dulu
                if ($existing?->image) {
                    Storage::disk('public')->delete($existing->image);
                }
                // Simpan foto baru ke storage/app/public/reviews/
                $imagePath = $uploadedFile->store('reviews', 'public');
            }

            Review::updateOrCreate(
                [
                    'user_id'    => Auth::id(),
                    'product_id' => $r['product_id'],
                    'order_id'   => $order->id,
                ],
                [
                    'rating'  => $r['rating'],
                    'comment' => $r['comment'] ?? null,
                    'image'   => $imagePath,
                ]
            );
        }

        return redirect()
            ->route('user.orders.show', $order->id)
            ->with('success', 'Makasih udah kasih review! ⭐');
    }
}