<?php

namespace common\models;

use Yii;
use yii\helpers\ArrayHelper;
use yii\behaviors\TimestampBehavior;
use common\components\Helper;

/**
 * This is the model class for table "ticket_installment_request".
 *
 * @property integer $id_ticket_installment_request
 * @property integer $id_ticket
 * @property integer $id_customer
 * @property integer $id_transfer
 * @property integer $status
 * @property integer $money
 * @property string $customer_name
 * @property string $bank_name
 * @property string $bank_address
 * @property string $bank_account
 * @property integer $priority
 * @property string $request_sent_at
 * @property string $request_processed_at
 * @property string $request_target_time_at
 * @property string $created_at
 * @property string $updated_at
 * @property string $detsta_answer
 * @property string $comment
 * @property string $updated_at
 * @property common\components\giro\GiroDETSTATetel  $detstaTetel GiroDetstaTetel record a DetSta fájlból
 */
class TicketInstallmentRequest extends \yii\db\ActiveRecord
{
	///status //pending | marked_to_send | sent | canceled | rejected | accepted |
	
	public static $STATUS_PENDING = 0;
	public static $STATUS_MARKED_TO_SEND = 10;
	public static $STATUS_SENT = 20;
	public static $STATUS_CANCELED = 30;
	public static $STATUS_REJECTED = 40;
	public static $STATUS_ACCEPTED = 50;
	public static $STATUS_ACCEPTED_MANUAL = 60;
	
