<?php

namespace common\models;

use Yii;
use common\components\Helper;

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

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

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id_shopping_cart' => Yii::t('common/shopping-cart', 'Id Shopping Cart'),
            'id_customer' => Yii::t('common/shopping-cart', 'Id Customer'),
            'id_transfer' => Yii::t('common/shopping-cart', 'Id Transfer'),
        ];
    }
    
    public function getTransfer(){
    	return $this->hasOne(Transfer::className(), ['id_transfer' => 'id_transfer']);
    }
    public function getProduct(){
    	return $this->hasOne(Product::className(), ['id_product' => 'id_product'])->via('transfer');
    }
    
    /**
     * @param $customer common\models\Customer
     * */
    public static function readCustomerCart($customer = null){
    	$transfers = [];
    	if ( isset($customer)){
	    	$query  = ShoppingCart::find()->andWhere( ['id_customer' => $customer->id_customer] );
	    	$query->with('product');
	    	$transfers = $query->all();	
    	}
    	return $transfers;
    }
    
    public static function payout( $customer, $idTransfers, $account = null) {
    	//apply transfer object
    	//delete cart
    	$sql = "UPDATE transfer AS t
				INNER JOIN shopping_cart AS s ON t.id_transfer = s.id_transfer
				SET t.paid_by = ".\Yii::$app->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
    			. " and s.id_customer = " . $customer->id_customer 
    			. " and t.id_transfer in ( '" . implode("','",   $idTransfers )."' )";
    	
    	$q1 = Yii::$app->db->createCommand($sql);
    	$q1->execute();
    	

    	
//     	ShoppingCart::deleteAll(['id_customer' => $customer->id_customer]);
    	
    	if ( isset($idTransfers) ){
    		ShoppingCart::deleteAll(['and' ,['id_customer' => $customer->id_customer] ,['in','id_transfer',$idTransfers] ]);
    	}else{
    		ShoppingCart::deleteAll(['id_customer' => $customer->id_customer]);
    	}
    	
    }
    
}
