<?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".
 *
 * The followings are the available columns in table 'tid':
 * @property integer $id
 * @property integer $point_of_entry_id
 * @property string $number
 * @property string $tid_no
 * @property string $initial_issue_date
 * @property string $customs_letter_no
 * @property string $customs_letter_date
 * @property string $shipment_ref
 * @property string $original_documnets_delivery_date
 * @property string $value
 * @property string $exported_date
 * @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 Document[] $documents
 * @property DocumentTypeTid[] $documentTypeTs
 * @property Invoice[] $invoices
 * @property PointOfEntry $pointOfEntry
 * @property TidStatus[] $tidStatuses
 *
 * @author Amaney
 * @package application.models
 */
class Tid extends TidansActiveRecord {

    public $document_array, $document_type_ids;
    /**
     * @return Integer the id of ti type of the status of the tid
     */
    public $ti_type_id;
    /**
     * @return Date the ti issue date of the status of the tid
     */
    public $ti_issue_date;
    /**
     * @return Date the ti expiry date of the status of the tid
     */
    public $ti_expiry_date;
    /**
     * @return Integer the id of contract of status of the tid
     */
    public $contract_id;
    /**
     * @return Integer the id of cca of the status of the tid
     */
    public $cca_id;
    /**
     * @return String the comments of the status of the tid
     */
    public $comments;
    /**
     * @return boolean the under processing of the status of the tid
     */
    public $under_processing;
    /**
     * @return Integer the id of renewal stage of the status of the tid
     */
    public $renewal_stage_id;
    /**
     * @return String the status of the tid
     */
    public $ti_status;
    /**
     * @return String the transferred contract id
     */
    public $transferred_to_contract_id;
    public $old_issue_date;

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

    /**
     * @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('point_of_entry_id, number, tid_no, initial_issue_date, shipment_ref', 'required'),
	    array('point_of_entry_id', 'numerical', 'integerOnly' => true),
	    array('value', 'validateValue'),
	    array('number', 'length', 'max' => 45),
	    array('value', 'length', 'max' => 15),
	    array('tid_no', 'unique'),
	    array('number', 'unique'),
	    array('tid_no, shipment_ref', 'length', 'max' => 20),
	    array('customs_letter_no', 'length', 'max' => 15),
	    array('transferred_to_contract_id,document_type_ids,document_array,ti_status,ti_type_id,ti_issue_date,ti_expiry_date,contract_id,cca_id,comments,under_processing,renewal_stage_id,customs_letter_date, original_documnets_delivery_date, exported_date', 'safe'),
	    // The following rule is used by search().
	    // @todo Please remove those attributes that should not be searched.
	    array('id,
		ti_status,ti_type_id,ti_issue_date,ti_expiry_date,contract_id,cca_id,comments,under_processing,renewal_stage_id,
		point_of_entry_id, number, tid_no, initial_issue_date, customs_letter_no, customs_letter_date, shipment_ref, original_documnets_delivery_date, value, exported_date', '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_id'),
	    'documents' => array(self::HAS_MANY, 'Document', 'tid_id'),
	    'documentTypeTs' => array(self::HAS_MANY, 'DocumentTypeTid', 'tid_id'),
	    'invoices' => array(self::HAS_MANY, 'Invoice', 'tid_id'),
	    'pointOfEntry' => array(self::BELONGS_TO, 'PointOfEntry', 'point_of_entry_id'),
	    'tidStatuses' => array(self::HAS_MANY, 'TidStatus', 'tid_id'),
	    'assets' => array(self::HAS_MANY, 'VAsset', 'tid_id'),
	);
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
	return array(
	    'point_of_entry_id' => Yii::t('default', 'Point of Entry'),
	    'number' => Yii::t('default', 'Number'),
	    'tid_no' => Yii::t('default', 'TID No'),
	    'initial_issue_date' => Yii::t('default', 'Initial Issue Date'),
	    'customs_letter_no' => Yii::t('default', 'Customs Letter No'),
	    'customs_letter_date' => Yii::t('default', 'Customs Letter Date'),
	    'shipment_ref' => Yii::t('default', 'Shipment Ref'),
	    'original_documnets_delivery_date' => Yii::t('default', 'Original Documnets Delivery Date'),
	    'value' => Yii::t('default', 'Value'),
	    'exported_date' => Yii::t('default', 'Exported Date'),
	    'contract_id' => Yii::t('default', 'Contract Ref') . "<font class='red-star' color='red'> * </font>",
	    'cca_id' => Yii::t('default', 'CCA') . "<font class='red-star' color='red'> * </font>",
	    'ti_type_id' => Yii::t('default', 'TI Type') . "<font class='red-star' color='red'> * </font>",
	    'ti_issue_date' => Yii::t('default', 'Issue Date') . "<font class='red-star' color='red'> * </font>",
	    'ti_expiry_date' => Yii::t('default', 'Expiry Date') . "<font class='red-star' color='red'> * </font>",
	    'ti_status' => Yii::t('default', 'Status'),
	    'comments' => Yii::t('default', 'Comments'),
	    'renewal_stage_id' => Yii::t('default', 'Processing Stage'),
	    'under_processing' => Yii::t('default', 'Under Processing'),
	    '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();
	$sort->defaultOrder = 't.id';
	$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->order = 'id';
	$criteria->compare('point_of_entry.name', $this->point_of_entry_id, true);
	$criteria->compare('number', $this->number, true);
	$criteria->compare('tid_no', $this->tid_no, true);
	$criteria->compare('initial_issue_date', $this->initial_issue_date, true);
	$criteria->compare('customs_letter_no', $this->customs_letter_no, true);
	$criteria->compare('customs_letter_date', $this->customs_letter_date, true);
	$criteria->compare('shipment_ref', $this->shipment_ref, true);
	$criteria->compare('original_documnets_delivery_date', $this->original_documnets_delivery_date, true);
	$criteria->compare('value', $this->value, true);
	$criteria->compare('exported_date', $this->exported_date, true);



	$ids = $this->setTidStatusConditions($criteria);
	if ($ids != '')
	    $criteria->addCondition('t.id in (' . $ids . ')');


	if ($tid_id != null)
	    $criteria->addCondition('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 Tid the static model class
     */
    public static function model($className = __CLASS__) {
	return parent::model($className);
    }