	/**
	 * GiroDetstaTetel record a DetSta fájlból
	 * */
	public $detstaTetel;
	
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'ticket_installment_request';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id_ticket', 'id_customer', 'id_transfer', 'status', 'money', 'priority'], 'integer'],
            [['request_sent_at', 'request_processed_at', 'request_target_time_at', 'created_at', 'updated_at'], 'required'],
            [['request_sent_at', 'request_processed_at', 'request_target_time_at', 'created_at', 'updated_at'], 'safe'],
            [['customer_name', 'bank_name', 'bank_address', 'bank_account'], 'string', 'max' => 255]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id_ticket_installment_request' => Yii::t('common/ticket_installment_request', 'Id Ticket Installment Request'),
            'id_ticket' => Yii::t('common/ticket_installment_request', 'Id Ticket'),
            'id_customer' => Yii::t('common/ticket_installment_request', 'Id Customer'),
            'id_transfer' => Yii::t('common/ticket_installment_request', 'Id Transfer'),
            'status' => Yii::t('common/ticket_installment_request', 'Status'),
            'money' => Yii::t('common/ticket_installment_request', 'Money'),
            'customer_name' => Yii::t('common/ticket_installment_request', 'Customer Name'),
            'bank_name' => Yii::t('common/ticket_installment_request', 'Bank Name'),
            'bank_address' => Yii::t('common/ticket_installment_request', 'Bank Address'),
            'bank_account' => Yii::t('common/ticket_installment_request', 'Bank Account'),
            'priority' => Yii::t('common/ticket_installment_request', 'Priority'),
            'request_sent_at' => Yii::t('common/ticket_installment_request', 'Request Sent At'),
            'request_processed_at' => Yii::t('common/ticket_installment_request', 'Request Processed At'),
            'request_target_time_at' => Yii::t('common/ticket_installment_request', 'Request Target Time At'),
            'created_at' => Yii::t('common/ticket_installment_request', 'Created At'),
            'updated_at' => Yii::t('common/ticket_installment_request', 'Updated At'),
        ];
    }
    

    public function behaviors()
    {
    	return ArrayHelper::merge(  [
    			[
    					'class' => TimestampBehavior::className(),
    					'value' => function(){  return date('Y-m-d H:i:s'   ); }
    			],
    			], parent::behaviors());
    }
    
    public function getCustomer(){
    	return $this->hasOne( Customer::className(), ["id_customer" =>"id_customer" ] );
    }
    public function getContract(){
    	return $this->hasOne( Contract::className(), ["id_contract" =>"id_contract" ] );
    }
    
    public function getTicket(){
    	return $this->hasOne( Ticket::className(), ["id_ticket" =>"id_ticket",  ] ) ;
    }
    
    public function getUgiro()
    {
    	return $this->hasOne(Ugiro::className(), [ 'id_ugiro' => 'id_ugiro'  ])
    	->viaTable('ugiro_request_assignment', [ 'id_request' => 'id_ticket_installment_request'  ]);
    }
    
    public function getTicketExpirationDate(){
    	$date =  \DateTime::createFromFormat("Y-m-d H:i:s", $this->request_target_time_at, new \DateTimeZone( 'UTC'));
    	$date->modify("+1 month");
    	$date->modify("-1 day");
    	$date->setTime(0, 0, 0);
    	
		return   $date->getTimestamp();
    }
    
    
    public function isStatusAccepted(){
    	return $this->status == static::$STATUS_ACCEPTED || $this->status == static::$STATUS_ACCEPTED_MANUAL;
    }
    
    public function isStatusRejected(){
    	return $this->status == static::$STATUS_REJECTED ;
    }
    
    public function isStatusCanceled(){
    	return $this->status == static::$STATUS_CANCELED ;
    }
    
    public function isStatusPending(){
    	return $this->status == static::$STATUS_PENDING ;
    }
    
    public function isStatusSent(){
    	return $this->status == static::$STATUS_SENT ;
    }
    
    public function getIdGiro(){
    	$result = null;
    	$giro = $this->ugiro;
    	if ( isset($giro) ){
    		$result = $giro->id_ugiro;
    	}
    	return $result;
    }
    
    /**
     * Megbízás státuszának beállítása
     * 
     * Létrehozza a szükséges ticket/transfer objectumokat
     * 
     * @param boolean $partRequired ha igaz, a bérleten a part mezőt változtatjuk
     * */
    public function applyStatus($status, $partRequired = false, $visszajelzes = "", $comment = ""){
    	$contract = $this->contract;
    	$contract->part_required = $contract->part_required +1;
    	if ( $status == static::$STATUS_ACCEPTED || $status == static::$STATUS_ACCEPTED_MANUAL){
			if ( !$this->isStatusAccepted() ){
				$contract->part_paid = $contract->part_paid +1;
// 				$tranfer = $this->addTransfer();
				$result = Transfer::sellContractTicket($contract, $this, Account::findOne(1), Transfer::STATUS_PAID, Transfer::PAYMENT_METHOD_TRANSFER);
				$transfer = $result[0];
				$ticket = $result[1];
				$this->status =  $status;
				$this->id_transfer = $transfer->id_transfer;
				$this->id_ticket = $ticket->id_ticket;
				
				$this->request_processed_at = Helper::getDateTimeString();
				$this->save(false);
				
				$contract->save(false);
				
				\Yii::info("Megbízás kifizetve: " . $this->id_ticket_installment_request);
// 				$this->applyNewTicketState($partRequired);
				return true;
			}else{
				\Yii::info("Megbízás már ki volt fizetve: " . $this->id_ticket_installment_request);
				return false;
			}
    	}else{
    		
    		$this->status =  $status;
    		$this->detsta_answer = $visszajelzes;
    		$this->comment = $comment;
    		$this->request_processed_at = Helper::getDateTimeString();
    		$this->save(false);
    		$contract->status = Contract::$STATUS_NOT_PAID;
    		$contract->save(false);
//     		$this->applyNewTicketState($partRequired);
    		\Yii::info("Megbízás visszautasítva: " . $this->id_ticket_installment_request);
    		return true;
    	}
    }
    
