<?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 "asset".
 *
 * The followings are the available columns in table 'asset':
 * @property integer $id
 * @property integer $invoice_id
 * @property integer $type_of_asset_id
 * @property string $serial_number
 * @property string $asset_number
 * @property string $part_number
 * @property string $description
 * @property string $asset_status
 * @property string $plate_number
 * @property string $chassis_number
 * @property string $radioactive_license_number
 * @property integer $segment_id
 * @property string $po_number
 * @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 Invoice $invoice
 * @property Segment $segment
 * @property TypeOfAsset $typeOfAsset
 * @property AssetStatus[] $assetStatuses
 * @property DahsboardAsset[] $dahsboardAssets
 *
 *
 * @author Amaney
 * @package application.models
 */
class Asset extends TidansActiveRecord {

    /**
     * @return Integer the id of tid that the asset belong to
     */
    public $tid_id;
    /**
     * @return Integer the id of old tid that the asset was belong to
     */
    public $old_tid_id;
    /**
     * @return Date the expiry date of radio active type
     */
    public $radioactive_license_expiry_date;
    /**
     * @return Date the expiry date of vehicle type
     */
    public $vehicle_book_expiry_date;
    /**
     * @return String the Warning message
     */
    public $warning_msg = '';
    /**
     * @return String the Warning attributes that may repeated
     */
    public $warning_attributes = '';
    /**
     * @return String the Warning attributes with their values that may repeated
     */
    public $warning_attributes_with_values;
    /**
     * @return String the plate number followed by "-" followed by asset number
     */
    public $plate_number_auto_complete;
    /**
     * @return String the license number followed by "-" followed by asset number
     */
    public $radioactive_license_number_auto_complete;
    /**
     * @return String the segment of the parent tid of the asset before saving the asset
     */
    public $old_segment;
    /**
     * @return String the segment of the parent tid of the asset before saving the asset
     */
    public $tid_old_segment_name;
    /**
     * @return String the old segment of the asset before saving the asset
     */
    public $asset_old_segment;
    /**
     * @return String the old type of asset before saving the asset
     */
    public $old_type_of_asset;
    /**
     * @return String the old status of asset
     */
    public $old_status;
    /**
     * @return String the old status of asset
     */
    public $old_asset_status;

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