    /**
     * The following validation is responsible for checking if the value has this format #.# where # means any number
     */
    public function validateValue($attribute, $params) {
	if ($this->value != null && $this->value != '') {
	    $numbers = explode('.', $this->value);
	    if (count($numbers) > 2)
		$this->addError('value', Yii::t('default', 'The value should be a valid real number.'));
	    else {
		if (count($numbers) == 1) {
		    if (!is_numeric($numbers[0]))
			$this->addError('value', Yii::t('default', 'The value should be a valid real number.'));
		}
		else {
		    if (!is_numeric($numbers[0]) || !is_numeric($numbers[1]))
			$this->addError('value', Yii::t('default', 'The value should be a valid real number.'));
		}
	    }
	}
    }

    /**
     * Save TID status information
     * @param string $error_msg the error msg if saving tid status failed.
     * @param Boolean $is_create_action if the request action is create or update
     * @return Boolean true if saving tid status successed , false otherwise
     */
    public function createUpdateStatus($is_create_action, &$error_msg) {
	$status = ($is_create_action) ? new TidStatus() : $this->getLastStatus();

	$status->ti_type_id = $this->ti_type_id;
	$status->cca_id = $this->cca_id;
	$status->contract_id = $this->contract_id;
	$status->renewal_stage_id = $this->renewal_stage_id;
	$status->comments = $this->comments;
	$status->under_processing = $this->under_processing;
	if ($status->under_processing == 'No' || $status->under_processing == 0) {
	    $status->renewal_stage_id = null;
	    $status->transferred_to_contract_id = null;
	}

	$status->transferred_to_contract_id = $this->transferred_to_contract_id;
	if ($status->renewal_stage_id == null || $status->renewal_stage_id != Setting::getUnderTransferOfPrivilege())
	    $status->transferred_to_contract_id = null;

	$status->ti_expiry_date = $this->ti_expiry_date;
	$status->ti_issue_date = $this->ti_issue_date;

	$status->ti_status = $status->setTidStatus($this);
	if ($status->ti_status == 'Exported') {
	    $this->exported_date = date("Y-m-d");
	    if (!$this->save())
		Yii::app()->user->setFlash('error', CHtml::errorSummary($this));
	}
	$status->tid_id = $this->id;
	if ($status->save())
	    return true;
	else {
	    $error_msg = CHtml::errorSummary($status);
	    return false;
	}
    }

