<?php
namespace frontend\models;

use common\models\Ticket;
use common\models\TicketType;
use common\models\Account;
use common\models\Discount;
use common\models\Transfer;
use common\models\UserSoldItem;
use common\models\ShoppingCart;
use yii\base\Object;
use common\models\TicketInstallmentRequest;
use common\models\Contract;
use common\components\Helper;
use common\models\Card;

/**
 *  @property $cart string  name of cart, into we put the ticket
 *  @property $userCart common\models\Transfer[]  items in user cart
 *  @property $customerCart common\models\Transfer[]  items in customer cart
 *  @property $customer common\models\Customer  selected customer
 *  
 *  */
class TicketCreate  extends Ticket{

	public $_currency;
	public $_account;
	public $_discount;
	public $_transfer;
	public $_ticketType;
	
	
	public $customer;
	public $userCart;
	public $customerCart;
	
	
	public $cart;
	
	public $payment_method;
	
	public function rules()
	{
		return [
				/////////////////////
				//ticket type
				/////////////////////
				[[  'id_ticket_type'], 'required'],
				[[  'id_ticket_type'], 'integer'],
				[[  'id_ticket_type'], 'validateTicketType'],
				/////////////////////
				//id_account
				/////////////////////
				[[  'id_account'], 'required'],
				[[  'id_account'], 'integer'],
				[[  'id_account'], 'validateAccount'],
				/////////////////////
				//payment_method
				/////////////////////
				[[  'payment_method'], 'required'],
				[[  'payment_method'], 'integer'],
				/////////////////////
				//id_discount
				/////////////////////
				[[  'id_discount'], 'integer'],
				[[  'id_discount'], 'validateDiscount'],
				/////////////////////
				// start and end date
				/////////////////////
				[['start', 'end' ], 'required'],
				[['start', 'end' ], 'date'],
				/////////////////////
				//id_account
				/////////////////////
				[[  'max_usage_count'], 'required'],
				[[  'max_usage_count'], 'integer'],
				/////////////////////
				//price 
				/////////////////////
				[[  'price_brutto'], 'required'],
				[[  'price_brutto'], 'integer'],
				/////////////////////
				//comment
				/////////////////////
				[['comment'], 'string', 'max' => 255],
				/////////////////////
				//cart
				/////////////////////
				[['cart'], 'string', 'max' => 10]
				
		];
	}
	
	
	public function validateTicketType($attribute,$params){
		$type = TicketType::findOne($this->id_ticket_type);
		$this->_ticketType = $type;
		if ( !isset($type)) {
			$this->addError($attribute,Yii::t('frontend/ticket' , 'Invalid ticket type' ));
		}else{
			if ( $type->isInstallment()){
				$bankAccount = trim($this->customer->bank_account);
				if ( !isset($bankAccount) || empty($bankAccount)){
					$this->addError($attribute,"Nincs bankszámlaszám vagy érvénytelen");
					return;
				}
				if (  !( strlen($bankAccount) == 16 ||  strlen($bankAccount) == 24 ) ){
					$this->addError($attribute,"Vendég bankszámlaszáma nem 16 vagy 24 hosszú");
					return;
				}
				//find
				$query = Contract::find();
				$query->andWhere( [ 'id_customer' => $this->customer->id_customer  ]);
				$query->andWhere( [ '>', 'expired_at' , Helper::getDateTimeString()   ]);
				$query->andWhere( [ 'not in', 'flag', [Contract::$FLAG_DELETED ]   ]);
				$contracts = $query->all();
				
				if ( count($contracts) > 0 ){
					$this->addError($attribute,"A vendégnek már van érvényes vagy felbontott szerződése!");
				}
				
			}
		}
	}
	
	public function validateAccount($attribute,$params){
		$this->_account = Account::findOne($this->id_account);
		if ( !isset($this->_account )) {
			$this->addError($attribute,Yii::t('frontend/ticket' , 'Invalid transfer' ));
		}
	}
	
	public function validateDiscount($attribute,$params){
		$this->_discount = Discount::findOne($this->id_discount);
		if ( !isset($this->_discount)) {
			$this->addError($attribute,Yii::t('frontend/ticket' , 'Invalid discount' ));
		}
	}
	
	public function beforeSave($insert){
		$result = parent::beforeSave($insert);
		if ( $result ){
			if ($insert){
				
				if ( $this->isAppendToCustomerCart() || $this->isAppendToUserCart()){
					$this->status = Ticket::STATUS_INACTIVE;
				}else{
					$this->status = Ticket::STATUS_ACTIVE;
				}
				
				$ticketType = TicketType::findOne($this->id_ticket_type);
				if ( isset($ticketType) && $ticketType->isInstallment() ){
					$this->part = 0;
					$this->part_paid = 0;
					$this->part_count =  $ticketType->installment_count;
				}else{
					$this->part_count = 0;
				}
			}
		}
		return $result;
	}
	