    /**
     * @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('invoice_id, type_of_asset_id, serial_number, asset_number, part_number, asset_status, segment_id, po_number', 'required'),
	    array('invoice_id, type_of_asset_id, segment_id', 'numerical', 'integerOnly' => true),
	    array('serial_number, asset_number, part_number, chassis_number', 'length', 'max' => 40),
	    array('description', 'length', 'max' => 200),
	    array('asset_status, plate_number, radioactive_license_number', 'length', 'max' => 10),
	    array('po_number', 'length', 'max' => 15),
	    array('asset_number', 'unique'),
	    array('tid_id', 'validateTIDIdentifier'),
	    array('serial_number,part_number,plate_number,chassis_number,radioactive_license_number', 'uniqueNotification'),
//            array('part_number', 'uniqueNotification'),
//            array('plate_number', 'uniqueNotification'),
//            array('chassis_number', 'uniqueNotification'),
//            array('radioactive_license_number', 'uniqueNotification'),
	    array('radioactive_license_number,radioactive_license_expiry_date', 'required', 'on' => 'radio'),
	    array('plate_number,chassis_number,vehicle_book_expiry_date', 'required', 'on' => 'vehicle'),
	    array('radioactive_license_number_auto_complete,plate_number_auto_complete,vehicle_book_expiry_date,radioactive_license_expiry_date,tid_id,old_tid_id', 'safe'),
	    // The following rule is used by search().
	    // @todo Please remove those attributes that should not be searched.
	    array('id, invoice_id, type_of_asset_id, serial_number, asset_number, part_number, description, asset_status, plate_number, chassis_number, radioactive_license_number, segment_id, po_number, created_by, created_date, last_edited_by, last_edited_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(
	    'invoice' => array(self::BELONGS_TO, 'Invoice', 'invoice_id'),
	    'segment' => array(self::BELONGS_TO, 'Segment', 'segment_id'),
	    'typeOfAsset' => array(self::BELONGS_TO, 'TypeOfAsset', 'type_of_asset_id'),
	    'assetStatuses' => array(self::HAS_MANY, 'AssetStatus', 'asset_id'),
	    'dahsboardAssets' => array(self::HAS_MANY, 'DahsboardAsset', 'asset_id'),
	);
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
	return array(
	    'tid_id' => Yii::t('default', 'TID No'),
	    'invoice_id' => Yii::t('default', 'Invoice Number'),
	    'type_of_asset_id' => Yii::t('default', 'Type of Asset'),
	    'serial_number' => Yii::t('default', 'Serial Number'),
	    'asset_number' => Yii::t('default', 'Asset Number'),
	    'part_number' => Yii::t('default', 'Part Number'),
	    'description' => Yii::t('default', 'Description'),
	    'asset_status' => Yii::t('default', 'Asset Status'),
	    'plate_number' => Yii::t('default', 'Plate Number'),
	    'chassis_number' => Yii::t('default', 'Chassis Number'),
	    'radioactive_license_number' => Yii::t('default', 'Radioactive License Number'),
	    'segment_id' => Yii::t('default', 'Segment'),
	    'po_number' => Yii::t('default', 'PO Number'),
	    'vehicle_book_expiry_date' => Yii::t('default', 'Vehicle Book Expiry Date'),
	    'radioactive_license_expiry_date' => Yii::t('default', 'Radioactive License Expiry Date'),
	    'plate_number_auto_complete' => Yii::t('default', 'Plate Number / Asset Number'),
	    'radioactive_license_number_auto_complete' => Yii::t('default', 'Radioactive License Number / Asset Number'),
	);
    }

    /**
     * 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() {
	// @todo Please modify the following code to remove attributes that should not be searched.

	$criteria = $this->ModelCriteria();

	$sort = new CSort();
	$sort->attributes = array(
	    'tid_id' => array(
		'asc' => 'tid.tid_no',
		'desc' => 'tid.tid_no 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() { // @todo Please modify the following code to remove attributes that should not be searched.
	$criteria = new CDbCriteria;

	//$criteria->compare('id',$this->id);

	$criteria->compare('invoice.number', $this->invoice_id, true);
	$criteria->compare('tid.tid_no', $this->tid_id, true);
	$criteria->compare('type_of_asset.name', $this->type_of_asset_id, true);
	$criteria->compare('serial_number', $this->serial_number, true);
	$criteria->compare('asset_number', $this->asset_number, true);
	$criteria->compare('part_number', $this->part_number, true);
	$criteria->compare('description', $this->description, true);
	$criteria->compare('asset_status', $this->asset_status, true);
	$criteria->compare('plate_number', $this->plate_number, true);
	$criteria->compare('chassis_number', $this->chassis_number, true);
	$criteria->compare('radioactive_license_number', $this->radioactive_license_number, true);
	$criteria->compare('segment.name', $this->segment_id, true);
	$criteria->compare('po_number', $this->po_number, true);

	$criteria->join = 'inner join invoice on invoice.id = t.invoice_id
			   inner join tid on tid.id = invoice.tid_id
			   inner join type_of_asset on type_of_asset.id = t.type_of_asset_id
			   inner join segment on segment.id = t.segment_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 Asset the static model class
     */
    public static function model($className = __CLASS__) {
	return parent::model($className);
    }

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

    /**
     * Returns the asset status options
     *
     * @return Array the asset status options
     */
    public static function getAssetStatusOptions() {
	return array(
	    'In Country' => Yii::t('default', 'In Country'),
	    'Exported' => Yii::t('default', 'Exported'),
	);
    }

    /**
     * The following validation is responsible for checking if the serial number,chassis number, plate number radio active liceinse number or part number are unique
     */
    public function uniqueNotification($attribute, $params) {
	$labels = $this->attributeLabels();
	if ($this->$attribute != '') {
	    $criteria = new CDbCriteria;
	    $criteria->select = $attribute;
	    $criteria->condition = $attribute . "='" . $this->$attribute . "'";
	    if (!$this->isNewRecord)
		$criteria->condition .= " and id !=" . $this->id;
	    $result = $this->commandBuilder->createFindCommand($this->tableName(), $criteria)->queryAll();
	    if ($result != null && count($result) > 0) {
		$this->warning_attributes_with_values .= ( $this->warning_attributes == '') ? strtolower($labels[$attribute]) . ' (' . $this->$attribute . ')' : ', ' . strtolower($labels[$attribute]) . ' (' . $this->$attribute . ')';
		$this->warning_attributes .= ( $this->warning_attributes == '') ? strtolower($labels[$attribute]) : ', ' . strtolower($labels[$attribute]);
		$this->warning_msg = Yii::t('default', 'The ' . $this->warning_attributes_with_values . ' has already been taken.') . "Do you want to use the same value for " . $this->warning_attributes . '?';
	    }
	}
    }

