<?php

namespace App\Http\Controllers;

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

class CartController extends Controller
{
    // ── Show Cart ────────────────────────────────────────────────────────────
    public function index()
    {
        $cart = $this->getOrCreateCart();
        $cartItems = $cart->items()->with('product.images')->get();

        $subtotal = $cartItems->sum(function ($item) {
            $price = ($item->product->is_on_sale && $item->product->discount_price)
                ? $item->product->discount_price
                : $item->product->price;
            return $price * $item->quantity;
        });

        return view('cart', compact('cartItems', 'subtotal'));
    }

    // ── Add to Cart ──────────────────────────────────────────────────────────
    public function add(Request $request)
    {
        $request->validate([
            'product_id' => 'required|exists:products,id',
            'quantity'   => 'integer|min:1',
        ]);

        $product  = Product::findOrFail($request->product_id);
        $quantity = $request->quantity ?? 1;
        $cart     = $this->getOrCreateCart();

        $item = $cart->items()->where('product_id', $product->id)->first();

        if ($item) {
            $item->increment('quantity', $quantity);
        } else {
            $cart->items()->create([
                'product_id' => $product->id,
                'quantity'   => $quantity,
            ]);
        }

        $cartCount = $cart->items()->sum('quantity');
        $cartTotal = $this->calcTotal($cart);

        return response()->json([
            'success'    => true,
            'message'    => 'Added to cart!',
            'cart_count' => $cartCount,
            'cart_total' => number_format($cartTotal, 2),
        ]);
    }

    // ── Update Quantity ──────────────────────────────────────────────────────
    public function update(Request $request)
    {
        $request->validate([
            'item_id'  => 'required|exists:cart_items,id',
            'quantity' => 'required|integer|min:1',
        ]);

        $item = CartItem::findOrFail($request->item_id);
        $item->update(['quantity' => $request->quantity]);

        $cart      = $this->getOrCreateCart();
        $cartCount = $cart->items()->sum('quantity');
        $cartTotal = $this->calcTotal($cart);

        return response()->json([
            'success'    => true,
            'cart_count' => $cartCount,
            'cart_total' => number_format($cartTotal, 2),
        ]);
    }

    // ── Remove Item ──────────────────────────────────────────────────────────
    public function remove(Request $request)
    {
        $request->validate(['item_id' => 'required|exists:cart_items,id']);

        CartItem::findOrFail($request->item_id)->delete();

        $cart      = $this->getOrCreateCart();
        $cartCount = $cart->items()->sum('quantity');

        return response()->json([
            'success'    => true,
            'cart_count' => $cartCount,
        ]);
    }

    // ── Helpers ──────────────────────────────────────────────────────────────
    private function getOrCreateCart()
    {
        if (auth()->check()) {
            return Cart::firstOrCreate(['user_id' => auth()->id()]);
        }

        $sessionId = session()->getId();
        return Cart::firstOrCreate(['session_id' => $sessionId]);
    }

    private function calcTotal(Cart $cart)
    {
        return $cart->items()->with('product')->get()->sum(function ($item) {
            $price = ($item->product->is_on_sale && $item->product->discount_price)
                ? $item->product->discount_price
                : $item->product->price;
            return $price * $item->quantity;
        });
    }

    public function checkout()
    {
        // This will be implemented in the next steps
        return view('checkout');
    }
}
