<?php


namespace backend\models;


use common\models\Card;
use common\models\Ticket;
use Yii;
use yii\base\Model;

class CustomerActivateForm  extends Model{

    public $inactiveCardCount;
    public $message ;


    public function rules()
    {
        return [
        ];
    }


    public function loadActiveCardCount(){
        $this->inactiveCardCount = Card::find()->andWhere(
            ['status' => Card::STATUS_INACTIVE]
        )->count();
    }

    /**
     * @return bool
     * @throws \Exception
     */
    public function activate(){
        if (!$this->validate()) {
            return false;
        }

        $tx = \Yii::$app->db->beginTransaction();
        assert(isset($tx));
        try {
            // update ticket end dates
            Yii::$app->db->createCommand(Ticket::$SQL_UPDATE_TICKETS_END_DATE_ON_CARD_ACTIVATION)->execute();
            // update card.status
            Card::updateAll([ 'status' => Card::STATUS_ACTIVE, ], [ 'status' => Card::STATUS_INACTIVE ] );
            // update card.flag
            Card::updateFlagStatus();
            // update ticket
            \Yii::$app->db->createCommand(Ticket::$SQL_UPDATE)->execute();

            $tx->commit();
        } catch (\Exception $exception) {
            $tx->rollBack();
            throw $exception;
        }
        $this->message = $this->inactiveCardCount . " kártya aktiválva";
        return true;
    }

}
