<?php

namespace App\Http\Controllers;

use App\Models\Product;
use Illuminate\Http\Request;

class CartController extends Controller
{
    public function index()
    {
        $cart = session()->get('cart', []);
        $total = 0;
        
        // Refresh stock levels to ensure they are up to date
        foreach ($cart as $id => $item) {
            $product = Product::find($id);
            if ($product) {
                $cart[$id]['en_stock'] = $product->en_stock;
                $cart[$id]['image'] = $product->image; // Refresh image
            }
            $total += $item['prix'] * $item['quantite'];
        }
        
        session()->put('cart', $cart); // Save refreshed stock levels
        
        return view('cart.index', compact('cart', 'total'));
    }

    public function add(Request $request, $id)
    {
        $product = Product::findOrFail($id);
        $quantite = (int) $request->input('quantite', 1);
        
        $cart = session()->get('cart', []);
        
        $currentQuantite = isset($cart[$id]) ? $cart[$id]['quantite'] : 0;
        $totalRequested = $currentQuantite + $quantite;

        if ($totalRequested > $product->en_stock) {
            return redirect()->back()->with('error', "Désolé, seulement {$product->en_stock} unités sont disponibles en stock.");
        }
        
        if (isset($cart[$id])) {
            $cart[$id]['quantite'] = $totalRequested;
        } else {
            $cart[$id] = [
                'nom' => $product->name,
                'marque' => $product->marque,
                'dimension' => $product->dimension,
                'prix' => $product->prix_actuel,
                'quantite' => $quantite,
                'en_stock' => $product->en_stock,
                'image' => $product->image,
            ];
        }
        
        session()->put('cart', $cart);
        
        return redirect()->back()->with('success', 'Produit ajouté au panier!');
    }

    public function update(Request $request, $id)
    {
        $product = Product::findOrFail($id);
        $quantite = (int) $request->input('quantite');
        
        if ($quantite > $product->en_stock) {
            return redirect()->back()->with('error', "Désolé, seulement {$product->en_stock} unités sont disponibles en stock.");
        }

        $cart = session()->get('cart', []);
        
        if (isset($cart[$id])) {
            $cart[$id]['quantite'] = $quantite;
            session()->put('cart', $cart);
        }
        
        return redirect()->route('cart.index')->with('success', 'Panier mis à jour!');
    }

    public function remove($id)
    {
        $cart = session()->get('cart', []);
        
        if (isset($cart[$id])) {
            unset($cart[$id]);
            session()->put('cart', $cart);
        }
        
        return redirect()->route('cart.index')->with('success', 'Produit retiré du panier!');
    }

    public function clear()
    {
        session()->forget('cart');
        return redirect()->route('cart.index')->with('success', 'Panier vidé!');
    }
}