    /**
     * Check for warning msg attribute and set falsh msg if exist  
     */
    public function setWarningMsg() {
	if ($this->warning_msg != '') {
	    Yii::app()->user->setFlash('warning', $this->warning_msg);
	}
    }

    /**
     * Save Asset status information
     * @param Boolean $is_create_action if the request action is create or update
     *  @param string $error_msg the error msg if saving asset status failed.
     *  @param string $action the action to indicate that action is renew or not.
     *  @param string $plate_number the autocomplete value of the plate number with the asset number.
     *  @param string $radio_active_license_number the autocomplete value of the radioactive number with the asset number.
     * @return Boolean true if saving tid status successed , false otherwise
     */
    public function createUpdateStatus($is_create_action, &$error_msg, $action = null, $plate_number = null, $radio_active_license_number = null) {

	//if the action is renew so the system will calculate expiry date for the status before renewing
	if ($action == 'renew') {
	    $status = $this->getBeforeLastStatus();
	    if ($status != null) {
		$fine = Setting::getFine();
		if ($this->type_of_asset_id == Setting::getVehicleTypeOfAsset()) {
		    $days = TidansActiveRecord::dateDiff($status->vehicle_book_expiry_date, date("Y-m-d"));
		    $status->vehicle_book_expired_days = $days + 1;
		    $status->fine = $fine * ($days + 1);
		    if (!$status->save()) {
			$error_msg = CHtml::errorSummary($status);
			return false;
		    }
		} else
		if ($this->type_of_asset_id == Setting::getRadioActiveTypeOfAsset()) {
		    $days = TidansActiveRecord::dateDiff($status->radioactive_license_expiry_date, date("Y-m-d"));
		    $status->radioactive_license_expired_days = $days + 1;
		    $status->fine = $fine * ($days + 1);
		    if (!$status->save()) {
			$error_msg = CHtml::errorSummary($status);
			return false;
		    }
		}
	    }
	}
	$status = ($is_create_action) ? new AssetStatus() : $this->getLastStatus();
	if ($status == null)
	    $status = new AssetStatus();
	$status->radioactive_license_number_auto_complete = $radio_active_license_number;
	$status->plate_number_auto_complete = $plate_number;
	if ($this->type_of_asset_id == Setting::getVehicleTypeOfAsset()) {
	    $status->setScenario('vehicle');
	    $status->asset_id = $this->id;
	    $status->vehicle_book_expiry_date = $this->vehicle_book_expiry_date;
	    $status->vehicle_book_status = $status->setAssetStatus($this->vehicle_book_expiry_date);

	    if ($status->save())
		return true;
	    else {
		$error_msg = CHtml::errorSummary($status);
		return false;
	    }
	} else
	if ($this->type_of_asset_id == Setting::getRadioActiveTypeOfAsset()) {
	    $status->setScenario('radio');
	    $status->asset_id = $this->id;
	    $status->radioactive_license_expiry_date = $this->radioactive_license_expiry_date;
	    $status->radioactive_license_status = $status->setAssetStatus($this->radioactive_license_expiry_date);

	    if ($status->save())
		return true;
	    else {
		$error_msg = CHtml::errorSummary($status);
		return false;
	    }
	} else {
	    return true;
	}
    }

    /**
     * Get the last status of asset
     * @return AssetStatus the last asset status of the asset
     */
    public function getLastStatus() {
	$cr = new CDbCriteria();
	$cr->condition = 'asset_id = ' . $this->id;
	$cr->order = 'created_date desc';
	$cr->limit = 1;
	return AssetStatus::model()->find($cr);
    }

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

    /**
     * Set scenario of the model according to type of asset
     */
    public function setModelScenario() {
	if ($this->type_of_asset_id == Setting::getVehicleTypeOfAsset())
	    $this->setScenario('vehicle');
	else
	if ($this->type_of_asset_id == Setting::getRadioActiveTypeOfAsset())
	    $this->setScenario('radio');
    }