    /**
     * Get the last status of tid
     * @return TidStatus the last tid status of the tid
     */
    public function getLastStatus($allow_null = false) {
	$cr = new CDbCriteria();
	$cr->condition = 'tid_id = ' . $this->id;
	$cr->order = 'created_date desc';
	$cr->limit = 1;
	$status = TidStatus::model()->find($cr);
	if ($status == null && !$allow_null)
	    $status = new TidStatus();

	return $status;
    }

    /**
     * Get before last status of tid
     * @return TidStatus the before last tid status of the tid
     */
    public function getBeforeLastStatus() {
	$cr = new CDbCriteria();
	$cr->condition = 'tid_id = ' . $this->id;
	$cr->order = 'created_date desc';
	$cr->limit = 2;
	$status = TidStatus::model()->findAll($cr);
	if ($status == null)
	    return new TidStatus();
	if (count($status) > 1)
	    return $status[1];
	else
	    return $status[0];
    }

    /**
     * Fill information of last TID status    
     */
    public function fillLastStatusInfo() {
	$status = $this->getLastStatus();
	if ($status != null) {
	    $this->ti_type_id = $status->ti_type_id;
	    $this->cca_id = $status->cca_id;
	    $this->contract_id = $status->contract_id;
	    $this->renewal_stage_id = $status->renewal_stage_id;
	    $this->comments = $status->comments;
	    $this->under_processing = $status->under_processing;
	    $this->ti_expiry_date = $status->ti_expiry_date;
	    $this->ti_issue_date = $status->ti_issue_date;
	    $this->transferred_to_contract_id = $status->transferred_to_contract_id;
	}
    }

    /**
     * Save TID documents
     * @param string $error_msg the error msg if saving tid documents failed.
     * @return Boolean true if saving tid documents successed , false otherwise
     */
    public function saveDocuments(&$error_msg, $transaction = null) {
	$result = Document::saveModelDocuments($this, $transaction);
	if ($result == "") {
	    if ($this->saveDocumenttypes($this->document_type_ids, $result))
		return true;
	}
	$error_msg = $result;
	return false;
    }

    /**
     *  generate the unique number for TID
     */
    protected function beforeValidate() {
	if ($this->isNewRecord) {
	    $this->number = $this->generateNumber();
	} else {
	    if ($this->old_issue_date != $this->initial_issue_date)
		$this->number = $this->generateNumber();
	}
	return parent::beforeValidate();
    }

    /**
     * generate TID number
     *
     */
    public function generateNumber() {

	if ($this->initial_issue_date != null) {
	    $cr = new CDbCriteria();
	    $static_part = date("d-m-y", strtotime($this->initial_issue_date)); //(date("y"));
	    $cr->select = "MAX(CAST(SUBSTRING(number, 10, length(number) - 9) AS UNSIGNED)) AS MaxNumber";
	    $cr->condition = "number like '%" . $static_part . "%'";

	    $model = Tid::model();
	    //Get max sequence number
	    $seq_number = $model->commandBuilder->createFindCommand(
			    $model->tableName(), $cr)->queryScalar();
	    //FORMAT THE NUMBER TO BE 3 DIGITS
	    $seq_number = $static_part . "-" . str_pad((string) ($seq_number + 1), 3, '0', STR_PAD_LEFT);

	    return $seq_number;
	}
	return null;
    }

