<?php
/**
 * IMPORTANT NOTE
 * The code of this system is closed and a private proprietary of Flex Solutions.
 * A written authorization/license from Flex Solutions is required before using or modifying this code.
 * Email: sales@flexsolution.biz, Phone: +962795342585, Website: http://www.flexsolutions.biz
 */
 
/**
 * This is the model class for table "tid_status".
 *
 * The followings are the available columns in table 'tid_status':
 * @property integer $id
 * @property integer $tid_id
 * @property integer $contract_id
 * @property integer $cca_id
 * @property integer $ti_type_id
 * @property string $ti_issue_date
 * @property string $ti_expiry_date
 * @property string $ti_status
 * @property string $comments
 * @property integer $expiry_days
 * @property double $fine
 * @property integer $renewal_stage_id
 * @property string $under_processing
 * @property integer $created_by
 * @property string $created_date
 * @property integer $last_edited_by
 * @property string $last_edited_date
 *
 * The followings are the available model relations:
 * @property DashboardTids[] $dashboardTids
 * @property Cca $cca
 * @property Contract $contract
 * @property RenewalStage $renewalStage
 * @property Tid $tid
 * @property TiType $tiType
 *
 * @author Amaney
 * @package application.models
 */
class TidStatus extends TidansActiveRecord {


    /**
     * @return Date the contract expiry date of the contract related to TIDStatus
     */
    public $is_updated_from_asset = false;
    /**
     * @return Date the contract expiry date of the contract related to TIDStatus
     */
    public $contract_expiry_date;
    /**
     * @return String the old status of the tid
     */
    public $old_ti_status;
    /**
     * @return String the old status of the tid
     */
    public $old_ti_status_id;
    /**
     * @return String the old status of the tid
     */
    public $old_under_processing;
    /**
     * @return String the old status of the tid
     */
    public $old_renewal_stage_id;
     /**
     * @return String the old segment of the tid
     */
    public $old_tid_segment;
    

