<?php

namespace App\Http\Controllers;

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

class CartController extends Controller
{
    private function getCart(): array
    {
        return session('cart', []);
    }

    private function saveCart(array $cart): void
    {
        session(['cart' => $cart]);
    }

    public function index()
    {
        $cart  = $this->getCart();
        $items = [];

        if (!empty($cart)) {
            $variantIds = array_column($cart, 'variant_id');
            $variants   = ProductVariant::with('product')
                ->whereIn('id', $variantIds)
                ->get()
                ->keyBy('id');

            foreach ($cart as $key => $row) {
                $variant = $variants->get($row['variant_id']);
                if (!$variant) continue;
                $items[] = [
                    'key'     => $key,
                    'variant' => $variant,
                    'product' => $variant->product,
                    'qty'     => $row['qty'],
                ];
            }
        }

        return view('site.cart', compact('items'));
    }

    public function add(Request $request)
    {
        $request->validate([
            'variant_id' => 'required|exists:product_variants,id',
            'qty'        => 'integer|min:1|max:99',
        ]);

        $variantId = (int) $request->variant_id;
        $qty       = max(1, (int) $request->input('qty', 1));
        $key       = 'v_' . $variantId;
        $cart      = $this->getCart();

        $variant   = \App\Models\ProductVariant::find($variantId);
        $stock     = (int) ($variant->stock ?? 0);
        $inCart    = isset($cart[$key]) ? (int) $cart[$key]['qty'] : 0;
        $newQty    = $inCart + $qty;

        if ($stock <= 0) {
            $msg = 'این محصول در حال حاضر ناموجود است.';
            if ($request->ajax()) {
                return response()->json(['success' => false, 'message' => $msg], 422);
            }
            return redirect()->back()->withErrors(['qty' => $msg]);
        }

        if ($newQty > $stock) {
            $msg = $inCart > 0
                ? "حداکثر {$stock} عدد از این محصول می‌توانید سفارش دهید (در حال حاضر {$inCart} عدد در سبد شماست)."
                : "تعداد انتخابی شما بیشتر از موجودی انبار می‌باشد. موجودی انبار {$stock} عدد می‌باشد.";
            if ($request->ajax()) {
                return response()->json(['success' => false, 'message' => $msg], 422);
            }
            return redirect()->back()->withErrors(['qty' => $msg]);
        }

        if (isset($cart[$key])) {
            $cart[$key]['qty'] = $stock > 0 ? min($stock, $inCart + $qty) : $inCart + $qty;
        } else {
            $cart[$key] = ['variant_id' => $variantId, 'qty' => $qty];
        }

        $this->saveCart($cart);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'count'   => array_sum(array_column($cart, 'qty')),
            ]);
        }

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

    public function update(Request $request, string $key)
    {
        $request->validate(['qty' => 'required|integer|min:1|max:99']);
        $cart = $this->getCart();

        if (isset($cart[$key])) {
            $newQty    = (int) $request->qty;
            $variantId = (int) ($cart[$key]['variant_id'] ?? 0);
            $variant   = $variantId ? \App\Models\ProductVariant::find($variantId) : null;
            $stock     = (int) ($variant->stock ?? 0);

            if ($stock > 0 && $newQty > $stock) {
                return response()->json([
                    'success' => false,
                    'message' => "تعداد انتخابی شما بیشتر از موجودی انبار می‌باشد. موجودی انبار {$stock} عدد می باشد.",
                ], 422);
            }

            $cart[$key]['qty'] = $newQty;
            $this->saveCart($cart);
        }

        return response()->json(['success' => true]);
    }

    public function remove(string $key)
    {
        $cart = $this->getCart();
        unset($cart[$key]);
        $this->saveCart($cart);

        if (request()->ajax()) {
            return response()->json(['success' => true]);
        }

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