<?php

namespace App\Http\Controllers\Shop;

use App\Http\Controllers\Controller;
use App\Models\Review;
use App\Models\ReviewImage;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;

class ReviewController extends Controller
{
    public function store(Request $request)
    {
        $request->validate([
            'product_id' => 'required|exists:products,id',
            'order_id' => 'nullable|exists:orders,id',
            'rating' => 'required|integer|min:1|max:5',
            'title' => 'nullable|string|max:255',
            'body' => 'required|string|min:10|max:2000',
            'images' => 'nullable|array|max:5',
            'images.*' => 'image|max:2048',
        ]);

        // Check if user has purchased this product
        $hasPurchased = false;
        if ($request->order_id) {
            $order = Auth::user()->orders()
                ->where('id', $request->order_id)
                ->where('status', 'delivered')
                ->whereHas('items', fn($q) => $q->where('product_id', $request->product_id))
                ->first();
            $hasPurchased = $order !== null;
        }

        // Check if user already reviewed this product for this order
        if ($request->order_id) {
            $existingReview = Review::where('user_id', Auth::id())
                ->where('product_id', $request->product_id)
                ->where('order_id', $request->order_id)
                ->first();

            if ($existingReview) {
                return back()->with('error', 'You have already reviewed this product for this order.');
            }
        }

        $review = Review::create([
            'product_id' => $request->product_id,
            'user_id' => Auth::id(),
            'order_id' => $request->order_id,
            'rating' => $request->rating,
            'title' => $request->title,
            'body' => $request->body,
            'is_approved' => true, // Auto-approve for now, can be changed
            'is_verified_purchase' => $hasPurchased,
        ]);

        // Handle review images
        if ($request->hasFile('images')) {
            foreach ($request->file('images') as $image) {
                $path = $image->store('review-images', 'public');
                ReviewImage::create([
                    'review_id' => $review->id,
                    'image_path' => $path,
                ]);
            }
        }

        return back()->with('success', 'Review submitted successfully!');
    }

    public function helpful($id)
    {
        $review = Review::findOrFail($id);
        $review->incrementHelpful();
        
        return back()->with('success', 'Thank you for your feedback!');
    }
}