//     protected function applyNewTicketState($partRequired = false){
//     	if ( $partRequired ){
//     		$this->ticket->setPartRequired($this);
//     	}
//     	$this->ticket->applyTicketInstallmentRequest($this);
//     	$this->ticket->save(false);
//     }
    
    
    protected function addTransfer(){
    
    	$account = Account::findOne($this->ticket->id_account);
    	$discount = null;
    	if ( isset($this->ticket->id_account)){
    		$discount =  Discount::findOne( $this->ticket->id_discount );
    	}
    
    	$transfer = Transfer::createTicketTransfer($account, $discount, null, 1, $this->ticket);
    
    	$transfer->status  = Transfer::STATUS_PAID;
    	$transfer->paid_at =  date('Y-m-d H:i:s' ) ;
    	$transfer->paid_by = \Yii::$app->user->id;
    	$transfer->payment_method = Transfer::PAYMENT_METHOD_TRANSFER;
    	$transfer->money = $this->money;
    	$transfer->comment = "Csoportos beszedes";
    	$transfer->id_user = \Yii::$app->user->id;
    	$transfer->id_customer = $this->ticket->card->customer->id_customer;
    	$transfer->save(false);
    	return $transfer;
    }
    
    
    /**
     * @param common\models\Ticket $ticket
     * @param common\models\TicketType $type
     * @return common\models\TicketInstallmentRequest[] 
     * */
    public static function createInstallments($ticket,$type,$customer,$contract){
    	$result = [];
    	if ( $type->isInstallment() ){
    		$count = $type->installment_count;
    		$discount = $ticket->discount;
    		$money = $type->installment_money;
    		if ( isset( $discount ) ){
	    		$money = Discount::applyDiscount( $money, $discount );
    		}
    		
    		
    		
    		for ( $i = 1; $i <= $count; $i++){
    			$request = TicketInstallmentRequest::createInstallment($ticket, $type, $customer, $contract, $money, null, $i);
    			$result[] = $request;
    		}
    		
    	}
    	return $result;
    }
    
    public static function createInstallment($ticket,$type,$customer,$contract,$money,$ticketCreated,$index){
    	 $request = new TicketInstallmentRequest();
//     	 $request->id_ticket = $ticket->id_ticket;
    	 $request->id_customer = $customer->id_customer;
    	 $request->status = TicketInstallmentRequest::$STATUS_PENDING;
    	 $request->priority = $index;
    	 $date =  \DateTime::createFromFormat("Y.m.d", $contract->started_at, new \DateTimeZone( 'UTC'));
    	 $date->modify("+$index month");
    	 $date->setTime(0, 0, 0);
    	 $request->request_target_time_at  = $date->format ( 'Y-m-d H:i:s' );
    	 $request->request_processed_at = null;
    	 $request->request_sent_at = null;
    	 $request->money = $money;
    	 $request->id_contract = $contract->id_contract;
    	 
    	 return $request;
    }
    
    public static function statuses(){
    	return [
    			TicketInstallmentRequest::$STATUS_PENDING => 'Indításra vár',
    			TicketInstallmentRequest::$STATUS_MARKED_TO_SEND=> 'Beküldésre jelölve',
    			TicketInstallmentRequest::$STATUS_SENT=> 'Beküldve',
    			TicketInstallmentRequest::$STATUS_CANCELED=> 'Törölve',
    			TicketInstallmentRequest::$STATUS_REJECTED=> 'Visszautasítva',
    			TicketInstallmentRequest::$STATUS_ACCEPTED=> 'Sikeresen beszedés',
    			TicketInstallmentRequest::$STATUS_ACCEPTED_MANUAL=> 'Személyesen fizetve',
    	];
    }
    
    public static function toStatusName($id_status){
    	$result = "Ismeretlen";
    	$statuses = TicketInstallmentRequest::statuses();
    	if ( array_key_exists($id_status, $statuses)){
    		$result = $statuses[$id_status];
    	}
    	return $result;
    }
    
    public function getStatusName(){
    	return static::toStatusName($this->status);
    }
    
}
