<?php

namespace backend\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\ProductCategory;
use yii\db\Query;
use common\models\Transfer;
use common\models\Product;
use common\models\Account;
use common\components\Helper;
use common\components\RoleDefinition;

/**
 * ProductCategorySearch represents the model behind the search form about `common\models\ProductCategory`.
 */
class ProductStatisticsSearch extends Product
{
	
	public $start;
	public $end;
	
	public $timestampStart;
	public $timestampEnd;
	
	
	/**
	 * if output is 'xls', dataprovider pagination will be false
	 * */
	public $output  = ''; 
	
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id_product_category', 'status','id_account'], 'integer'],
            [['name','barcode','product_number','output'  ], 'safe'],
        		[[ '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' ],
        		 
        ];
    }

    /**
     * @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([
	        'product.id_product as product_id_product',
	        'product.name as product_name',
	        'product.sale_price as product_sale_price',
	        'product.product_number as product_number',
	        'product.barcode as product_barcode',
	        "father_account.name  as father_account_name",
// 	        "coalesce(account.name,'-') as account_name",
        	'coalesce(sum(transfer.count),0) as transfer_count',
        	'coalesce(sum(transfer.money),0) as transfer_money',
        		
        ]);
        $query->from("product");
        $query->innerJoin('account as father_account','father_account.id_account = product.id_account');
        $query->innerJoin('product_category','product_category.id_product_category = product.id_product_category');
        $query->leftJoin("sale" ,'sale.id_product = product.id_product  '  );
        $query->leftJoin("transfer" ,'transfer.id_object = sale.id_sale and transfer.type =' .Transfer::TYPE_PRODUCT  );
        $query->leftJoin('account','account.id_account = transfer.id_account');
        
        
        if ( !RoleDefinition::isAdmin() ){
        	$query->innerJoin ( "user_account_assignment", 'father_account.id_account = user_account_assignment.id_account' );
        	$query->andWhere ( [
        			'user_account_assignment.id_user' => Yii::$app->user->id
        	] );
        	
        	$query->andWhere(['account.type' => Account::TYPE_ALL]);
        }
        
        $query->andWhere(['in' , 'transfer.status',[Transfer::STATUS_PAID,Transfer::STATUS_NOT_PAID]]);
        
        $query->groupBy([
        'product.id_product',
        'product.name',
        'product.sale_price',
        'father_account.name',
        'product.barcode',
        'product.product_number',
        ]);

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        	'sort' =>[
        		'defaultOrder' =>[
        				'product_name' => SORT_ASC
        		],
        		'attributes' =>[
        				'product_name' => [
        					'asc' => ['product.name' => SORT_ASC ],
        					'desc' => ['product.name' => SORT_DESC],
        				],
        				'product_number' => [
        					'asc' => ['product.product_number' => SORT_ASC ],
        					'desc' => ['product.product_number' => SORT_DESC],
        				],
        				'product_barcode' => [
        					'asc' => ['product.barcode' => SORT_ASC ],
        					'desc' => ['product.barcode' => SORT_DESC],
        				],
        				'father_account_name' => [
        					'asc' => ['father_account.name' => SORT_ASC ],
        					'desc' => ['father_account.name' => SORT_DESC],
        				],
        				'product_sale_price' => [
        					'asc' => ['product.sale_price' => SORT_ASC ],
        					'desc' => ['product.sale_price' => SORT_DESC],
        				],
        				'transfer_count' => [
        					'asc' => ['coalesce(sum(transfer.count),0)' => SORT_ASC ],
        					'desc' => ['coalesce(sum(transfer.count),0)' => SORT_DESC],
        				],
        				'transfer_money' => [
        					'asc' => ['coalesce(sum(transfer.money),0)' => SORT_ASC ],
        					'desc' => ['coalesce(sum(transfer.money),0)' => SORT_DESC],
        				],
//         				'account_name' => [
//         					'asc' => ['account.name' => SORT_ASC ],
//         					'desc' => ['account.name' => SORT_DESC],
//         				],
        		]	
        	],
        ]);
        
        

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        if ( $this->output == 'xls'){
        	$dataProvider->pagination = false;
        }
        
        $query->andFilterWhere([
            'product_category.id_product_category' => $this->id_product_category,
            'product.barcode' => Helper::fixAsciiChars($this->barcode),
            'product.product_number' => Helper::fixAsciiChars($this->product_number),
            'product.name' =>  ($this->name),
            'product.id_account' =>  ($this->id_account),
//             'id_product_category' => $this->id_product_category,
        ]);
        
        $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]);

//         $query->andFilterWhere(['like', 'product.name', $this->name]);

        return $dataProvider;
    }
}
