<?php

namespace frontend\models;

use Yii;
use yii\base\Model;
use common\models\Transfer;
use common\components\Helper;
use common\models\Account;
use common\components\TransferPayout;

/**
 * ContactForm is the model behind the contact form.
 */
class UserCartForm extends Model
{

	public $items = []; 
	public $transfers;
	public $payment_method;
	public $money = 0;
	public $selected = [];
	
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
        		['selected', 'each', 'rule' => ['integer']],
        		[['money' ,'payment_method'],'integer'],
        		[['payment_method'],'validatePaymentMethod'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
        ];
    }

    public function validatePaymentMethod( $attribute, $params ){
    	if ( !empty($this->payment_method)){
//     		echo $this->payment_method;
    		$arr  = Transfer::paymentMethods();
    		if ( !array_key_exists($this->payment_method, $arr) ){
    			 $this->addError($attribute, "Érvénytelen fizetési mód");
    		}
    	}
    }
    
    
    public function payout(){
    	$valid = $this->validate();
    	
    	if ( !$valid ){
    		return false;
    	}
    	
    	if ( isset($this->selected) && count($this->selected) > 0 ){
    		
    		$connection = \Yii::$app->db;
    		$transaction = $connection->beginTransaction();
    		try {
    			$tp = new TransferPayout( [
    					'idUser' => \Yii::$app->user->id,
    					'idTransfers' => $this->selected,
    					'idAccount' => Account::readDefault (),
    					'cartType' => 'user',
    					'overridePaymentMethod' => $this->payment_method
    			] );
    			 
    			$tp->payout ();
    			 
    			$transaction->commit ();
    			\Yii::$app->session->setFlash ( 'success', 'A recepció kosár kiválasztott tranzakciói ki lettek kifizetve!');
    			return true;
    			
    		} catch ( Exception $e ) {
    			$transaction->rollback ();
    			Yii::error ( "faled to save :" . $e->getMessage () );
    		} catch ( \Exception $e ) {
    			$transaction->rollback ();
    			Yii::error ( "faled to save :" . $e->getMessage () );
    		}
    		return false;
    		
// 	    	$items = $this->loadTransfers($this->selected);
// 	    	if ( count($items) == count($this->selected) ){
// 	    		foreach ($items as $item){
// 	    			$this->changePaymentMethod($item);
// 	    			if ( Helper::isUserCartVisibilityAll() ){
// 		    			$item->id_account = Account::readDefault();
// 	    			}
// 	    			$item->payout();
// 	    		}
// 	    		\Yii::$app->session->setFlash('success', 'Kifizetve');
// 	    		return true;
// 	    	}else{
// 	    		\Yii::$app->session->setFlash('danger', 'Időközben változtak a kosrában  található tételek');
// 	    		return false;
// 	    	}
    	}else{
	    	\Yii::$app->session->setFlash('danger', 'Nem választott ki terméket');
    		return false;
    	}
    }
    
    public function changePaymentMethod($item){
    	if ( !empty($this->payment_method)){
    		$item->payment_method = $this->payment_method;
    	}
    }
    
    public function run(){
    	$this->readTransfers();
    }
    
    public function readTransfers( ) {
    	$this->transfers = $this->loadTransfers();
    }

    public function loadTransfers($id_tranfer_array = null){
    	$query = Transfer::find();
    	$query->innerJoin("user_sold_item", "user_sold_item.id_transfer = transfer.id_transfer");
    	if ( Helper::isUserCartVisibilityUser()){
    		$query->andWhere(["user_sold_item.id_user" => \Yii::$app->user->id]);
    	}
    	if (isset($id_tranfer_array)){
    		$query->andWhere(["in", "transfer.id_transfer" , $id_tranfer_array  ]);
    	}
    	return  $query->all();
    }
    
}
