<?php

namespace portalpeople\invoicing\behaviors;

use portalpeople\invoicing\models\Invoicesbe;
use Yii;
use yii\base\Behavior;
use yii\web\Controller;
use yii\web\ForbiddenHttpException;

/**
 * Cart Update Restriction Behavior
 *
 * Prevents cart updates if the cart has been invoiced.
 * Attaches to CartController to enforce immutability of invoiced orders.
 */
class CartUpdateBehavior extends Behavior
{
    /**
     * {@inheritdoc}
     */
    public function events()
    {
        return [
            Controller::EVENT_BEFORE_ACTION => 'beforeAction',
        ];
    }

    /**
     * Before action event handler
     *
     * @param \yii\base\ActionEvent $event
     * @throws ForbiddenHttpException
     */
    public function beforeAction($event)
    {
        $controller = $event->sender;
        $action = $event->action->id;

        // Only restrict update actions
        if (!in_array($action, ['update', 'save', 'delete'])) {
            return true;
        }

        // Get cart ID from request
        $cartId = Yii::$app->request->get('id') ?? Yii::$app->request->post('id');
        if (!$cartId) {
            return true;
        }

        // Check if cart has invoice
        $cart = \backend\models\Cartsbe::findOne($cartId);
        if (!$cart) {
            return true;
        }

        if (!empty($cart->invoiceid)) {
            throw new ForbiddenHttpException(
                'This order has been invoiced and cannot be modified. ' .
                'Please create a credit note if corrections are needed.'
            );
        }

        return true;
    }
}