    /**
     * The Following function is responsible for return array of all vehicles by their plate numbers and asset numbers to display in drop dwon
     *
     * @return String[] array of (platenumber-assetnumber) of asset model .
     */
    public static function getPlateNumbersForDropDown() {
	$model = Asset::model();
	$criteria = new CDbCriteria;
	$criteria->select = 'id,plate_number,asset_number';
	if (Setting::getVehicleTypeOfAsset() != '')
	    $criteria->condition = 'type_of_asset_id = ' . Setting::getVehicleTypeOfAsset();
	$result = $model->commandBuilder->createFindCommand($model->tableName(), $criteria)->queryAll();
	$names = array();
	foreach ($result as $res) {
	    $names[$res['id']] = $res['plate_number'] . "-" . $res['asset_number'];
	}
	return $names;
    }

    /**
     * The Following function is responsible for return array of all radio actives by their License numbers and asset numbers to display in drop dwon
     *
     * @return String[] array of (Licensenumber-assetnumber) of asset model .
     */
    public static function getLicenseNumbersForDropDown() {
	$model = Asset::model();
	$criteria = new CDbCriteria;
	$criteria->select = 'id,asset_number,radioactive_license_number';
	if (Setting::getRadioActiveTypeOfAsset() != '')
	    $criteria->condition = 'type_of_asset_id = ' . Setting::getRadioActiveTypeOfAsset();
	$result = $model->commandBuilder->createFindCommand($model->tableName(), $criteria)->queryAll();
	$names = array();
	foreach ($result as $res) {
	    $names[$res['id']] = $res['radioactive_license_number'] . "-" . $res['asset_number'];
	}
	return $names;
    }

    /**
     * The Following function is responsible for return asset model by its asset number
     * @param string $error_msg the error msg if getting asset failed
     * @return Asset the asset model
     */
    public function getAssetByNumber(&$error_msg = null) {
	if ($this->type_of_asset_id == Setting::getVehicleTypeOfAsset()) {
	    $numbers = explode('-', $this->plate_number_auto_complete);
	    if ($numbers != null) {
		$asset_number = end($numbers);
		if ($asset_number == '') {
		    $this->setScenario('vehicle');
		    $error_msg = Yii::t('default', 'Please specify either Plate Number or Asset Number');
		    return $this;
		}
		$model = Asset::model()->findByAttributes(array('asset_number' => $asset_number));
		if ($model != null) {
		    $this->setScenario('vehicle');
		    $model->plate_number_auto_complete = $this->plate_number_auto_complete;
		    $model->vehicle_book_expiry_date = $this->vehicle_book_expiry_date;
		    return $model;
		} else {
		    $this->setScenario('vehicle');
		    return $this;
		}
	    }
	} else
	if ($this->type_of_asset_id == Setting::getRadioActiveTypeOfAsset()) {
	    $numbers = explode('-', $this->radioactive_license_number_auto_complete);
	    if ($numbers != null) {
		$asset_number = end($numbers);
		if ($asset_number == '') {
		    $this->setScenario('radio');
		    $error_msg = Yii::t('default', 'Please specify either Radioactive License Number or Asset Number');
		    return $this;
		}
		$model = Asset::model()->findByAttributes(array('asset_number' => $asset_number));
		if ($model != null) {
		    $this->setScenario('radio');
		    $model->radioactive_license_number_auto_complete = $this->radioactive_license_number_auto_complete;
		    $model->radioactive_license_expiry_date = $this->radioactive_license_expiry_date;
		    return $model;
		} else {
		    $this->setScenario('radio');
		    return $this;
		}
	    }
	}
	$error_msg = Yii::t('default', 'Type of Asset cannot be blank');
	return $this;
    }

    protected function afterSave() {
	if ($this->old_asset_status != $this->asset_status || $this->isNewRecord) {
	    $tid = ($this->tid_id != null && $this->tid_id != '') ? Tid::model()->findByAttributes(array('tid_no' => $this->tid_id)) : $this->invoice->tid;
	    if (!$tid->updateStatus($error_msg, $this->tid_old_segment_name)) {
		$this->addError('id', $error_msg);
		return false;
	    }
	}
	return parent::afterSave();
    }

    protected function afterFind() {
	$this->asset_old_segment = $this->segment_id;
	$this->old_type_of_asset = $this->type_of_asset_id;
	$this->old_asset_status = $this->asset_status;
	$this->old_tid_id = $this->invoice->tid->tid_no;
	$status = $this->getLastStatus();
	$this->old_status = ($status == null) ? null : (($this->type_of_asset_id == Setting::getVehicleTypeOfAsset()) ? $status->vehicle_book_status : $status->radioactive_license_status);
	return parent::afterFind();
    }

