<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Wine;
use Illuminate\Support\Facades\Session;

class CartController extends Controller
{
    /**
     * Display the shopping cart
     */
    public function index()
    {
        $cart = $this->getCart();
        $cartItems = [];
        $total = 0;

        foreach ($cart as $wineId => $item) {
            $wine = Wine::with('grapeVariety')->find($wineId);
            if ($wine) {
                $itemTotal = $wine->price_per_bottle * $item['quantity'];
                $cartItems[] = [
                    'wine' => $wine,
                    'quantity' => $item['quantity'],
                    'item_total' => $itemTotal,
                ];
                $total += $itemTotal;
            }
        }

        return view('cart.index', compact('cartItems', 'total'));
    }

    /**
     * Add item to cart
     */
    public function add(Request $request, $wineId)
    {
        $wine = Wine::findOrFail($wineId);

        $quantity = $request->input('quantity', 1);

        // Check stock availability
        if ($wine->bottles_in_stock < $quantity) {
            return redirect()->back()->with('error', 'Nedostatočné množstvo na sklade.');
        }

        $cart = $this->getCart();

        if (isset($cart[$wineId])) {
            $cart[$wineId]['quantity'] += $quantity;
        } else {
            $cart[$wineId] = [
                'quantity' => $quantity,
                'price' => $wine->price_per_bottle,
            ];
        }

        Session::put('cart', $cart);

        return redirect()->back()->with('success', 'Víno pridané do košíka.');
    }

    /**
     * Update cart item quantity
     */
    public function update(Request $request, $wineId)
    {
        $quantity = $request->input('quantity', 1);

        if ($quantity < 1) {
            return $this->remove($wineId);
        }

        $wine = Wine::findOrFail($wineId);

        // Check stock availability
        if ($wine->bottles_in_stock < $quantity) {
            return redirect()->back()->with('error', 'Nedostatočné množstvo na sklade.');
        }

        $cart = $this->getCart();

        if (isset($cart[$wineId])) {
            $cart[$wineId]['quantity'] = $quantity;
            Session::put('cart', $cart);
        }

        return redirect()->back()->with('success', 'Košík aktualizovaný.');
    }

    /**
     * Remove item from cart
     */
    public function remove($wineId)
    {
        $cart = $this->getCart();

        if (isset($cart[$wineId])) {
            unset($cart[$wineId]);
            Session::put('cart', $cart);
        }

        return redirect()->back()->with('success', 'Položka odstránená z košíka.');
    }

    /**
     * Clear entire cart
     */
    public function clear()
    {
        Session::forget('cart');
        return redirect()->route('cart.index')->with('success', 'Košík vyprázdnený.');
    }

    /**
     * Get cart from session
     */
    private function getCart()
    {
        return Session::get('cart', []);
    }

    /**
     * Get cart item count
     */
    public function count()
    {
        $cart = $this->getCart();
        $count = 0;

        foreach ($cart as $item) {
            $count += $item['quantity'];
        }

        return response()->json(['count' => $count]);
    }
}
