<?php

namespace App\Http\Controllers;

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

/**
 * Carrito gestionado con sesiones de Laravel.
 * Estructura en sesión: cart[product_id] = [name, price, image_url, quantity]
 */
class CartController extends Controller
{
    public function add(Request $request)
    {
        $request->validate([
            'product_id' => 'required|exists:products,id',
            'quantity'   => 'required|integer|min:1',
        ]);

        $product = Product::findOrFail($request->product_id);
        $cart = session()->get('cart', []);

        if (isset($cart[$product->id])) {
            $cart[$product->id]['quantity'] += $request->quantity;
        } else {
            $cart[$product->id] = [
                'name'      => $product->name,
                'price'     => $product->active_price, // usa el accesor (oferta o normal)
                'image_url' => $product->image_url,
                'quantity'  => $request->quantity,
            ];
        }

        session()->put('cart', $cart);
        return redirect()->back()->with('success', '¡Producto añadido al carrito!');
    }

    public function update(Request $request)
    {
        $request->validate([
            'product_id' => 'required|integer',
            'quantity'   => 'required|integer|min:0',
        ]);

        $cart = session()->get('cart', []);
        if ($request->quantity === 0) {
            unset($cart[$request->product_id]);
        } elseif (isset($cart[$request->product_id])) {
            $cart[$request->product_id]['quantity'] = $request->quantity;
        }
        session()->put('cart', $cart);

        return redirect()->route('cart.index');
    }

    public function remove(Request $request)
    {
        $cart = session()->get('cart', []);
        unset($cart[$request->product_id]);
        session()->put('cart', $cart);
        return redirect()->route('cart.index');
    }

    public function index()
    {
        $cart = session()->get('cart', []);
        $total = collect($cart)->sum(fn ($i) => $i['price'] * $i['quantity']);
        return view('store.cart', compact('cart', 'total'));
    }
}