    protected function beforeSave() {
	$tid = $this->invoice->tid;
	if ($tid != null) {
	    $segment = $tid->getSegmentInfo();
	    $this->old_segment = ($segment != null) ? $segment['segment_id'] : null;
	    $this->tid_old_segment_name = ($segment != null) ? $segment['segment_name'] : null;
	}
	return parent::beforeSave();
    }

    protected function beforeDelete() {
	$tid = $this->invoice->tid;
	if ($tid != null) {
	    $segment = $tid->getSegmentInfo();
	    $this->old_segment = ($segment != null) ? $segment['segment_id'] : null;
	    $this->tid_old_segment_name = ($segment != null) ? $segment['segment_name'] : null;
	}
	return parent::beforeDelete();
    }

    protected function afterDelete() {
	if (!$this->invoice->tid->updateStatus($error_msg, $this->tid_old_segment_name)) {
	    $this->addError('id', $error_msg);
	    return false;
	}
	return parent::afterDelete();
    }

    /**
     * The Following function is responsible for update all tid status
     * @param string $error_msg the error msg if saving tid status failed.
     * @param Asset[] $expired_vehicle By reference variable to hold vehicles that are converted to expired
     * @param Asset[] $expired_radioactives By reference variable to hold radioactive that are converted to expired
     * @return Tid[] the expired tids in order to send notification to the users
     */
    public static function UpdateAllAssetStatuses(&$error_msg, &$expired_vehicle, &$expired_radioactives) {
	$expired_vehicle = array();
	$expired_radioactives = array();
	$fine = Setting::getFine();
	$vehicle_type_of_asset = Setting::getVehicleTypeOfAsset();
	$radio_active_type_of_asset = Setting::getRadioActiveTypeOfAsset();
	//if ($vehicle_type_of_asset != null && $vehicle_type_of_asset != '')
	$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 = "(expiry_date <='" . $grace_expire_date . "')";
	if ($vehicle_type_of_asset != null && $vehicle_type_of_asset != '' && $radio_active_type_of_asset != null && $radio_active_type_of_asset != '')
	    $criteria->condition .=" and (type_of_asset_id =" . $vehicle_type_of_asset;
	$criteria->condition .=" Or type_of_asset_id =" . $radio_active_type_of_asset . ')';
	$assets = VAsset::model()->findAll($criteria);
	if ($assets != null) {
	    foreach ($assets as $asset) {
		$asset_status = $asset->getLastStatus();
		if ($asset_status != null) {
		    if ($asset->type_of_asset_id == $vehicle_type_of_asset) {
			$status = $asset_status->setAssetStatus($asset->vehicle_book_expiry_date);
			if ($asset_status->vehicle_book_status != $status) {
			    $asset_status->vehicle_book_status = $status;
			    if ($status == 'Expired') {
				$days = TidansActiveRecord::dateDiff($asset->vehicle_book_expiry_date, date("Y-m-d"));
				$asset_status->vehicle_book_expired_days = $days + 1;
				$asset_status->fine = ($days + 1) * $fine;
			    }
			    if ($asset_status->save()) {
				if ($status == 'Expired' && $asset->asset_status != 'Exported') {
				    $expired_vehicle[] = $asset;
				}
			    } else
				$error_msg = CHtml::errorSummary($asset_status);
			}
			elseif ($asset_status->vehicle_book_status == 'Expired') {
			    $days = TidansActiveRecord::dateDiff($asset->vehicle_book_expiry_date, date("Y-m-d"));
			    $asset_status->vehicle_book_expired_days = $days + 1;
			    $asset_status->fine = ($days + 1) * $fine;
			    if (!$asset_status->save())
				$error_msg = CHtml::errorSummary($asset_status);
			}
		    }
		    else {
			if ($asset->type_of_asset_id == $radio_active_type_of_asset) {
			    $status = $asset_status->setAssetStatus($asset->radioactive_license_expiry_date);
			    if ($asset_status->radioactive_license_status != $status) {
				$asset_status->radioactive_license_status = $status;
				if ($status == 'Expired') {
				    $days = TidansActiveRecord::dateDiff($asset->radioactive_license_expiry_date, date("Y-m-d"));
				    $asset_status->radioactive_license_expired_days = $days + 1;
				    $asset_status->fine = ($days + 1) * $fine;
				}
				if ($asset_status->save()) {
				    if ($status == 'Expired' && $asset->asset_status != 'Exported') {
					$expired_radioactives[] = $asset;
				    }
				} else {
				    $error_msg = CHtml::errorSummary($asset_status);
				    Yii::log($error_msg, 'info', 'system.Scheduler.UpdateAssetStatus');
				}
			    } elseif ($asset_status->radioactive_license_status == 'Expired') {
				$days = TidansActiveRecord::dateDiff($asset->radioactive_license_expiry_date, date("Y-m-d"));
				$asset_status->radioactive_license_expired_days = $days + 1;
				$asset_status->fine = ($days + 1) * $fine;
				if (!$asset_status->save())
				    $error_msg = CHtml::errorSummary($asset_status);
			    }
			}
		    }
		}
	    }
	}
    }

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

