<?php


namespace frontend\models;


use common\models\Card;
use common\models\Ticket;
use Exception;
use Yii;
use yii\base\Model;
use yii\data\ArrayDataProvider;
use yii\db\Query;
use yii\web\HttpException;
use yii\web\ServerErrorHttpException;

/**
 * Class SingleCustomerActivateForm
 * @package backend\models
 *
 * @property  Card $card
 *
 */
class SingleCustomerActivateForm  extends Model{

    public $message ;
    public $number ;
    public $card;
    public $tickets;
    public $daysPassed;


    public function rules()
    {
        return [
            [['number'], 'required'],
        ];
    }


    public function loadTicketsToActivate(){
        $this->card = Card::readCard($this->number);

        $query = new Query();

        $this->daysPassed =  $query
            ->select(
                [
                    'datediff(current_date, card.inactivated_at ) '
                ]
            )
            ->from(Card::tableName())
            ->andWhere(['id_card' => $this->card->id_card])
            ->scalar();

        $query = new Query();
        $this->tickets = $query
            ->select(
                [
                    'ticket.id_ticket as id_ticket',
                    'ticket.start as start',
                    'ticket.end as end',
                    'ticket.created_at as created_at',
                    'ticket.usage_count as usage_count',
                    'ticket.max_usage_count as max_usage_count',
                    'date_add( ticket.end, INTERVAL  datediff(current_date, card.inactivated_at) DAY ) as end2'
                ]
            )
            ->from(Ticket::tableName())
            ->innerJoin(Card::tableName(), 'card.id_card = ticket.id_card')
            ->andWhere(['ticket.id_card' => $this->card->id_card])
            ->andWhere(
                    ['and',
                        ['<=','ticket.start',$this->card->inactivated_at ],
                        ['>=','ticket.end',$this->card->inactivated_at ]
                    ]
            )
            ->orderBy(
                [
                    'ticket.start' => SORT_DESC
                ]
            )
            ->all();

    }

    public function loadTicketsDataProvider()
    {
        $this->loadTicketsToActivate();
        return new ArrayDataProvider(
            [
                'allModels' => $this->tickets,
                'sort' => false,
                'pagination' => false
            ]
        );
    }

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


        if ( !isset($this->card) || !isset($this->card->id_card) || empty($this->card->id_card)){
            throw new ServerErrorHttpException("Hiba történt: nics kártya megadva");
        }

        $tx = Yii::$app->db->beginTransaction();
        assert(isset($tx));
        try {

        $command =  Yii::$app->db->createCommand(Ticket::$SQL_UPDATE_TICKETS_END_DATE_ON_CARD_ACTIVATION_SINGLE_CARD,[':id_card' => $this->card->id_card]);

    	$command->execute();

            Card::updateAll(
                [
                    'status' => Card::STATUS_ACTIVE,
                ],
                [
                    'status' => Card::STATUS_INACTIVE,
                    'id_card' => $this->card->id_card
                ]
            );
            Card::updateFlagStatus();

            Card::updateCardFlagTicket( $this->card->id_card);

            $tx->commit();
        } catch (Exception $exception) {
            $tx->rollBack();
            throw $exception;
        }
        Yii::$app->session->setFlash('success', 'Kártya aktiválva');
        return true;
    }

}
