<?php

namespace app\controllers;

use Yii;
use yii\web\Controller;
use yii\web\Response;
use yii\web\NotFoundHttpException;

use app\models\Product;
use app\models\AddToCartForm;
use app\models\CartUpdateForm;
use app\models\CheckoutForm;

use app\components\SessionManager;
use app\models\SessionUser;
use app\models\SessionCart;

class CartController extends Controller
{
    /** @var SessionUser */
    private $_sessionUser;

    /** @var SessionCart */
    private $_sessionCart;

    public function init()
    {
        parent::init();

        $sessionManager = new SessionManager();
        $this->_sessionUser = new SessionUser($sessionManager);
        $this->_sessionCart = new SessionCart($this->_sessionUser);
    }

    /**
     * View Cart and update quantities
     */
    public function actionIndex()
    {
        $form = new CartUpdateForm();

        // Load current cart items (productId => quantity) from session cart
        $cartItems = $this->_sessionCart->getCartSession() ?? [];

        // Prepare form data
        $form->items = [];
        foreach ($cartItems as $productId => $itemData) {
            $form->items[] = [
                'productId' => (int)$productId,
                'quantity' => (int)$itemData['quantity'],
            ];
        }

        if ($form->load(Yii::$app->request->post()) && $form->validate()) {
            // Update cart based on submitted quantities
            foreach ($form->items as $item) {
                $productId = (int)$item['productId'];
                $quantity = (int)$item['quantity'];

                if ($quantity > 0) {
                    $this->_sessionCart->addToCartProduct($productId, $quantity);
                } else {
                    $this->_sessionCart->removeFromCart($productId);
                }
            }

            // Persist to DB if logged in
            if (!Yii::$app->user->isGuest) {
                $this->_sessionCart->setSessionToDatabase(Yii::$app->user->id);
            }

            Yii::$app->session->setFlash('success', 'Cart updated successfully.');
            return $this->refresh();
        }

        // Fetch all products in the cart for display
        $productIds = array_column($form->items, 'productId');
        $products = Product::find()->where(['id' => $productIds])->indexBy('id')->all();

        return $this->render('index', [
            'form' => $form,
            'products' => $products,
        ]);
    }

    /**
     * Add product to cart
     */
    public function actionAdd()
    {
        $form = new AddToCartForm();

        if ($form->load(Yii::$app->request->post()) && $form->validate()) {
            $productId = $form->productId;
            $quantity = $form->quantity;

            // Check product exists before adding
            $product = Product::findOne($productId);
            if (!$product) {
                throw new NotFoundHttpException('Product not found');
            }

            $added = $this->_sessionCart->addToCartProduct($productId, $quantity);

            if ($added) {
                if (!Yii::$app->user->isGuest) {
                    $this->_sessionCart->setSessionToDatabase(Yii::$app->user->id);
                }
                Yii::$app->session->setFlash('success', 'Product added to cart.');
                return $this->redirect(['cart/index']);
            } else {
                Yii::$app->session->setFlash('error', 'Could not add product to cart.');
            }
        }

        // List products for select dropdown
        $products = Product::find()->select(['name', 'id'])->indexBy('id')->column();

        return $this->render('add', [
            'model' => $form,
            'products' => $products,
        ]);
    }

    /**
     * Checkout action
     */
    public function actionCheckout()
    {
        $form = new CheckoutForm();

        // Load cart items
        $cartItems = $this->_sessionCart->getCartSession();

        if (empty($cartItems)) {
            Yii::$app->session->setFlash('error', 'Your cart is empty.');
            return $this->redirect(['cart/index']);
        }

        if ($form->load(Yii::$app->request->post()) && $form->validate()) {
            // Process the order (replace with your real order processing logic)
            $orderSuccess = $this->processOrder($form, $cartItems);

            if ($orderSuccess) {
                $this->_sessionCart->clearCart();

                if (!Yii::$app->user->isGuest) {
                    $this->_sessionCart->setSessionToDatabase(Yii::$app->user->id);
                }

                Yii::$app->session->setFlash('success', 'Your order has been placed successfully!');
                return $this->redirect(['site/index']);
            } else {
                Yii::$app->session->setFlash('error', 'Failed to process your order.');
            }
        }

        return $this->render('checkout', [
            'model' => $form,
        ]);
    }

    /**
     * Sample order processing method - replace with your business logic
     *
     * @param CheckoutForm $form
     * @param array $cartItems
     * @return bool
     */
    protected function processOrder(CheckoutForm $form, array $cartItems): bool
    {
        // Validate stock, create order records, process payment, send confirmation
        // For now, assume success
        return true;
    }
}

issue im facing with your cart controller suggestion is the session cart does not handle the cart model, it only 
handles the session cart. easier way to explain this is session cart is for guest only and cart activerecorder model is
for users.