<?php

namespace frontend\models;

use Yii;
use yii\base\Model;
use common\models\Card;
use common\models\Customer;
use common\models\Product;
use common\models\Transfer;
use yii\base\Object;
use common\models\Account;
use common\models\Discount;
use common\models\Currency;
use common\models\UserSoldItem;
use common\models\Sale;
use common\models\ShoppingCart;

/**
 * ContactForm is the model behind the contact form.
 * 
 *  @property integer $id_product
 *  @property integer $count
 *  @property integer $id_currency
 *  @property integer $id_discount
 *  @property string $comment
 *  @property string $barcode
 *  @property string $product_number
 *  @property integer $sale_price
 *  @property string $product_name
 *  @property common\models\Account[] $accounts
 *  @property common\models\Currency[] $currencies
 *  @property common\models\Discount[] $discounts
 *  @property common\models\Product $product
 *  @property common\models\Account $account
 *  @property common\models\Currency $currency
 *  @property common\models\Discount $discount
 *  @property common\models\Customer $customer
 *  @property common\models\Card $card
 *  @property common\models\Transfer $transfer
 *  @property common\models\Sale $sale
 *  @property common\models\ShoppingCart[] $customerCart
 *  
 *  
 */
class ProductSaleForm extends Model
{
	
	public $cart;
	
	public $id_product;
	public $count;
	public $id_currency;
	public $id_account;
	public $id_discount;
	public $comment;
	public $barcode;
	public $product_number;
	public $sale_price;
	public $product_name;
	
	
	public $accounts;
	public $currencies;
	public $discounts;
	
	public $product;
	public $account;
	public $currency;
	public $discount;
	public $customer;
	public $card;
	
	public $transfer;
	public $sale;
	
	public $customerCart;
	
	public $products;
	
