<?php

namespace backend\models;

use common\models\Transfer;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\Ticket;
use common\components\Helper;
use yii\db\ActiveRecord;
use yii\db\Expression;
use yii\db\Query;
use yii\helpers\ArrayHelper;

/**
 * TicketSearch represents the model behind the search form about `common\models\Ticket`.
 */
class TicketSearch extends Ticket
{

    public $timestampStart;
    public $timestampEnd;

    public $users;
    public $accounts;
    public $ticketTypes;

    public $valid_in_interval;
    public $created_in_interval;
    public $expire_in_interval;
    public $paid_in_interval;

    public $statistics;
    public $statisticsTotal;

    public $customer;
    public $output;

    public $id_customer;
    public $customer_name;
    public $card_number;

    public $modified;


    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id_ticket', 'id_user', 'id_ticket_type', 'id_account', 'status', 'id_customer', 'modified'], 'integer'],
//            [[ 'start', ], 'date'  , 'timestampAttribute' => 'timestampStart' ,'timestampAttributeFormat' => 'yyyy-MM-dd'  ],
//        	[[ 'end' , ], 'date'    , 'timestampAttribute' => 'timestampEnd' ,'timestampAttributeFormat' => 'yyyy-MM-dd' ],
            [['start',], 'date', 'format' => Yii::$app->formatter->datetimeFormat, 'timestampAttribute' => 'timestampStart', 'timestampAttributeFormat' => 'yyyy-MM-dd HH:mm', 'timeZone' => 'UTC'],
            [['end',], 'date', 'format' => Yii::$app->formatter->datetimeFormat, 'timestampAttribute' => 'timestampEnd', 'timestampAttributeFormat' => 'yyyy-MM-dd HH:mm', 'timeZone' => 'UTC'],
            [['valid_in_interval', 'created_in_interval', 'expire_in_interval', 'paid_in_interval'], 'boolean'],
            [['output', 'customer_name', 'card_number'], 'safe']

        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    public function attributeLabels()
    {
        return ArrayHelper::merge(parent::attributeLabels(), [
            'start' => Yii::t('backend/ticket', 'Start of interval'),
            'end' => Yii::t('backend/ticket', 'End of interval'),
            'valid_in_interval' => Yii::t('backend/ticket', 'Valid in interval'),
            'created_in_interval' => Yii::t('backend/ticket', 'Created in interval'),
            'expire_in_interval' => Yii::t('backend/ticket', 'Expire in interval'),
            'paid_in_interval' => "Fizetve az időszakban",
            'modified' => "Módosított",
        ]);
    }