    /**
     * @return string the associated database table name
     */
    public function tableName() {
	return 'tid_status';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
	// NOTE: you should only define rules for those attributes that
	// will receive user inputs.
	return array(
	    array('tid_id, contract_id, cca_id, ti_type_id, ti_issue_date, ti_status', 'required'),
	    array('transferred_to_contract_id,tid_id, contract_id, cca_id, ti_type_id, expiry_days, renewal_stage_id', 'numerical', 'integerOnly' => true),
	    array('fine', 'numerical'),
	    array('ti_status', 'length', 'max' => 18),
	    array('comments', 'length', 'max' => 50),
	    array('under_processing', 'length', 'max' => 3),
	    array('ti_expiry_date', 'expireDateValidate'),
	    // The following rule is used by search().
	    // @todo Please remove those attributes that should not be searched.
	    array('id, tid_id,contract_expiry_date, contract_id, cca_id, ti_type_id, ti_issue_date, ti_expiry_date, ti_status, comments, expiry_days, fine, renewal_stage_id, under_processing', 'safe', 'on' => 'search'),
	);
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
	// NOTE: you may need to adjust the relation name and the related
	// class name for the relations automatically generated below.
	return array(
	    'dashboardTids' => array(self::HAS_MANY, 'DashboardTids', 'tid_status_id'),
	    'cca' => array(self::BELONGS_TO, 'Cca', 'cca_id'),
	    'contract' => array(self::BELONGS_TO, 'Contract', 'contract_id'),
	    'transferredContract' => array(self::BELONGS_TO, 'Contract', 'transferred_to_contract_id'),
	    'renewalStage' => array(self::BELONGS_TO, 'RenewalStage', 'renewal_stage_id'),
	    'tid' => array(self::BELONGS_TO, 'Tid', 'tid_id'),
	    'tiType' => array(self::BELONGS_TO, 'TiType', 'ti_type_id'),
	);
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
	return array(
	    'tid_id' => Yii::t('default', 'TID'),
	    'contract_id' => Yii::t('default', 'Contract Ref'),
	    'cca_id' => Yii::t('default', 'CCA'),
	    'ti_type_id' => Yii::t('default', 'TI Type'),
	    'ti_issue_date' => Yii::t('default', 'Issue Date'),
	    'ti_expiry_date' => Yii::t('default', 'Expiry Date'),
	    'ti_status' => Yii::t('default', 'Status'),
	    'comments' => Yii::t('default', 'Comments'),
	    'expiry_days' => Yii::t('default', 'Expiry Days'),
	    'fine' => Yii::t('default', 'Fine'),
	    'renewal_stage_id' => Yii::t('default', 'Processing Stage'),
	    'under_processing' => Yii::t('default', 'Under Processing'),
	    'last_edited_by' => Yii::t('default', 'Last Updated By'),
	    'transferred_to_contract_id' => Yii::t('default', 'Transfer to Contract'),
	);
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     *
     * Typical usecase:
     * - Initialize the model fields with values from filter form.
     * - Execute this method to get CActiveDataProvider instance which will filter
     * models according to data in model fields.
     * - Pass data provider to CGridView, CListView or any similar widget.
     *
     * @return CActiveDataProvider the data provider that can return the models
     * based on the search/filter conditions.
     */
    public function search($tid_id = null) {
	// @todo Please modify the following code to remove attributes that should not be searched.

	$criteria = $this->ModelCriteria($tid_id);

	$sort = new CSort();
	if ($tid_id == null)
	    $sort->defaultOrder = 't.tid_id';
	else
	    $sort->defaultOrder = 't.created_date desc';
	$sort->attributes = array(
	    'contract_expiry_date' => array(
		'asc' => 'contract.expiry_date',
		'desc' => 'contract.expiry_date desc',
	    ),
	    '*',
	);

	$pageSize = $this->yiiparam('pageSize');
	return new CActiveDataProvider($this, array(
	    'pagination' => array('pageSize' => $pageSize,),
	    'criteria' => $criteria,
	    'sort' => $sort
	));
    }

    /**
     * Get the query used to get the current model information to be used in export to excel action
     * @return CDbCriteria the criteria used to get the current model information
     */
    public function ModelCriteria($tid_id = null) {
	$criteria = new CDbCriteria;

	$criteria->compare('tid_id', $this->tid_id);
	$criteria->compare('contract.reference', $this->contract_id, true);
	$criteria->compare('contract.expiry_date', $this->contract_expiry_date, true);
	$criteria->compare('cca.full_name', $this->cca_id, true);
	$criteria->compare('ti_type.name', $this->ti_type_id, true);
	$criteria->compare('ti_issue_date', $this->ti_issue_date, true);
	$criteria->compare('ti_expiry_date', $this->ti_expiry_date, true);
	$criteria->compare('ti_status', $this->ti_status, true);
	$criteria->compare('t.comments', $this->comments, true);
	$criteria->compare('t.expiry_days', $this->expiry_days);
	$criteria->compare('t.fine', $this->fine);
	$criteria->compare('renewal_stage.name', $this->renewal_stage_id, true);
	$criteria->compare('transfer_contract.reference', $this->transferred_to_contract_id, true);
	$criteria->compare('t.under_processing', $this->under_processing, true);
	$criteria->join = 'inner join v_tid tid on tid.id = t.tid_id
			   inner join contract on contract.id = t.contract_id
			   inner join contract transfer_contract on transfer_contract.id = t.contract_id
			   inner join cca on cca.id = t.cca_id
			   inner join ti_type on ti_type.id = t.ti_type_id
			   left join renewal_stage on renewal_stage.id = t.renewal_stage_id
			   left join user on user.id = t.last_edited_by';
	if ($tid_id != null)
	    $criteria->compare('tid_id', $tid_id);
	return $criteria;
    }

    /**
     * Returns the static model of the specified AR class.
     * Please note that you should have this exact method in all your CActiveRecord descendants!
     * @param string $className active record class name.
     * @return TidStatus the static model class
     */
    public static function model($className = __CLASS__) {
	return parent::model($className);
    }

    /**
     * Save TID status information    
     * @return string the status of the tid
     */
    public function setTidStatus(&$tid) {
	if ($this->tiType != null) {
	    if ($this->tiType->validity_mode == 'Permanent')
		return 'Permanent';
	}
	else {
	    $ti_type = TiType::model()->findByPk($this->ti_type_id);
	    if ($ti_type != null)
		if ($ti_type->validity_mode == 'Permanent')
		    return 'Permanent';
	}
	if ($this->ti_expiry_date != null || $this->ti_expiry_date != '') {
	    $is_parilly_exported = false;
	    $index = 0;
	    $is_expired = false;
	    $is_grace = false;
	    $settings_array = Setting::getSettingsArray();
	    $grace_period = $settings_array['grace_period'];
	    $grace_expire_date = date("Y-m-d", strtotime(date("Y-m-d", strtotime(date("Y-m-d"))) . " +$grace_period day"));
	    $current_date = date("Y-m-d", strtotime(date("Y-m-d")));
	    if ($this->ti_expiry_date <= $current_date)
		$is_expired = true;
	    if ($this->ti_expiry_date <= $grace_expire_date)
		$is_grace = true;
	    if ($tid->assets != null && count($tid->assets) > 0) {
		foreach ($tid->assets as $asset) {
		    if ($asset->asset_status == 'Exported') {
			$is_parilly_exported = true;
			$index++;
		    }
		}
		if ($index == count($tid->assets)) {
		    return 'Exported';
		}

		if ($is_parilly_exported && !$is_expired && !$is_grace)
		    return 'Partially Exported';
	    }
	    if ($is_expired)
		return 'Expired';

	    if ($is_grace)
		return 'Grace';
	}
	return 'Valid';
    }

    /**
     * The following validation is responsible for checking if the expire date doesn't exceed the maximum allowed period for badges
     */
    public function expireDateValidate($attribute, $params) {
	if (isset($this->ti_expiry_date) && $this->ti_expiry_date != "" && isset($this->contract_id) && $this->contract_id != "") {
	    if ($this->ti_expiry_date > $this->contract->expiry_date) {
		if (isset($this->ti_type_id)) {
		    if ($this->tiType->validity_mode != 'Permanent')
			$this->addError('ti_expiry_date', Yii::t('default', 'The TID expiry date (' . $this->ti_expiry_date . ') cannot exceed the contract expiry date (' . $this->contract->expiry_date . ')'));
		} else
		    $this->addError('ti_expiry_date', Yii::t('default', 'The TID expiry date (' . $this->ti_expiry_date . ') cannot exceed the contract expiry date (' . $this->contract->expiry_date . ')'));

		return;
	    }
	}
	else {
	    if (!isset($this->ti_expiry_date) || $this->ti_expiry_date == "") {
		if (isset($this->ti_type_id) && $this->ti_type_id != "") {
		    if ($this->tiType->validity_mode != 'Permanent')
			$this->addError('ti_expiry_date', Yii::t('default', 'TI Expiry Date cannot be blank'));
		}
	    }
	}
    }

    /**
     * Returns the tid status options
     *
     * @return Array the tid status options
     */
    public static function getStatusOptions() {
	return array(
	    'Valid' => Yii::t('default', 'Valid'),
	    'Grace' => Yii::t('default', 'Grace'),
	    'Expired' => Yii::t('default', 'Expired'),
	    'Partially Exported' => Yii::t('default', 'Partially Exported'),
	    'Exported' => Yii::t('default', 'Exported'),
	    'Permanent' => Yii::t('default', 'Permanent'),
	);
    }

//    protected function afterFind() {
//	$this->old_ti_status = $this->ti_status;
//	return parent::afterFind();
//    }


    protected function beforeDelete() {
	if ($this->tid != null) {
	    $status = $this->tid->getLastStatus();
	    $this->old_ti_status_id = ($status == null) ? null : $status->id;
	    $this->old_under_processing = ($status == null) ? null : $status->under_processing;
	    $this->old_renewal_stage_id = ($status == null) ? null : $status->renewal_stage_id;
	}
	return parent::beforeDelete();
    }

    protected function beforeSave() {
	if ($this->tid != null) {
	    $status = $this->tid->getLastStatus();
	    $this->old_ti_status = ($status == null) ? null : $status->ti_status;
	    $this->old_under_processing = ($status == null) ? null : $status->under_processing;
	    $this->old_renewal_stage_id = ($status == null) ? null : $status->renewal_stage_id;
	}
	return parent::beforeSave();
    }

    /**
     * Check if two status are equal or not
     *
     * @return Boolean true if two status are equal , false otherwise
     */
    public static function isEqual($first_status, $second_status) {
	if ($first_status != null && $second_status != null) {
	    if ($first_status->id == $second_status->id)
		return true;
	    return false;
	}
	return true;
    }

}