	public function afterSave($insert, $changedAttributes){
		$this->addTransfer();
    	$this->appendToUserCart();
    	$this->appendToCustomerCart();
		$this->addContract($insert);
		$this->updateCardFlag();
	
	}
	
	protected function updateCardFlag(){
		Card::updateCardFlagTicket($this->id_card);
	}
	
	public function addContract($insert){
		if ($insert){
			$ticketType = TicketType::findOne($this->id_ticket_type);
			if ( isset($ticketType) && $ticketType->isInstallment() ){
				
				$contract = new Contract();
				$contract->id_customer = $this->customer->id_customer;
				$contract->id_user = \Yii::$app->user->id;
				$contract->status = Contract::$STATUS_PAID;
				$contract->flag = Contract::$FLAG_ACTIVE;
				$contract->part_count = $ticketType->installment_count;
				$contract->part_paid = 0;
				$contract->part_required = 0;
				$contract->expired_at = date('Y-m-d', strtotime("today +12 month -1 day"));
				$contract->id_ticket_type = $this->id_ticket_type;
				$contract->id_discount = $this->id_discount;
				$contract->save();
				
				$requests = TicketInstallmentRequest::createInstallments($this, $ticketType, $this->customer,$contract);
				foreach ($requests as $request){
					$request->save(false);
				}
			}
		}
	}

	protected function addTransfer(){
		//$transfer = Transfer::createTicketTransfer($this->_account, $this->_discount, null, 1, $this);

		
		$transfer = new Transfer();
		
		$transfer->type = Transfer::TYPE_TICKET;
		$transfer->direction = Transfer::DIRECTION_IN;
		
		$transfer->id_object = $this->id_ticket;
		
		$transfer->item_price = $this->_ticketType->price_brutto;
		$transfer->count = 1;
		
		if (isset ( $this->_discount )) {
			$transfer->id_discount = $this->_discount->id_discount;
		}
		
		
		$transfer->money = $this->price_brutto;
		
		$transfer->id_account = $this->_account->id_account;
		
		$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 {
			$status  = Transfer::STATUS_PAID;
			$transfer->paid_at =  date('Y-m-d H:i:s' ) ;
			$transfer->paid_by = \Yii::$app->user->id;
		}
		$transfer->status = $status;
		$transfer->payment_method = $this->payment_method;
		
		if ( isset($this->comment)){
			$transfer->comment = $this->comment;
		}
		$transfer->id_user = \Yii::$app->user->id;
		$transfer->id_customer = $this->customer->id_customer;
		if ( !$transfer->save(false) ){
			\Yii::error("Nem sikerült mentenei a bérlet tranzakció objektumot!");
			throw new \Exception("Nem sikerült menteni a bérlet tranzakciót");
		}
		$this->_transfer = $transfer;
	}
	
	
	
	protected function addToCart(){
		if ( $this->isAddToCart()){
			$item = new UserSoldItem();
			$item->id_transfer = $this->_transfer->id_transfer;
			$item->id_user = \Yii::$app->user->id;
			$item->save(false);
		}
	}
	
	
	public function isAppendToUserCart(){
    	$result = false;
    	if ( isset( $this->cart )  && $this->cart  == 'user' ){
    		$result = true;
    	}
    	return $result;
    }
    
    public function isAppendToCustomerCart(){
    	$result = false;
    	if ( isset( $this->cart )  && $this->cart  == 'customer' ){
    		$result = true;
    	}
    	return $result;
    }
    
    
    public function appendToUserCart(){
    	if ( $this->isAppendToUserCart() ){
    		$item = new UserSoldItem();
    		$item->id_transfer = $this->_transfer->id_transfer;
    		$item->id_user = \Yii::$app->user->id;
    		if ( !$item->save(false) ){
    			\Yii::error("Nem sikerült menteni a bérletet! Recepció kosár hozzárendelés sikertelen!");
    			throw new \Exception("Nem sikerült menteni a bérletet! Recepció kosár hozzárendelés sikertelen!");
    		}
    	}
    }
    
    public function appendToCustomerCart(){
    	if ( Transfer::canBeAddedToCart($this->payment_method)){
	    	if ( $this->isAppendToCustomerCart() && isset($this->customer)  ){
	    		$item = new ShoppingCart();
	    		$item->id_customer = $this->customer->id_customer;
	    		$item->id_transfer = $this->_transfer->id_transfer;
	    		if ( !$item->save(false) ){
	    			\Yii::error("Nem sikerült menteni a bérletet! Vendég kosár hozzárendelés sikertelen!");
	    			throw new \Exception("Nem sikerült menteni a bérletet! Vendég kosár hozzárendelés sikertelen!");
	    		}
	    		
	    	}
    	}
    }
    
   
	
}