<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class CartController extends Controller
{
    private function sessionId(): string
    {
        return session()->getId();
    }

    private function cartQuery()
    {
        $q = \App\Models\CartItem::with('product')->where('session_id', $this->sessionId());
        if (auth()->check()) {
            $q->orWhere('user_id', auth()->id());
        }
        return $q;
    }

    public function index()
    {
        $items = $this->cartQuery()->get();
        $subtotal = $items->sum(fn($i) => $i->product->price * $i->qty);
        $original = $items->sum(fn($i) => ($i->product->old_price ?? $i->product->price) * $i->qty);
        return view('cart', compact('items', 'subtotal', 'original'));
    }

    public function add(Request $request)
    {
        $request->validate(['product_id' => 'required|exists:products,id', 'qty' => 'integer|min:1']);
        $sid  = $this->sessionId();
        $uid  = auth()->id();
        $item = \App\Models\CartItem::where('session_id', $sid)
            ->where('product_id', $request->product_id)->first();
        if ($item) {
            $item->increment('qty', $request->qty ?? 1);
        } else {
            \App\Models\CartItem::create([
                'session_id' => $sid,
                'user_id'    => $uid,
                'product_id' => $request->product_id,
                'qty'        => $request->qty ?? 1,
            ]);
        }
        return back()->with('success', 'Added to cart!');
    }

    public function update(Request $request, int $id)
    {
        $request->validate(['qty' => 'required|integer|min:1']);
        $item = \App\Models\CartItem::where('id', $id)
            ->where('session_id', $this->sessionId())->firstOrFail();
        $item->update(['qty' => $request->qty]);
        return back();
    }

    public function remove(int $id)
    {
        \App\Models\CartItem::where('id', $id)
            ->where('session_id', $this->sessionId())->delete();
        return back()->with('success', 'Item removed.');
    }

    public function clear()
    {
        $this->cartQuery()->delete();
        return back()->with('success', 'Cart cleared.');
    }

    public function count()
    {
        $count = $this->cartQuery()->sum('qty');
        return response()->json(['count' => $count]);
    }
}