    /**
     * check if tid status info is applied in the seach query and build the query for it
     * @param string $error_msg the error msg if saving tid documents failed.
     * @return String the ids of TIds seperated by comma that satisfy the conditions
     */
    public function setTidStatusConditions() {
	$ids = "";
	if ($this->contract_id != null || $this->cca_id != null ||
		$this->ti_type_id != null || $this->ti_issue_date != null ||
		$this->ti_expiry_date != null || $this->ti_status != null ||
		$this->comments != null || $this->renewal_stage_id != null || $this->under_processing != null) {

	    $criteria = new CDbCriteria();
	    $criteria->select = 't.tid_id';
	    $criteria->compare('contract.reference', $this->contract_id, 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('renewal_stage.name', $this->renewal_stage_id, true);
	    $criteria->compare('t.under_processing', $this->under_processing, true);
	    $criteria->compare('transferrd_contract.reference', $this->transferred_to_contract_id, true);

	    $criteria->join = 'inner join contract on 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
			   inner join contract transferrd_contract on transferrd_contract.id = t.transferred_to_contract_id';

	    $model = new TidStatus();
	    $result = $model->commandBuilder->createFindCommand(
			    $model->tableName(), $criteria)->queryAll();


	    foreach ($result as $res) {
		$ids .= $res['tid_id'] . ",";
	    }
	    $ids = substr($ids, 0, -1);
	    if ($ids == '')
		$ids = '-1';
	}
	return $ids;
    }

    /**
     * Save all document types for current tid
     * @param string $document_type_string the ids of document types seperated by comma
     * @param String $error_msg the error msg that may happend
     * @return Boolean true if saving all document types correctly, false otherwise
     */
    public function saveDocumenttypes($document_type_string, &$error_msg) {
	$document_types = explode(',', $document_type_string);
	if ($document_types != null)
	    foreach ($document_types as $doc_type) {
		if ($doc_type != '' && $doc_type != null) {
		    $exist_doc_type = DocumentTypeTid::model()->findAllByAttributes(array('tid_id' => $this->id, 'document_type_id' => $doc_type));
		    if ($exist_doc_type != null)
			continue;
		    $docTypeTid = new DocumentTypeTid;
		    $docTypeTid->document_type_id = $doc_type;
		    $docTypeTid->tid_id = $this->id;
		    if (!$docTypeTid->save()) {
			$error_msg = CHtml::errorSummary($docTypeTid);
			return false;
		    }
		}
	    }
	if ($document_type_string != '') {
	    $cr = new CDbCriteria();
	    $last_char = substr($document_type_string, -1);
	    $document_type_string = ($last_char == ',') ? substr($document_type_string, 0, -1) : $document_type_string;
	    $cr->condition = 'document_type_id not in (' . $document_type_string . ') and tid_id = ' . $this->id;
	    $doc_types = DocumentTypeTid::model()->findAll($cr);
	    //$doc_types = DocumentTypeTid::model()->findAll($cr);
	    if ($doc_types != null)
		foreach ($doc_types as $doc_type_model)
		    $doc_type_model->delete();
	}
	else {
	    $cr = new CDbCriteria();
	    $cr->condition = 'tid_id = ' . $this->id;
	    $doc_types = DocumentTypeTid::model()->findAll($cr);
	    if ($doc_types != null)
		foreach ($doc_types as $doc_type_model)
		    $doc_type_model->delete();
	}
	return true;
    }

    /**
     * Get all document types for a specific tid
     * @param Integer $id the id of tid     
     * @return Array[] the ids of document types  for a specific tid
     */
    public static function getSelectedDocumentType($id) {
	$result = null;
	if ($id != null && $id != '') {
	    $cr = new CDbCriteria();
	    $cr->select = "document_type_id";
	    $cr->condition = "tid_id =" . $id;
	    $model = DocumentTypeTid::model();
	    $result = $model->commandBuilder->createFindCommand(
			    $model->tableName(), $cr)->queryColumn();
	}
	if ($result == null)
	    $result = array();

	return $result;
    }

    /**
     * Get all document types as string for a specific tid
     * @param Integer $id the id of tid     
     * @return String the ids of document types  for a specific tid seperated by comma
     */
    public static function getSelectedDocumentTypeAsString($id) {
	$result = '';
	$doctypes = Tid::getSelectedDocumentType($id);
	if ($doctypes != null) {
	    foreach ($doctypes as $doctype) {
		$result .= $doctype . ',';
	    }
	}
	if ($result != '')
	    return substr($result, 0, -1);
	return $result;
    }

    /**
     * The Following function is responsible for return array of all tids
     *
     * @return Tid[] array of Tid model .
     */
    public static function getNumberForView() {
	$result = Tid::getNumberLists();
	$names = array();
	foreach ($result as $res) {
	    $names[$res] = $res;
	}
	return $names;
    }

    /**
     * The Following function is responsible for return array of all Tids
     *
     * @return Tid[] array of Tid model .
     */
    public static function getNumberLists() {
	$model = Tid::model();
	$criteria = new CDbCriteria;
	$criteria->select = 'tid_no';
	$criteria->order = 'tid_no';
	return $model->commandBuilder->createFindCommand($model->tableName(), $criteria)->queryColumn();
    }

    /**
     * The Following function is responsible for return array of all Tids to display in drop dwon
     *
     * @return Tid[] array of Tid model .
     */
    public static function getNumbersForDropDown() {
	$model = Tid::model();
	$criteria = new CDbCriteria;
	$criteria->select = 'id,tid_no';
	$criteria->order = 'tid_no';
	$result = $model->commandBuilder->createFindCommand($model->tableName(), $criteria)->queryAll();
	$names = array();
	foreach ($result as $res) {
	    $names[$res['id']] = $res['tid_no'];
	}
	return $names;
    }

    /**
     * The Following function is responsible for return the id based on number
     * @param String $number the number of tid
     * @return Integer the id of the Tid model .
     */
    public static function getIdfromNumber($number) {
	$tid = Tid::model()->findByAttributes(array('tid_no' => $number));
	if ($tid != null)
	    return $tid->id;
	return $number;
    }

    /**
     * The Following function is responsible for return the number based on id of tid
     * @param String $id the id of tid
     * @return Integer the tid_no of the Tid model .
     */
    public static function getNumberfromId($id) {
	$tid = Tid::model()->findByPk($id);
	if ($tid != null)
	    return $tid->tid_no;
    }

    /**
     * The Following function is responsible for return the segment(s)of the tid
     * @param String $id the id of tid
     * @return string the segment of the Tid .
     */
//    public static function getSegmentInfo($id) {
//	$model = VTid::model();
//	$criteria = new CDbCriteria;
//	$criteria->select = 'segment_name,segment_id';
//	$criteria->condition = 'id=' . $id;
//	$result = $model->commandBuilder->createFindCommand($model->tableName(), $criteria)->queryAll();
//	return ($result != null) ? $result[0] : null;
//    }

    /**
     * The Following function is responsible for return the segment(s)of the tid before adding current asset
     * @param String $asset the asset that added
     * @return string the segment of the Tid .
     */
    public function getOldSegmentInfoWithoutSpecificAsset($asset) {
	$segment_name_array = array();
	$segment_id_array = array();


	if ($this->assets != null) {
	    foreach ($this->assets as $tid_asset) {
		if ($tid_asset->id != $asset->id) {
		    if (!array_key_exists($tid_asset->segment_name, $segment_name_array))
			$segment_name_array[$tid_asset->segment_name] = $tid_asset->segment_name;
		    if (!array_key_exists($tid_asset->segment_id, $segment_id_array))
			$segment_id_array[$tid_asset->segment_id] = $tid_asset->segment_id;
		}
	    }
	    return array('segment_id' => implode(",", $segment_id_array), 'segment_name' => implode(",", $segment_name_array));
	}
	return array('segment_id' => null, 'segment_name' => null);
    }

    /**
     * The Following function is responsible for return the segment(s)of the tid
     * @param String $id the id of tid
     * @return string the segment of the Tid .
     */
    public function getSegmentInfo() {
//	$segment_name = '';
//	$segment_id = '';
	$segment_name_array = array();
	$segment_id_array = array();
//	if ($this->invoices != null) {
//	    foreach ($this->invoices as $invoice) {
//		if ($invoice->assets != null) {
//		    foreach ($invoice->assets as $asset) {
//			if (!array_key_exists($asset->segment->name, $segment_name_array))
//			    $segment_name_array[$asset->segment->name] = $asset->segment->name;
//			if (!array_key_exists($asset->segment_id, $segment_id_array))
//			    $segment_id_array[$asset->segment_id] = $asset->segment_id;
//			//$segment_name .= $asset->segment->name . ',';
//		    }
//		}
//	    }
//	}
//	if (empty ($segment_name_array))
//	    return null;
//	return array('segment_id' => implode(",", $segment_id_array), 'segment_name' => implode(",", $segment_name_array));
//	$model = VTidDashboard::model();
//	$criteria = new CDbCriteria;
//	$criteria->select = 'segment_name,segment_id';
//	$criteria->condition = 'id=' . $this->id;
//	$result = $model->commandBuilder->createFindCommand($model->tableName(), $criteria)->queryAll();
//	return ($result != null) ? $result[0] : null;
//	

	$model = VSegmentDashboard::model();
	$criteria = new CDbCriteria;
	$criteria->select = 'segment_name,segment_id';
	$criteria->condition = 'tid_id=' . $this->id;
	$segments = $model->commandBuilder->createFindCommand($model->tableName(), $criteria)->queryAll();
	//return ($result != null) ? $result[0] : null;
	if ($segments != null) {
	    foreach ($segments as $segment) {
		if (!array_key_exists($segment['segment_name'], $segment_name_array))
		    $segment_name_array[$segment['segment_name']] = $segment['segment_name'];
		if (!array_key_exists($segment['segment_id'], $segment_id_array))
		    $segment_id_array[$segment['segment_id']] = $segment['segment_id'];
		//$segment_name .= $asset->segment->name . ',';
	    }
	}
	return array('segment_id' => implode(",", $segment_id_array), 'segment_name' => implode(",", $segment_name_array));
    }

    /**
     * The Following function is responsible for updating tid status
     * @param String $error_msg the error msg if any error happend
     * @return Boolean true if successfully updating the status, false otherwise .
     */
    public function updateStatus(&$error_msg, $old_segment = null) {
	$last_status = $this->getLastStatus();
	if ($last_status != null) {
	    $last_status->ti_status = $last_status->setTidStatus($this);
	    $last_status->is_updated_from_asset = true;
	    $last_status->old_tid_segment = $old_segment;
	    if (!$last_status->save()) {
		$error_msg = CHtml::errorSummary($last_status);
		return false;
	    }
	}
	if ($last_status->ti_status == 'Exported') {
	    $this->exported_date = date("Y-m-d");
	    if (!$this->save()) {
		$error_msg = CHtml::errorSummary($this);
		return false;
	    }
	}
	return true;
    }

    /**
     * The Following function is responsible for setting failure message when delete tid
     * @return string the failure message
     */
    public function setTidFailureMessage() {
	$failer_msg = '';
	if ($this->invoices != null && count($this->invoices) > 0 && $this->tidStatuses != null && count($this->tidStatuses) > 0)
	    $failer_msg = Yii::t('default', 'You cannot delete this element, you need to delete its invoices and statuses first');
	else
	if ($this->invoices != null && count($this->invoices) > 0) {
	    $failer_msg = Yii::t('default', 'You cannot delete this element, you need to delete its invoices first');
	} else
	if ($this->tidStatuses != null && count($this->tidStatuses) > 0) {
	    $failer_msg = Yii::t('default', 'You cannot delete this element, you need to delete its statuses first');
	}
	else
	    $failer_msg = Yii::t('default', 'You cannot delete this element because it is referenced by dashboard reports');
	return $failer_msg;
    }

    /**
     * The Following function is responsible for update all tid status
     * @return Tid[] the expired tids in order to send notification to the users
     */
    public static function UpdateAllTIDStatuses(&$error_msg) {
	$expired_models = array();
	$grace_period = Setting::getGracePeriod();
	$grace_expire_date = date("Y-m-d", strtotime(date("Y-m-d", strtotime(date("Y-m-d"))) . " +$grace_period day"));
	$criteria = new CDbCriteria();
	$criteria->condition = "(last_status_ti_expiry_date <='" . $grace_expire_date . "') and last_status_ti_status != 'Exported' and last_status_ti_status != 'Permanent'";
	$tids = VTid::model()->findAll($criteria);
	if ($tids != null) {
	    foreach ($tids as $tid) {
		$tid_status = $tid->getLastStatus();
		if ($tid_status != null) {
		    $status = $tid_status->setTidStatus($tid);
		    if ($tid_status->ti_status == 'Exported') {
			$tid_status->tid->exported_date = date("Y-m-d");
			if (!$tid_status->tid->save()) {
			    $error_msg = CHtml::errorSummary($tid);
			    break;
			}
		    }

		    if ($tid_status->ti_status != $status) {
			$tid_status->ti_status = $status;
			if (!$tid_status->save()) {
			    $error_msg = CHtml::errorSummary($tid_status);
			    break;
			} else {
			    if ($status == 'Expired')
				$expired_models[] = $tid;
			}
		    } else {
			if ($status == 'Expired') {
			    $fine = Setting::getFine();
			    //$expired_models[] = $tid;
			    $diff = abs(strtotime($tid_status->ti_expiry_date) - strtotime(date("Y-m-d")));
			    $years = floor($diff / (365 * 60 * 60 * 24));
			    $months = floor(($diff - $years * 365 * 60 * 60 * 24) / (30 * 60 * 60 * 24));
			    $days = floor(($diff - $years * 365 * 60 * 60 * 24 - $months * 30 * 60 * 60 * 24) / (60 * 60 * 24));
			    $tid_status->expiry_days = $days + 1;
			    $tid_status->fine = ($days + 1) * $fine;
			    if (!$tid_status->save()) {
				$error_msg = CHtml::errorSummary($tid_status);
				break;
			    }
			}
		    }
		}
	    }
	}
	return $expired_models;
    }

    /**
     * The following function is called when the system check if the expiry date of tid and its asset to change tid status
     * And then notifiy concerned people
     */
    public static function UpdateTIDStatusAndSendEmails() {
	Yii::log('Start Update TID Status', 'info', 'system.Scheduler.UpdateTIDStatus');

	try {

	    $error_msg = '';
	    $expired_models = Tid::UpdateAllTIDStatuses($error_msg);
	    $tid_message = '';
	    if ($expired_models != null && $error_msg == '') {
		foreach ($expired_models as $tid) {
		    $segment_msg = ($tid->segment_name == null) ? ')' : (strpos($tid->segment_name, ',') !== false ? ') which is related to segments  (' . $tid->segment_name : ') which is related to segment (' . $tid->segment_name);
		    $tid_message .= '<br/>The TID (' . $tid->tid_no . $segment_msg . ')  is expired on (' . $tid->last_status_ti_expiry_date . ')';
		}
		TidansActiveRecord::SendNotification('TIDANS - TID Expired', '<br/>' . $tid_message . '.<br/><br/>  Please take the needed action.<br/><br/>');
	    } else {
		if ($error_msg != '') {
		    TIDANSMail::sendMail("TIDANS - Update TID Status Error ",
				    "An error has been occurred while updating tid status.<br/>
				    Please contact Flex Solutions support team to investigate this issue.",
				    Yii::app()->params["support_email"]);
		    Yii::log('Error' . PHP_EOL . $error_msg, 'info', 'system.Scheduler.UpdateTIDStatus');
		}
	    }

	    Yii::log('End Update TID Status', 'info', 'system.Scheduler.UpdateTIDStatus');
	} catch (Exception $ex) {
	    TIDANSMail::sendMail("TIDANS - Update TID Status Error ",
			    "An error has been occurred while updating tid status.<br/>
				    Please contact Flex Solutions support team to investigate this issue.",
			    Yii::app()->params["support_email"]);
	    Yii::log(' RollBack ', 'error', 'system.Scheduler.UpdateTIDStatus');
	    Yii::log($ex->__toString(), 'error', 'system.Scheduler.UpdateTIDStatus');
	    return;
	}
    }

    /**
     * The Following function is responsible for check if tid identifier input is from autocomplete list
     * @param string $tid_identifier the tid identifier to check
     * @return boolean true if tid identifier inside autocomplete list, false otherwise.
     */
    public static function checkTidInsideArrayOfTids($tid_identifier) {

	$tids = array_values(tid::getNumbersForDropDown());
	if ($tid_identifier != null && $tid_identifier != "") {
	    if (!in_array($tid_identifier, $tids))
		return false;
	}
	return true;
    }

    protected function afterFind() {
	$this->old_issue_date = $this->initial_issue_date;
	return parent::afterFind();
    }

}