	try {
	    Asset::UpdateAllAssetStatuses($error_msg, $expired_vehicle, $expired_radioactives);
	    $asset_message = '';
	    if ($error_msg == '') {
		if ($expired_vehicle != null)
		    foreach ($expired_vehicle as $asset) {
			$asset_message .= '<br/>The vehicle which has the plate number (' . $asset->plate_number . ')  is expired on (' . $asset->expiry_date . ')';
		    }

		if ($expired_radioactives != null)
		    foreach ($expired_radioactives as $asset) {
			$asset_message .='<br/>The radioactive source which has the license number (' . $asset->radioactive_license_number . ')  is expired on (' . $asset->expiry_date . ')';
		    }
		if ($expired_radioactives != null && $expired_vehicle != null)
		    TidansActiveRecord::SendNotification('TIDANS - Asset Expired', '<br/>' . $asset_message . '.<br/><br/> Please take the needed action.<br/><br/>');
	    } else {
		TIDANSMail::sendMail("TIDANS - Update Asset Status Error ",
				"An error has been occurred while updating asset 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.UpdateAssetStatus');
	    }
	    Yii::log('End Update Asset Status', 'info', 'system.Scheduler.UpdateAssetStatus');
	} catch (Exception $ex) {
	    TIDANSMail::sendMail("TIDANS - Update Asset Status Error ",
			    "An error has been occurred while updating asset status.<br/>
				    Please contact Flex Solutions support team to investigate this issue.",
			    Yii::app()->params["support_email"]);
	    Yii::log(' RollBack ', 'error', 'system.Scheduler.UpdateAssetStatus');
	    Yii::log($ex->__toString(), 'error', 'system.Scheduler.UpdateAssetStatus');
	    return;
	}
    }

    /**
     * The following validation is responsible for checking if tid identifier is in auto complete list or not
     */
    function validateTIDIdentifier($attribute, $params) {

	if (!Tid::checkTidInsideArrayOfTids($this->tid_id)) {
	    $this->addError('tid_id', Yii::t('default', "The TID (tid_no) is not valid, just start typing the TID No then select the required TID.", array('tid_no' => $this->tid_id)));
	}
    }

    /**
     * The following fuinction is responsible for checking if there are any vehicle asset created in the system
     * @param Integer $vehicle the id of vehicle type of asset
     */
    public static function isThereVehicleAssets($vehicle) {
	//$vehicle = Setting::getVehicleTypeOfAsset();
	if ($vehicle != null && $vehicle != '') {
	    $criteria = new CDbCriteria();
	    $criteria->limit = 1;
	    $criteria->condition = 'type_of_asset_id = ' . $vehicle;
	    $models = Asset::model()->find($criteria);
	    if ($models != null && count($models) > 0)
		return true;
	    return false;
	}
    }

    /**
     * The following fuinction is responsible for checking if there are any radioactive asset created in the system
     *  @param Integer $radioactive the id of radioactive type of asset
     */
    public static function isThereRadioactiveAssets($radioactive) {
	//$vehicle = Setting::getVehicleTypeOfAsset();
	if ($radioactive != null && $radioactive != '') {
	    $criteria = new CDbCriteria();
	    $criteria->limit = 1;
	    $criteria->condition = 'type_of_asset_id = ' . $radioactive;
	    $models = Asset::model()->find($criteria);
	    if ($models != null && count($models) > 0)
		return true;
	    return false;
	}
    }

}

