<?php

namespace common\models;

use Yii;
use yii\db\Query;
use yii\db\Expression;
use common\components\Helper;

/**
 * This is the model class for table "user_sold_item".
 *
 * @property integer $id_user_sold_item
 * @property integer $id_user
 * @property integer $id_transfer
 */
class UserSoldItem extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'user_sold_item';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id_user', 'id_transfer'], 'integer']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id_user_sold_item' => Yii::t('common/user-sold-item', 'Id User Sold Item'),
            'id_user' => Yii::t('common/user-sold-item', 'Id User'),
            'id_transfer' => Yii::t('common/user-sold-item', 'Id Transfer'),
        ];
    }
    
    public function getAccount(){
    	$this->hasOne(Transfer::className(), ["id_transfer" => "id_transfer"]);
    }
    
    public function getUser(){
    	$this->hasOne(User::className(), ["id" => "id_user"]);
    }
    
    
    public static function read($user){
    	
    	$query = UserSoldItem::find();
    	$query->andWhere(['id_user' => $user->id_user]);
    	$result = $query->all();
    	
    }
    
    public static function readTotalForAccount($idUser,$idAccount){
    	 
    	$query = new Query();
    	
    	$query->addSelect( [
    			new Expression( ' COALESCE(sum( transfer.money ) ,0) as money /** total unpaid reception cart */' )
    	
    	]);
    	$query->innerJoin('transfer','user_sold_item.id_transfer = transfer.id_transfer');
    	
    	$query->from('user_sold_item');
    	
    	$query->andFilterWhere([
    			'transfer.id_account' => $idAccount,
    			]);

    	$query->andFilterWhere(['user_sold_item.id_user' => $idUser]);
    	
    	
    	return $query->scalar();
    	 
    }
    
    
    /**
     * @param common\models\User $user
     * */
    public static function payout( $user, $idTransfers = null, $account = null ) {
    	//apply transfer object
    	//delete cart
    	$sql = "UPDATE transfer AS t
				INNER JOIN user_sold_item AS s ON t.id_transfer = s.id_transfer
				SET t.paid_by = ".$user->id.", t.status = "  . Transfer::STATUS_PAID . ", t.paid_at = '" . date('Y-m-d H:i:s' ) ."' ";
    	
    	if ( isset($account)){
    		$sql .= " , id_account = " . $account;
    	}else  	if ( Helper::isUserCartVisibilityAll() ){
    		$sql .= " , id_account = " . Account::readDefault();
    	}
    	
    	
    	
		$sql .= " WHERE  t.status = " . Transfer::STATUS_NOT_PAID;
		
		//we can see all transfer in cart, or just our
		if ( Helper::isUserCartVisibilityUser()){
    		$sql .= " and s.id_user =" . $user->id ;
		}
    	
		//just payout selected transfers
    	if ( isset($idTransfers)){
    		$sql .= " and t.id_transfer in ( '" . implode("','",   $idTransfers )."' )";
   		}
    	 
    	$q1 = Yii::$app->db->createCommand($sql);
    	$q1->execute();
    	 

    	$deleteConditions = [];
    	
    	if ( isset($idTransfers) ){
    		$deleteConditions[] = ['in','id_transfer',$idTransfers];
    	} 
    	
    	if ( Helper::isUserCartVisibilityUser()){
    		$deleteConditions[] = ['id_user' => Yii::$app->user->id];
    	}
    	
    	if ( count($deleteConditions) > 1 ){
    		// ['and', 'cond1','cond2']
    		$deleteConditions = ["and"] + $deleteConditions; 
    	}else if ( count($deleteConditions) == 1 ){
    		//[a => b ]
    		$deleteConditions =   $deleteConditions[0];
    	}else{
    		//[]
    		$deleteConditions = [];
    	}
    	UserSoldItem::deleteAll($deleteConditions);
    	
    	 
    }
    
    
}
