<?php

namespace App\Http\Controllers\Marketplace;

use App\Http\Controllers\Controller;
use App\Models\Cart;
use App\Models\Currency;
use App\Models\PaymentGateway;
use App\Models\Country;
use App\Models\UserAddress;
use App\Models\Product; 
use Illuminate\Http\Request;
use Inertia\Inertia;

class CartController extends Controller
{
    public function index()
    {
        $userId = auth()->id();

        $cartItems = Cart::with(['product.images', 'product.seller'])
            ->where('user_id', $userId)
            ->latest()
            ->get();

        $userCountryIso2 = auth()->user()->country_id 
            ? Country::find(auth()->user()->country_id)?->iso2 
            : null;

        $addresses = UserAddress::with(['country', 'state', 'city'])
            ->where('user_id', $userId)
            ->get();

        $gateways = PaymentGateway::where('is_active', true)->get()->map(function ($g) {
            $creds = ($g->mode === 'live' ? $g->live_credentials : $g->test_credentials) ?? [];
            return [
                'code' => $g->code,
                'name' => $g->name,
                'is_global' => $g->is_global,
                'allowed_countries' => $g->allowed_countries,
                'supported_currencies' => $g->supported_currencies,
                'instructions' => $g->code === 'manual' ? ($creds['payment_instructions'] ?? '') : null,
            ];
        });

        return Inertia::render('Marketplace/Cart', [
            'cartItems' => $cartItems,
            'currencies' => Currency::where('is_active', true)->get(['code', 'symbol', 'exchange_rate']),
            'gateways' => $gateways,
            'userCountryIso2' => $userCountryIso2,
            'addresses' => $addresses 
        ]);
    }

    public function store(Request $request)
    {
        $request->validate([
            'product_id' => 'required|exists:products,id',
            'quantity'   => 'required|integer|min:1',
            'variations' => 'nullable|array' 
        ]);

        $product = Product::findOrFail($request->product_id);
        
        // --- STRICT SECURITY: Prevent buying own product ---
        // Cast to int to prevent string mismatch
        if ((int) auth()->id() === (int) $product->seller_id) {
            return back()->withErrors(['error' => 'You cannot add your own product to the cart.']);
        }

        $requestedVariations = $request->variations ?? [];

        $existingCarts = Cart::where('user_id', auth()->id())
            ->where('product_id', $product->id)
            ->get();

        $cart = null;
        foreach ($existingCarts as $existingCart) {
            $existingVars = $existingCart->selected_variations ?? [];
            if ($existingVars == $requestedVariations) {
                $cart = $existingCart;
                break;
            }
        }

        if (!$cart) {
            $cart = new Cart([
                'user_id' => auth()->id(),
                'product_id' => $product->id,
                'selected_variations' => $requestedVariations 
            ]);
        }

        $newQuantity = $cart->exists ? $cart->quantity + $request->quantity : $request->quantity;

        if ($newQuantity > $product->stock) {
            return back()->withErrors(['error' => "Cannot add more items. Only {$product->stock} available in stock."]);
        }

        $cart->quantity = $newQuantity;
        $cart->save();

        return back()->with('success', 'Product added to your cart!');
    }

    public function update(Request $request, Cart $cart)
    {
        // --- Cast to int to prevent strict type failures ---
        if ((int) $cart->user_id !== (int) auth()->id()) {
            abort(403, 'Unauthorized action.');
        }
        
        $request->validate(['quantity' => 'required|integer|min:1']);

        // SECURE STOCK VALIDATION
        if ($request->quantity > $cart->product->stock) {
            return back()->withErrors(['error' => "Only {$cart->product->stock} items available in stock."]);
        }

        $cart->update(['quantity' => $request->quantity]);
        
        return back();
    }

    public function destroy(Cart $cart)
    {
        // --- F Cast to int to prevent strict type failures ---
        if ((int) $cart->user_id !== (int) auth()->id()) {
            abort(403, 'Unauthorized action.');
        }
        
        $cart->delete();
        return back()->with('success', 'Item removed from cart.');
    }
}