    public function afterValidate()
    {

        if (!isset($this->timestampStart)) {
            $this->timestampStart = '1900-01-01';
        }

        if (!isset($this->timestampEnd)) {
            $this->timestampEnd = '3000-01-01';
        }

    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {

        $query = new Query();
        $query->select([
            'ticket.id_ticket as ticket_id_ticket',
            'customer.id_customer as customer_id_customer',
            'customer.name as customer_name',
            'card.number as card_number',
            'ticket.start as ticket_start',
            'ticket.end as ticket_end',
            'ticket.created_at as ticket_created_at',
            'user.username as user_username',
            'ticket_type.name as ticket_type_name',
            'account.name as account_name',
            'ticket.status as ticket_status',
            'ticket.max_usage_count as ticket_max_usage_count',
            'ticket.usage_count as ticket_usage_count',
            'paid_by.username as paid_by_username',
            'transfer.payment_method as transfer_payment_method',
            'transfer.status as transfer_status',
            'transfer.money as transfer_money',
            'ticket.price_brutto as ticket_price_brutto'
        ]);
        $query->from('ticket');
        $query->innerJoin("transfer", "ticket.id_ticket = transfer.id_object and transfer.type =" . Transfer::TYPE_TICKET);
        $query->innerJoin("card", "ticket.id_card = card.id_card");
        $query->innerJoin("customer", "card.id_card = customer.id_customer_card");
        $query->innerJoin("user", "user.id = transfer.id_user");
        $query->leftJoin("user as paid_by", "paid_by.id = transfer.paid_by");
        $query->innerJoin("account", "account.id_account = transfer.id_account");
        $query->innerJoin("ticket_type", "ticket_type.id_ticket_type = ticket.id_ticket_type");

        $query->andWhere(['transfer.type' => Transfer::TYPE_TICKET]);

        Helper::queryAccountConstraint($query, 'ticket.id_account');

        $this->load($params);


        if (!$this->validate()) {
            $query->where('0=1');
            return $query;
        }


        $dataProviderSetup = [
            'query' => $query,
        ];

        $dataProviderSetup['sort'] = [
            'defaultOrder' => ['ticket_created_at' => SORT_DESC],
            'attributes' => Helper::mkYiiSortItems([
                ['ticket_id_ticket'],
                ['customer_name'],
                ['customer_id_customer'],
                ['card_number'],
                ['ticket_start'],
                ['ticket_end'],
                ['ticket_created_at'],
                ['user_username'],
                ['ticket_type_name'],
                ['account_name'],
                ['ticket_status'],
                ['ticket_max_usage_count'],
                ['ticket_usage_count'],
                ['paid_by_username'],
                ['paid_at'],
                ['transfer_payment_method'],
                ['transfer_status'],
                ['transfer_money'],
                ['ticket_price_brutto'],
            ])
        ];

        if ($this->output == 'pdf' || $this->output == 'xls') {
            $dataProviderSetup['pagination'] = false;
        }

        $dataProvider = new ActiveDataProvider($dataProviderSetup);

        $query->andFilterWhere([
            'user.id' => $this->id_user,
            'ticket_type.id_ticket_type' => $this->id_ticket_type,
            'account.id_account' => $this->id_account,
            'card.id_card' => $this->id_card,
            'ticket.id_ticket' => $this->id_ticket,
            'ticket.status' => $this->status,
            'customer.id_customer' => $this->id_customer,
            'card.number' => $this->card_number
        ]);

        if ($this->modified == 1) {
            $query->andWhere(
                [
                    'or',
                    ['and', ['not', ['ticket.original_price' => null]], ['<>', 'ticket.original_price', 'ticket.price_brutto']],
                    ['and', ['not', ['ticket.original_end' => null]], ['<>', 'ticket.original_end', 'ticket.end']],

                ]
            );
//            $query->andWhere('ticket.original_price is not null and ticket.original_price <> ticket.price_brutto');
//            $query->andWhere('ticket.original_end is not null and ticket.original_end <> ticket.end');
        }

        $query->andFilterWhere(['like', new Expression('LOWER(customer.name)'), strtolower($this->customer_name)]);

        $all = (!($this->valid_in_interval) && !($this->expire_in_interval) && !($this->created_in_interval) && !($this->paid_in_interval))
            ||
            ($this->valid_in_interval == true && $this->expire_in_interval == true && $this->created_in_interval && $this->paid_in_interval);

        $dateConditions = [];
        $start = $this->timestampStart;
        $end = $this->timestampEnd;

        if ($all || $this->created_in_interval) {
            $dateConditions[] = Helper::queryInIntervalRule('ticket.created_at', $start, $end);
        }

        if ($all || $this->valid_in_interval) {
            $dateConditions[] = Helper::queryValidRule('ticket.start', 'ticket.end', $start, $end);
        }

        if ($all || $this->expire_in_interval) {
            $dateConditions[] = Helper::queryExpireRule('ticket.start', 'ticket.end', $start, $end);
        }

        if ($all || $this->paid_in_interval) {
            $dateConditions[] = ['and', ['>=', 'transfer.paid_at', $start], ['<', 'transfer.paid_at', $end]];
        }

        if (count($dateConditions) == 1) {
            $query->andWhere($dateConditions[0]);
        } else if (count($dateConditions) > 1) {
            $cond = ['or'];
            foreach ($dateConditions as $c) {
                $cond[] = $c;
            }
            $query->andWhere($cond);
        }

        return $dataProvider;
    }


    public function isAllDateConditionOn()
    {
        $all = (!($this->valid_in_interval) && !($this->expire_in_interval) && !($this->created_in_interval) && !($this->paid_in_interval))
            ||
            ($this->valid_in_interval == true && $this->expire_in_interval == true && $this->created_in_interval && $this->paid_in_interval);

        return $all;
    }


    public function searchTotals()
    {
        $query = Ticket::mkStatisticQuery($this->timestampStart, $this->timestampEnd, $this->id_card);
        $this->statistics = $query->all();

        $this->statisticsTotal = [
            'valid' => 0,
            'created' => 0,
            'created_at_money' => 0,
            'expired' => 0,
        ];

        $this->statisticsTotal['valid'] = array_sum(array_column($this->statistics, 'valid'));
        $this->statisticsTotal['created'] = array_sum(array_column($this->statistics, 'created'));
        $this->statisticsTotal['created_money'] = array_sum(array_column($this->statistics, 'created_money'));
        $this->statisticsTotal['expired'] = array_sum(array_column($this->statistics, 'expired'));
    }


    public static function mkSearchCondition($timestampStart, $timestampEnd, $id_user, $id_ticket_tpye, $id_account, $valid_in_interval, $expire_in_interval, $created_in_interval)
    {
        $query = Ticket::find();

        Helper::queryAccountConstraint($query, 'ticket.id_account');

        $query->with('ticketType');
        $query->with('user');
        $query->with('customer');

        $query->andFilterWhere([
            'id_user' => $id_user,
            'id_ticket_type' => $id_ticket_type,
            'id_account' => $id_account,
        ]);

        $all = (!($valid_in_interval) && !($expire_in_interval) && !($created_in_interval))
            ||
            ($valid_in_interval == true && $expire_in_interval == true && $created_in_interval);

        $dateConditions = [];
        $start = $timestampStart;
        $end = $timestampEnd;

        if ($all || $created_in_interval) {
            $dateConditions[] = Helper::queryInIntervalRule('ticket.created_at', $start, $end);
        }

        if ($all || $valid_in_interval) {
            $dateConditions[] = Helper::queryValidRule('ticket.start', 'ticket.end', $start, $end);
        }

        if ($all || $expire_in_interval) {
            $dateConditions[] = Helper::queryExpireRule('ticket.start', 'ticket.end', $start, $end);
        }

        if (count($dateConditions) == 1) {
            $query->andWhere($dateConditions[0]);
        } else if (count($dateConditions) > 1) {
            $cond = ['or'];
            foreach ($dateConditions as $c) {
                $cond[] = $c;
            }
            $query->andWhere($cond);
        }
    }

}
