<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class CartController extends Controller
{
    public function index()
    {
        $cart = session()->get('cart', []);
        return view('cart.index', compact('cart'));
    }

    public function add(Request $request)
    {
        $item = $request->only(['id', 'name', 'quantity']);

        $cart = session()->get('cart', []);
        $found = false;

        foreach ($cart as &$c) {
            if ($c['id'] == $item['id']) {
                $c['quantity'] += $item['quantity'];
                $found = true;
                break;
            }
        }

        if (!$found) {
            $cart[] = $item;
        }

        session(['cart' => $cart, 'cart_count' => array_sum(array_column($cart, 'quantity'))]);

        return redirect()->route('cart.index')->with('success', 'Item ditambahkan ke keranjang!');
    }

    public function remove(Request $request)
    {
        $cart = session()->get('cart', []);
        $cart = array_filter($cart, fn($item) => $item['id'] != $request->id);

        session(['cart' => $cart, 'cart_count' => array_sum(array_column($cart, 'quantity'))]);

        return redirect()->route('cart.index')->with('success', 'Item dihapus dari keranjang!');
    }

    public function clear()
    {
        session()->forget(['cart', 'cart_count']);

        return redirect()->route('cart.index')->with('success', 'Keranjang dikosongkan!');
    }
}
