<?php

namespace backend\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\Transfer;
use yii\db\Expression;
use yii\base\Object;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use common\models\Account;
use common\components\Helper;
use common\components\RoleDefinition;

/**
 * TransferSearch represents the model behind the search form about `common\models\Transfer`.
 */
class TransferLaterSearch extends Transfer
{
	public $start;
	public $end;
	
	public $timestampStart;
	public $timestampEnd;
	
	public $id_ticket_type;
	

	public $ticket_type;
	public $selected = [];
	
	public $total_money;
	
	public $output;
	
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
        	[['output' ] ,'safe'],
            [[  'id_ticket_type','id_user'], 'integer'],
       		[[ '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' ],
       		['selected', 'each', 'rule' => ['integer']],
        ];
    }

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

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = new Query();
        
        $query->select([
        	'transfer.id_transfer as transfer_id_transfer',
        	'transfer.created_at as transfer_created_at',
        	'transfer.money as transfer_money',
        	'transfer.status as transfer_status',
        	'user.username as user_username',
        	'customer.id_customer as customer_id_customer',
        	'customer.name as customer_name',
        	'customer.description as customer_description',
        	'ticket_type.name as ticket_type_name',
        	'product.name as product_name',
        	'ticket.start as ticket_start',
        	'ticket.end as ticket_end',
        	'ticket.comment as ticket_comment',
        ]);
        $query->from("transfer");
       	$query->innerJoin('user', " user.id = transfer.id_user");
       	$query->leftJoin('customer', " transfer.id_customer = customer.id_customer");
       	$query->leftJoin('ticket', " transfer.type = ".Transfer::TYPE_TICKET." and transfer.id_object = ticket.id_ticket");
       	$query->leftJoin('ticket_type', " ticket.id_ticket_type = ticket_type.id_ticket_type");
       	$query->leftJoin('sale', " transfer.type = ".Transfer::TYPE_PRODUCT." and transfer.id_object = sale.id_sale");
       	$query->leftJoin('product', "   product.id_product = sale.id_product");
        
        $query->andWhere(["transfer.payment_method" => Transfer::PAYMENT_METHOD_TRANSFER_LATER  ]);
        
		$query->andWhere(['transfer.status' => Transfer::STATUS_NOT_PAID]);

      	$this->load($params);

      	$valid = $this->validate();
      
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        	'pagination' => $this->output == 'pdf' ? false : [],
        	'sort' =>  [
        		'defaultOrder' =>[
        				'transfer_created_at' => SORT_DESC
        		],
        		'attributes' => Helper::mkYiiSortItems([
        				['transfer_created_at'],
        				['transfer_money'],
        				['transfer_status'],
        				['user_username'],
        				['customer_name'],
        				['ticket_type_name'],
        				['product_name'],
        				['ticket_start'],
        				['ticket_end'],
        				['ticket_comment'],
        				['customer_description'],
        		]) 
        			
        		]
        ]);

        
     	if (!$valid) {
            // uncomment the following line if you do not want to return any records when validation fails
            $query->where('0=1');
            return $dataProvider;
        }
        
        
        $query->andFilterWhere([
        		'ticket_type.id_ticket_type' => $this->id_ticket_type,
		         'transfer.id_user' => $this->id_user,
        ]);
        
		$created_condition = ['and',[ '>=', 'transfer.created_at', $this->timestampStart ] ,[ '<', 'transfer.created_at', $this->timestampEnd ]  ];
        $paid_condition = ['and',[ '>=', 'transfer.paid_at', $this->timestampStart ] ,[ '<', 'transfer.paid_at', $this->timestampEnd ]  ];
        
        $query->andFilterWhere(['or' , $created_condition , $paid_condition]);
        
		$qtotal = Query::create($query);
		$qtotal->select([ new Expression("coalesce(sum(transfer.money),0) as transfer_money" )]);
		$this->total_money = $qtotal->scalar();
        
        
        return $dataProvider;
    }
    
    
    public function totalsTransfers( ){
    	
    	
    	 
    
    }
    
    
    public function doPayout(){
    	
    	if ( !isset($this->selected) || count($this->selected) == 0){
    		Helper::flash("error", "Nincs kiválasztott tranzakció");
    		return false;
    	}
    	
    	$transfers = Transfer::find()
    	->andWhere(['status' => Transfer::STATUS_NOT_PAID ])
    	->andWhere(['payment_method' => Transfer::PAYMENT_METHOD_TRANSFER_LATER])
    	->andWhere(['in','transfer.id_transfer',$this->selected])
    	->all();
    	
    	if ( count($transfers) != count($this->selected)){
    		Helper::flash("warning", "A kiválasztott tranzakciókban időközben változás történt");
    		return false;
    	}
    	
    	$db = \Yii::$app->db;
    	$tx = $db->beginTransaction();
    	try{
	    	foreach ($transfers as $transfer){
	    		if ( !$transfer->payout($transfer->id_account) ){
	    			\Yii::error("Failed to payout transaction: " .$transfer->id_transfer);
	    			throw new \Exception("Nem sikerült mententi a tranzakciókat");
	    		}
	    	}
	    	$tx->commit();
	    	Helper::flash("success", "Tranzakciók fizetettnek jelölve: " .count($transfers) . " db");
    	}catch (\Exception $e){
    		$tx->rollBack();
    		Helper::flash("error", "Hiba történt a művelet közben");
    		return false;
    	}
    	
    	
    	return true;
    }
    
    
    
}