	public $payment_method;
	
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id_product','count','id_account','payment_method'], 'required'],
            [['id_product','id_currency','id_account', 'id_discount','count','payment_method'], 'integer'],
            [['comment'], 'string' ,'max' => 255],
            [['cart'], 'string' ,'max' => 20],
            [['id_product' ], 'validateProduct'],
//             [['count' ], 'validateCount'],
            [['id_currency' ], 'validateCurrency'],
            [['id_account' ], 'validateAccount'],
            [['id_discount' ], 'validateDiscount'],
        ];
    }

	/**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id_product' => Yii::t("frontend/product", "Product"),
            'count' => Yii::t("frontend/product", "Count"),
            'id_currency' => Yii::t("frontend/product", "Currency"),
            'id_account' => Yii::t("frontend/product", "Account"),
            'id_discount' => Yii::t("frontend/product", "Discount"),
            'comment' => Yii::t("frontend/product", "Comment"),
        	'payment_method' => Yii::t('common/transfer', 'Fizetési mód'),
        ];
    }
    
    
    public function validateProduct($attribute,$params){
    	$this->product = Product::findOne($this->id_product);
    	
    	if ( !isset( $this->product ) ){
    		$this->addError($attribute, Yii::t('frontend/product', 'Product not found!'));
    	}
    	
    	
    }
    
    public function validateCount($attribute,$params){
    	if ( $this->product != null ){
    		if ( $this->product->stock  < $this->count ){
    			$this->addError($attribute, Yii::t('frontend/product', 'Stock {stock} lower then {count}!', [ 'count' => $this->count, 'stock' => $this->product->stock ] ));
    		}
    	}
    }
    public function validateCurrency($attribute,$params){
    	if ( isset($this->id_currency ) ){
    		$this->currency = Currency::findOne($this->id_currency);
    		if ( !isset( $this->currency )  ){
    			$this->addError($attribute,Yii::t('frontend/product', 'Currency not found') );
    		}
    	}		 
    }
    
    public function validateAccount($attribute,$params){
    	$this->account = Account::findOne($this->id_account);
    }
    
    public function validateDiscount($attribute,$params){
    	if (  isset( $this->id_discount ) ){
	    	$this->discount = Discount::findOne($this->id_discount);
	    	if ( !isset( $this->discount )  ){
	    		$this->addError($attribute,Yii::t('frontend/product', 'Discount not found') );
	    	}
    	}
    }
    
    
    public function save(){
    	if ( $this->validate() ){
    		$connection = \Yii::$app->db;
    		$transaction = $connection->beginTransaction();
    		try {
	    		$this->saveSale();
		    	$this->saveTransfer();
		    	$this->saveProduct();
		    	$this->appendToUserCart();
		    	$this->appendToCustomerCart();
		    	$transaction->commit();
		    	return true;
	    	} catch(Exception $e) {
	    		$transaction->rollback();
	    		return false;
	    	}
	    	
	    	return true;
    	} 
    	return false;
    }
    
    
    protected function saveSale(){
    	
    	$this->sale =  Sale::createSale($this->account, $this->discount, $this->currency, $this->count,   $this->product );
    	if ( isset($this->comment)){
 			$this->sale->comment = $this->comment;
    	}
 		$this->sale->id_user = Yii::$app->user->id;
 		$this->sale->save();
    }
    
    protected function saveTransfer(){
    	$customer = null;
    	$paid_at;
    	$status  = Transfer::STATUS_PAID;
    	if ( !Transfer::canMarkPaidByReception($this->payment_method)){
    		$status = Transfer::STATUS_NOT_PAID;
    	}else if (   $this->isAppendToUserCart() ){
    		$status  = Transfer::STATUS_NOT_PAID;
    	}else if ( $this->isAppendToCustomerCart() ){
    		$status = Transfer::STATUS_NOT_PAID; 
    		$customer = $this->customer;
    	}else{
    		$paid_at =  date('Y-m-d H:i:s' ) ;
    	}
    	
    	$this->transfer =  Transfer::createProductTransfer($this->sale,$this->account, $this->discount, $this->currency, $this->count,   $this->product,$status,$customer);
    	$this->transfer->payment_method = $this->payment_method;
    	if ( isset($this->comment)){
 			$this->transfer->comment = $this->comment;
    	}
    	
    	if ( isset($paid_at)){
    		$this->transfer->paid_at = $paid_at;
    	}
    	
    	
 		$this->transfer->id_user = Yii::$app->user->id;
 		
 		if ( $status == Transfer::STATUS_PAID){
 			$this->transfer->paid_by = Yii::$app->user->id;
 		}
 		
 		
 		$this->transfer->save();
    }

    protected function saveProduct(){
    	Product::sellProduct($this->product, $this->count);
    	$this->product->save();
    }
    
    public function isAppendToUserCart(){
    	$result = false;
    	if ( isset( $this->cart )  && $this->cart  == 'user' ){
    		$result = true;
    	}
    	return $result;
    }
    
    public function appendToUserCart(){
    	if ( $this->isAppendToUserCart() ){
    		if ( Transfer::canBeAddedToCart($this->payment_method)){
	    		$item = new UserSoldItem();
	    		$item->id_transfer = $this->transfer->id_transfer;
	    		$item->id_user = Yii::$app->user->id;
	    		$item->save(false);
    		}
    	}
    }
    public function isAppendToCustomerCart(){
    	$result = false;
    	if ( isset( $this->cart )  && $this->cart  == 'customer' ){
    		$result = true;
    	}
    	return $result;
    }
    
    public function appendToCustomerCart(){
    	if ( $this->isAppendToCustomerCart() && isset($this->customer)  ){
    		if ( Transfer::canBeAddedToCart($this->payment_method)){
	    		$item = new ShoppingCart();
	    		$item->id_customer = $this->customer->id_customer;
	    		$item->id_transfer = $this->transfer->id_transfer;
	    		$item->save(false);
    		}
    	}
    }
}
