<?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 "summary_dashboard_per_segment".
 *
 * The followings are the available columns in table 'summary_dashboard_per_segment':
 * @property integer $id
 * @property string $date
 * @property integer $segment_id
 * @property string $segment_name
 * @property integer $total_tids
 * @property integer $valid_tids
 * @property integer $grace_period_tids
 * @property integer $expired_tids
 * @property double $expired_tids_fine
 * @property integer $expired_tids_days_count
 * @property integer $partially_exported_tids
 * @property integer $exported_tids
 * @property integer $permanent_declaration_tids
 * @property integer $total_vehicles
 * @property integer $valid_vehicles
 * @property integer $grace_vehicles
 * @property integer $expired_vehicles
 * @property integer $expired_vehicle_days_count
 * @property integer $total_radioactives
 * @property integer $valid_radioactives
 * @property integer $grace_radioactives
 * @property integer $expired_radioactives
 * @property integer $expired_radioactive_days_count
 * @property integer $total_assets
 * @property integer $is_total
 *
 * The followings are the available model relations:
 * @property AssetDetailedDashboard[] $assetDetailedDashboards
 * @property Segment $segment
 * @property SummaryDashboardPerSegmentAndRenewal[] $summaryDashboardPerSegmentAndRenewals
 * @property TidDetailedDashboard[] $tidDetailedDashboards
 */
class SummaryDashboardPerSegment extends TidansDashboardActiveRecord {

    public $section_drop_down;

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

    /**
     * @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('date, segment_name, total_tids, valid_tids, grace_period_tids, expired_tids, expired_tids_fine, expired_tids_days_count, partially_exported_tids, exported_tids, permanent_declaration_tids, total_vehicles, valid_vehicles, grace_vehicles, expired_vehicles, expired_vehicle_days_count, total_radioactives, valid_radioactives, grace_radioactives, expired_radioactives, expired_radioactive_days_count, total_assets, is_total', 'required'),
//	    array('segment_id, total_tids, valid_tids, grace_period_tids, expired_tids, expired_tids_days_count, partially_exported_tids, exported_tids, permanent_declaration_tids, total_vehicles, valid_vehicles, grace_vehicles, expired_vehicles, expired_vehicle_days_count, total_radioactives, valid_radioactives, grace_radioactives, expired_radioactives, expired_radioactive_days_count, total_assets, is_total', 'numerical', 'integerOnly' => true),
//	    array('expired_tids_fine', 'numerical'),
//	    array('segment_name', 'length', 'max' => 45),
//	    // The following rule is used by search().
//	    // @todo Please remove those attributes that should not be searched.
	    array('id, date, segment_id, segment_name, total_tids, valid_tids, grace_period_tids, expired_tids, expired_tids_fine, expired_tids_days_count, partially_exported_tids, exported_tids, permanent_declaration_tids, total_vehicles, valid_vehicles, grace_vehicles, expired_vehicles, expired_vehicle_days_count, total_radioactives, valid_radioactives, grace_radioactives, expired_radioactives, expired_radioactive_days_count, total_assets, is_total,section_drop_down', 'safe'),
	);
    }

    /**
     * @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(
	    'assetDetailedDashboards' => array(self::HAS_MANY, 'AssetDetailedDashboard', 'dashboard_per_segment_id'),
	    'segment' => array(self::BELONGS_TO, 'Segment', 'segment_id'),
	    'summaryDashboardPerSegmentAndRenewals' => array(self::HAS_MANY, 'SummaryDashboardPerSegmentAndRenewal', 'summary_dashboard_per_segment_id'),
	    'tidDetailedDashboards' => array(self::HAS_MANY, 'TidDetailedDashboard', 'summary_dashboard_per_segment_id'),
	);
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
	return array(
	    'id' => 'ID',
	    'date' => 'Date',
	    'segment_id' => 'Segment',
	    'segment_name' => 'Segment Name',
	    'total_tids' => 'Total Tids',
	    'valid_tids' => 'Valid Tids',
	    'grace_period_tids' => 'Grace Period Tids',
	    'expired_tids' => 'Expired Tids',
	    'expired_tids_fine' => 'Expired Tids Fine',
	    'expired_tids_days_count' => 'Expired Tids Days Count',
	    'partially_exported_tids' => 'Partially Exported Tids',
	    'exported_tids' => 'Exported Tids',
	    'permanent_declaration_tids' => 'Permanent Declaration Tids',
	    'total_vehicles' => 'Total Vehicles',
	    'valid_vehicles' => 'Valid Vehicles',
	    'grace_vehicles' => 'Grace Vehicles',
	    'expired_vehicles' => 'Expired Vehicles',
	    'expired_vehicle_days_count' => 'Expired Vehicle Days Count',
	    'total_radioactives' => 'Total Radioactives',
	    'valid_radioactives' => 'Valid Radioactives',
	    'grace_radioactives' => 'Grace Radioactives',
	    'expired_radioactives' => 'Expired Radioactives',
	    'expired_radioactive_days_count' => 'Expired Radioactive Days Count',
	    'total_assets' => 'Total Assets',
	    'is_total' => 'Is Total',
	);
    }

    /**
     * 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 = new CDbCriteria;

	$criteria->compare('id', $this->id);
	$criteria->compare('date', $this->date, true);
	$criteria->compare('segment_id', $this->segment_id);
	$criteria->compare('segment_name', $this->segment_name, true);
	$criteria->compare('total_tids', $this->total_tids);
	$criteria->compare('valid_tids', $this->valid_tids);
	$criteria->compare('grace_period_tids', $this->grace_period_tids);
	$criteria->compare('expired_tids', $this->expired_tids);
	$criteria->compare('expired_tids_fine', $this->expired_tids_fine);
	$criteria->compare('expired_tids_days_count', $this->expired_tids_days_count);
	$criteria->compare('partially_exported_tids', $this->partially_exported_tids);
	$criteria->compare('exported_tids', $this->exported_tids);
	$criteria->compare('permanent_declaration_tids', $this->permanent_declaration_tids);
	$criteria->compare('total_vehicles', $this->total_vehicles);
	$criteria->compare('valid_vehicles', $this->valid_vehicles);
	$criteria->compare('grace_vehicles', $this->grace_vehicles);
	$criteria->compare('expired_vehicles', $this->expired_vehicles);
	$criteria->compare('expired_vehicle_days_count', $this->expired_vehicle_days_count);
	$criteria->compare('total_radioactives', $this->total_radioactives);
	$criteria->compare('valid_radioactives', $this->valid_radioactives);
	$criteria->compare('grace_radioactives', $this->grace_radioactives);
	$criteria->compare('expired_radioactives', $this->expired_radioactives);
	$criteria->compare('expired_radioactive_days_count', $this->expired_radioactive_days_count);
	$criteria->compare('total_assets', $this->total_assets);
	$criteria->compare('is_total', $this->is_total);

	return new CActiveDataProvider($this, array(
	    'criteria' => $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 SummaryDashboardPerSegment the static model class
     */
    public static function model($className = __CLASS__) {
	return parent::model($className);
    }

    /**
     * Get the array of the row headers for the dashboard
     */
    public static function dashboardRowHeader() {
	return array(
	    'id' => 'ID',
	    'date' => 'Date',
	    'segment_id' => 'Segment',
	    'segment_name' => 'Segment Name',
	    'total_tids' => 'Total TIDs',
	    'valid_tids' => 'Valid TIDs',
	    'grace_period_tids' => 'Grace Period TIDs',
	    'expired_tids' => 'Expired TIDs',
	    'expired_tids_fine' => 'Expired TIDs Fine',
	    'expired_tids_days_count' => 'Expired TIDs Days Count',
	    'partially_exported_tids' => 'Partially Exported TIDs',
	    'exported_tids' => 'Exported TIDs',
	    'permanent_declaration_tids' => 'Permanent Declaration TIDs',
	    'total_vehicles' => 'Total Vehicles (Including Exported)',
	    'valid_vehicles' => 'Valid Vehicles',
	    'grace_vehicles' => 'Grace Vehicles',
	    'expired_vehicles' => 'Expired Vehicles (Non Exported)',
	    'expired_vehicle_days_count' => 'Expired Vehicle Days Count (Non Exported)',
	    'total_radioactives' => 'Total Radioactives (Including Exported)',
	    'valid_radioactives' => 'Valid Radioactives',
	    'grace_radioactives' => 'Grace Radioactives',
	    'expired_radioactives' => 'Expired Radioactives (Non Exported)',
	    'expired_radioactive_days_count' => 'Expired Radioactive Days Count (Non Exported)',
	    'total_assets' => 'Total Assets',
	    'is_total' => 'Is Total',
	);
    }

    /**
     * Get the array of the row urls for the dashboard
     */
    public static function dashboardRowsUrl() {
	return array(
	    'total_tids' => 'Total',
	    'valid_tids' => 'Valid',
	    'grace_period_tids' => 'Grace',
	    'expired_tids' => 'Expired',
	    'expired_tids_fine' => 'Fine',
	    'expired_tids_days_count' => 'Days Count',
	    'partially_exported_tids' => 'Partially Exported',
	    'exported_tids' => 'Exported',
	    'permanent_declaration_tids' => 'Permanent',
	    'total_vehicles' => 'Total',
	    'valid_vehicles' => 'Valid',
	    'grace_vehicles' => 'Grace',
	    'expired_vehicles' => 'Expired',
	    'expired_vehicle_days_count' => 'Days Count',
	    'total_radioactives' => 'Total',
	    'valid_radioactives' => 'Valid',
	    'grace_radioactives' => 'Grace',
	    'expired_radioactives' => 'Expired',
	    'expired_radioactive_days_count' => 'Days Count',
	    'total_assets' => 'Total',
	);
    }

    /**
     * Get the array of the row colors for the dashboard
     */
    public static function dashboardRowsColors() {
	return array(
	    'id' => 'ID',
	    'date' => 'Date',
	    'valid_vehicles' => 'rgb(208, 236, 176)',
	    'valid_radioactives' => 'rgb(208, 236, 176)',
	    'valid_tids' => 'rgb(208, 236, 176)',
	    'grace_vehicles' => 'rgb(250, 228, 158)',
	    'grace_period_tids' => 'rgb(250, 228, 158)',
	    'grace_radioactives' => 'rgb(250, 228, 158)',
	    'expired_tids' => 'rgb(248, 200, 200)',
	    'expired_tids_days_count' => 'rgb(248, 200, 200)',
	    'expired_tids_fine' => 'rgb(248, 200, 200)', // 'rgb(255, 175, 175)',
	    'expired_vehicles' => 'rgb(248, 200, 200)',
	    'expired_vehicle_days_count' => 'rgb(248, 200, 200)',
	    'expired_radioactives' => 'rgb(248, 200, 200)',
	    'expired_radioactive_days_count' => 'rgb(248, 200, 200)',
	    'expired_radio_active_days_count' => 'rgb(248, 200, 200)',
	    'partially_exported_tids' => 'rgb(222, 232, 224)',
	    'exported_tids' => 'rgb(193, 206, 221)',
	    'permanent_declaration_tids' => 'rgb(217, 217, 217)',
	    'total_tids' => 'rgb(159, 159, 159)',
	    'total_vehicles' => 'rgb(159, 159, 159)',
	    'total_radioactives' => 'rgb(159, 159, 159)',
	    'total_assets' => 'rgb(159, 159, 159)',
	);
    }

    /**
     * Get the array of the row colors for the dashboard export to excel
     * Excel color don't accept rgb format and must be written without the # character
     */
    public static function dashboardRowsColorsForExcel() {
	return array(
	    'id' => 'ID',
	    'date' => 'Date',
	    'valid_vehicles' => 'D0ECB0', //'rgb(208, 236, 176)',
	    'valid_radioactives' => 'D0ECB0',
	    'valid_tids' => 'D0ECB0', // 'rgb(208, 236, 176)',
	    'grace_vehicles' => 'FAE49E',
	    'grace_period_tids' => 'FAE49E',
	    'grace_radioactives' => 'FAE49E',
	    'expired_tids' => 'F8C8C8',
	    'expired_tids_days_count' => 'F8C8C8',
	    'expired_tids_fine' => 'F8C8C8', // 'rgb(255, 175, 175)',
	    'expired_vehicles' => 'F8C8C8',
	    'expired_vehicle_days_count' => 'F8C8C8',
	    'expired_radioactives' => 'F8C8C8',
	    'expired_radioactive_days_count' => 'F8C8C8',
	    'expired_radio_active_days_count' => 'F8C8C8',
	    'partially_exported_tids' => 'DEE8F2',
	    'exported_tids' => 'C1CEDD',
	    'permanent_declaration_tids' => 'D9D9D9',
	    'total_tids' => '9F9F9F',
	    'total_vehicles' => '9F9F9F',
	    'total_radioactives' => '9F9F9F',
	    'total_assets' => '9F9F9F',
	);
    }

    /**
     * This function called when get the data that will be displayed in the dashboard summary
     * @param Boolean $is_current indicate that the data displayed is the current or history
     * @param string[] $tids the information of the tids
     * @param string[] $vehicles the information of the vehicles
     * @param string[] $radioactives information of the radioactives
     * @param string[] $assets information of the total asset
     * @param string[] $segments array of segment names
     * @param string $date the date in which dashboard will be displayed
     */
    public static function getDataPerDate($is_current, &$tids, &$vehicles, &$radioactives, &$assets, &$segments, $date = null) {
	$update_process_date = Setting::getUpdateProcessDate();
	if ($update_process_date != null) {
	    if ($update_process_date != date("Y-m-d")) {
		TidansActiveRecord::UpdateTidAndAssetStatues();
	    }
	} else {
	    TidansActiveRecord::UpdateTidAndAssetStatues();
	}
	$criteria = new CDbCriteria;
	if ($is_current)
	    $criteria->condition = 'is_current = 1';
	else {
	    if ($date != null)
		if ($date == '(18 months history)') {
		    $now_minus_18 = date("Y-m-d", strtotime(date("Y-m-d", strtotime(date("Y-m-d"))) . " -18 month"));
		    $criteria->condition = "is_current = 0 and date is not null and date <'" . $now_minus_18 . "'";
		}
		else
		    $criteria->condition = "is_current = 0 and date = '" . $date . "'";
	}

	$model = SummaryDashboardPerSegment::model();
	$data = $model->commandBuilder->createFindCommand(
			$model->tableName(), $criteria)->queryAll();



	$tids = array();
	$vehicles = array();
	$radioactives = array();
	$others = array();
	$assets = array();
	$renewals = array();
	$out = array();

	if ($data != null) {
	    foreach ($data as $rowidx => $row) {
		foreach ($row as $colidx => $val) {
		    if ($colidx == 'segment_name') {
			$key = ($data[$rowidx]['segment_name'] == 'Total') ? 'Total' : (($data[$rowidx]['segment_name'] == 'Multi Segment') ? 'Multi Segment' : (($data[$rowidx]['segment_name'] == 'Non Segment') ? 'Non Segment' : $data[$rowidx]['segment_id']));

			$segments[$key] = $val;
		    }

		    $out[$colidx][$rowidx] = $val;
		    if (strpos($colidx, 'fine') != false) {
			$tids[$colidx][$out['segment_name'][$rowidx]] = '$' . number_format($out[$colidx][$rowidx], 0, '.', ',');
		    } elseif (strpos($colidx, 'tid') != false) {
			$tids[$colidx][$out['segment_name'][$rowidx]] = $out[$colidx][$rowidx];
		    } elseif (strpos($colidx, 'vehicle') != false) {
			$vehicles[$colidx][$out['segment_name'][$rowidx]] = $out[$colidx][$rowidx];
		    } elseif (strpos($colidx, 'radio') != false) {
			$radioactives[$colidx][$out['segment_name'][$rowidx]] = $out[$colidx][$rowidx];
		    } elseif (strpos($colidx, 'asset') != false) {
			$assets[$colidx][$out['segment_name'][$rowidx]] = $out[$colidx][$rowidx];
		    }
		}
	    }
	    //$segments = $out['segment_name'];
	}
//return the ids of the summmary dashboard records
	if ($out != null)
	    return $out;
    }

    /**
     * This function called when get the renewal data that will be displayed in the dashboard summary
     * @param Boolean $is_current indicate that the data displayed is the current or history
     * @param string[] $segments array of segment names
     * @param string[] $ids the ids of the summary dashboard table records to get their related renewal summary records
     * @param string[] $colors the color of renewal stages rows
     * @param string $rowHeades the rows headers for the renewal stage section
     * @param string $urlParams the url parameters that will be passed to the renewal stage records
     */
    public static function getRenewalInfos($is_current, $segments, $ids, &$colors, &$rowHeades, &$urlParams) {
	$renewals = array();
	//this is used to store the any id of summary dashboard id (here the first one) in order to use it to calculate the count of renewal stage for history
	$first_dashboard_summary_id = (is_array($ids) && count($ids) > 0) ? $ids[0] : '';
	$ids_string = '';
	if (is_array($ids)) {
	    foreach ($ids as $id)
		$ids_string .= $id . ',';
	    $ids_string = substr($ids_string, 0, -1);
	}

	if ($ids_string != '') {
	    $criteria = new CDbCriteria;
	    $criteria->select = "summary_dashboard_per_segment_id,if(isnull(renewal_stage.name),'total_renewal',renewal_stage.name)  as renewal_stage_name,tids_count";
	    $criteria->condition = 'summary_dashboard_per_segment_id in (' . $ids_string . ')';
	    $criteria->order = 'summary_dashboard_per_segment_id,renewal_stage.name';
	    $criteria->join = 'left join renewal_stage on renewal_stage.id = t.renewal_stage_id';
	    $model = SummaryDashboardPerSegmentAndRenewal::model();
	    $data = $model->commandBuilder->createFindCommand(
			    $model->tableName(), $criteria)->queryAll();
	    if ($data != null) {
		$renewal_counts = null;
		if ($is_current) {
		    $criteria = new CDbCriteria;
		    $criteria->select = "count(*)";
		    $criteria->condition = "status ='Active'";
		    $model = RenewalStage::model();
		    $renewal_counts = $model->commandBuilder->createFindCommand(
				    $model->tableName(), $criteria)->queryScalar();
		} else {
		    $criteria = new CDbCriteria;
		    $criteria->select = "count(renewal_stage_id)";
		    $criteria->condition = '`summary_dashboard_per_segment_id` =' . $first_dashboard_summary_id;
		    $model = SummaryDashboardPerSegmentAndRenewal::model();
		    $renewal_counts = $model->commandBuilder->createFindCommand(
				    $model->tableName(), $criteria)->queryScalar();
		}
		if ($renewal_counts == null)
		    $renewal_counts = 0;
		$index = 0;
		$helper_index = 0;
		foreach ($data as $rowidx => $row) {
		    $rowHeades[str_replace(' ', '', $data[$rowidx]['renewal_stage_name'])] = ($data[$rowidx]['renewal_stage_name'] != 'total_renewal') ? $data[$rowidx]['renewal_stage_name'] : 'Total Processing Stages';
		    $colors[str_replace(' ', '', $data[$rowidx]['renewal_stage_name'])] = ($data[$rowidx]['renewal_stage_name'] != 'total_renewal') ? 'rgb(250, 228, 158)' : 'rgb(159, 159, 159)';
		    $renewals[str_replace(' ', '', $data[$rowidx]['renewal_stage_name'])][$segments[$index]] = $data[$rowidx]['tids_count'];
		    $urlParams[str_replace(' ', '', $data[$rowidx]['renewal_stage_name'])] = ($data[$rowidx]['renewal_stage_name'] != 'total_renewal') ? $data[$rowidx]['renewal_stage_name'] : 'Total Renewal';
		    if ($helper_index == ($renewal_counts)) {
			$index++;
			$helper_index = -1;
		    }
		    $helper_index++;
		}
	    }
	}
	return $renewals;
    }

    public static function BuildDashboardRowQuery($segment, $id, &$error_msg, $is_current) {
	$segment_condition = '';
	$and = ($segment == 'Total') ? '' : ' and ';
	$where = ($segment == 'Total') ? '' : ' where ';
	if ($segment == 'Multi Segment')
	    $segment_condition = "segment_name like '%,%'";
	elseif ($segment == 'Non Segment')
	    $segment_condition = "segment_name is null";
	elseif ($segment != 'Total')
	    $segment_condition = "segment_name='" . $segment . "'";

	$grace_period = Setting::getGracePeriod();
	$condition = '';
	$valid_condition = '';
	if ($grace_period != null && $grace_period != '')
	    $condition = " and grace_period > 0 and grace_period <=" . $grace_period;
	if ($grace_period != null && $grace_period != '')
	    $valid_condition = " and grace_period > " . $grace_period;


	$query_string = '';
	$query_string .= ( $is_current) ? 'NULL,' : "'" . date("Y-m-t", strtotime("-1 month")) . "',";
	$query_string .= ( $segment == 'Total' || $segment == 'Multi Segment' || $segment == 'Non Segment') ? 'NULL,' : $id . ",";
	$query_string .= "'" . $segment . "',";
	$query_string .= "(select count(*) from v_tid" . $where . $segment_condition . "),";
	$query_string .= "(select count(*) from
	    where last_status_ti_status = 'Valid'" . $and . $segment_condition . "),";
	$query_string .= "(select count(*) from v_tid where last_status_ti_status = 'Grace'" . $and . $segment_condition . "),";
	$query_string .= "(select count(*) from v_tid where last_status_ti_status = 'Expired'" . $and . $segment_condition . "),";
	$query_string .= "(select IF( ISNULL( SUM( fine ) ) ,  '0', SUM( fine ) )  from v_tid where last_status_ti_status = 'Expired'" . $and . $segment_condition . "),";
	$query_string .= "(select IF( ISNULL( SUM( expiry_days ) ) ,  '0', SUM( expiry_days ) ) from v_tid where last_status_ti_status = 'Expired'" . $and . $segment_condition . "),";
	$query_string .= "(select count(*) from v_tid where last_status_ti_status = 'Partially Exported'" . $and . $segment_condition . "),";
	$query_string .= "(select count(*) from v_tid where last_status_ti_status = 'Exported'" . $and . $segment_condition . "),";
	$query_string .= "(select count(*) from v_tid where last_status_ti_status = 'Permanent'" . $and . $segment_condition . "),";
	$vehicles = Setting::getVehicleTypeOfAsset();
	if ($vehicles != null && $vehicles != '') {
	    $query_string .= ( $segment == 'Multi Segment' || $segment == 'Non Segment') ? '0,' : "(select count(*) from v_asset where type_of_asset_id = " . $vehicles . $and . $segment_condition . "),";
	    $query_string .= ( $segment == 'Multi Segment' || $segment == 'Non Segment') ? '0,' : "(select count(*) from v_asset where status = 'Valid' and type_of_asset_id = " . $vehicles . $and . $segment_condition . "),";
	    $query_string .= ( $segment == 'Multi Segment' || $segment == 'Non Segment') ? '0,' : "(select count(*) from v_asset where status = 'Grace' and type_of_asset_id = " . $vehicles . $and . $segment_condition . "),";
	    $query_string .= ( $segment == 'Multi Segment' || $segment == 'Non Segment') ? '0,' : "(select count(*) from v_asset where status = 'Expired' and type_of_asset_id = " . $vehicles . $and . $segment_condition . "),";
	    $query_string .= ( $segment == 'Multi Segment' || $segment == 'Non Segment') ? '0,' : "(select IF( ISNULL( SUM( expiry_days ) ) ,  '0', SUM( expiry_days ) ) from v_asset where status = 'Expired' and type_of_asset_id = " . $vehicles . $and . $segment_condition . "),";
	}
	$radioactives = Setting::getRadioActiveTypeOfAsset();
	if ($radioactives != null && $radioactives != '') {
	    $query_string .= ( $segment == 'Multi Segment' || $segment == 'Non Segment') ? '0,' : "(select count(*) from v_asset where type_of_asset_id = " . $radioactives . $and . $segment_condition . "),";
	    $query_string .= ( $segment == 'Multi Segment' || $segment == 'Non Segment') ? '0,' : "(select count(*) from v_asset where status = 'Valid' and type_of_asset_id = " . $radioactives . $and . $segment_condition . "),";
	    $query_string .= ( $segment == 'Multi Segment' || $segment == 'Non Segment') ? '0,' : "(select count(*) from v_asset where status = 'Grace' and type_of_asset_id = " . $radioactives . $and . $segment_condition . "),";
	    $query_string .= ( $segment == 'Multi Segment' || $segment == 'Non Segment') ? '0,' : "(select count(*) from v_asset where status = 'Expired' and type_of_asset_id = " . $radioactives . $and . $segment_condition . "),";
	    $query_string .= ( $segment == 'Multi Segment' || $segment == 'Non Segment') ? '0,' : "(select IF( ISNULL( SUM( expiry_days ) ) ,  '0', SUM( expiry_days ) ) from v_asset where status = 'Expired' and type_of_asset_id = " . $radioactives . $and . $segment_condition . "),";
	}
	$query_string .= ( $segment == 'Multi Segment' || $segment == 'Non Segment') ? '0,' : "(select count(*) from v_asset" . $where . $segment_condition . "),";
	$query_string .= ( ($segment == 'Total') ? '1,' : '0,');
	$query_string .= ( $is_current ? '1' : '0');




	return '(' . $query_string . ')';
    }

    /**
     * This function called when build history dashboard and it's called for each segment and then called for 'Total', 'Multi Segment' and 'Non Segment'<br>
     * it's also used when adding new segment to add a row for the new added segment to dashboard summary
     */
    public static function BuildDashboardRowModel($segment, $id, &$error_msg, $is_current) {
	//First we need to check the segment to know which row of the dashboard summary we are working with
	$segment_condition = '';
	$and = ($segment == 'Total') ? '' : ' and ';
	$where = ($segment == 'Total') ? '' : ' where ';
	if ($segment == 'Multi Segment')
	    $segment_condition = "segment_name like '%,%'";
	elseif ($segment == 'Non Segment')
	    $segment_condition = "segment_name is null";
	elseif ($segment != 'Total')
	    $segment_condition = "segment_name='" . $segment . "'";

	$grace_period = Setting::getGracePeriod();
	$condition = '';
	$valid_condition = '';
	if ($grace_period != null && $grace_period != '')
	    $condition = " and grace_period > 0 and grace_period <=" . $grace_period;
	if ($grace_period != null && $grace_period != '')
	    $valid_condition = " and grace_period > " . $grace_period;

	$model = new SummaryDashboardPerSegment();



	//=======This is the query that get the count and fine and expiry days for each statuses of tid according to the segment=========
	//if the segment or the system not have any tid for example with valid status...there will be no records to the valid status
	//so it's important to initilaize the each value of tid to set values for statuses that not returned by the query
	$tid_model = VTidDashboard::model();
	$cr1 = new CDbCriteria();
	$cr1->select = "count(*) as count,sum(expiry_days) as expiry_days,ROUND(sum(expiry_days) * (select value from setting where name = 'tid_daily_fine')) as fine, last_status_ti_status";
	$cr1->condition = $segment_condition;
	$cr1->group = 'last_status_ti_status';

	$tid_data = $tid_model->commandBuilder->createFindCommand(
			$tid_model->tableName(), $cr1)->queryAll();


	//Initliaze each value of the tid
	$model->total_tids = 0;
	$model->valid_tids = 0;
	$model->grace_period_tids = 0;
	$model->expired_tids = 0;
	$model->partially_exported_tids = 0;
	$model->exported_tids = 0;
	$model->permanent_declaration_tids = 0;
	$model->expired_tids_fine = 0;
	$model->expired_tids_days_count = 0;
	//=======end of query=======================


	$total_tids = 0;
	if ($tid_data != null)
	    foreach ($tid_data as $data) {
		if ($data['last_status_ti_status'] == 'Valid')
		    $model->valid_tids = $data['count'];
		if ($data['last_status_ti_status'] == 'Grace')
		    $model->grace_period_tids = $data['count'];
		if ($data['last_status_ti_status'] == 'Expired') {
		    $model->expired_tids = $data['count'];
		    $model->expired_tids_fine = $data['fine'];
		    $model->expired_tids_days_count = $data['expiry_days'];
		}
		if ($data['last_status_ti_status'] == 'Partially Exported')
		    $model->partially_exported_tids = $data['count'];
		if ($data['last_status_ti_status'] == 'Exported')
		    $model->exported_tids = $data['count'];
		if ($data['last_status_ti_status'] == 'Permanent')
		    $model->permanent_declaration_tids = $data['count'];
		$total_tids += $data['count'];
	    }

	$model->total_tids = $total_tids;

	//=======This is the query that get the count and fine and expiry days for each asset according to the segment=========
	//if the segment or the system not have any asset for example with valid status...there will be no records to the valid status
	//so it's important to initilaize the each value of assets to set values for statuses that not returned by the query
	$asset_model = VAssetDashboard::model();
	$cr1 = new CDbCriteria();
	$cr1->select = 'count(*) as count,status,type_of_asset_id';
	$cr1->condition = "status != 'Expired'" . $and . $segment_condition;
	$cr1->group = 'status,type_of_asset_id';

	$asset_data = $asset_model->commandBuilder->createFindCommand(
			$asset_model->tableName(), $cr1)->queryAll();



	$cr2 = new CDbCriteria();
	$cr2->select = 'count(*) as count,status,type_of_asset_id,asset_status,sum(expiry_days) as expiry_days';
	$cr2->condition = "status = 'Expired'" . $and . $segment_condition;
	$cr2->group = 'status,type_of_asset_id,asset_status';

	$expired_asset_data = $asset_model->commandBuilder->createFindCommand(
			$asset_model->tableName(), $cr2)->queryAll();


	$model->total_vehicles = 0;
	$model->valid_vehicles = 0;
	$model->grace_vehicles = 0;
	$model->expired_vehicles = 0;

	$model->total_radioactives = 0;
	$model->valid_radioactives = 0;
	$model->grace_radioactives = 0;
	$model->expired_radioactives = 0;

	$vehicles = Setting::getVehicleTypeOfAsset();
	$radioactives = Setting::getRadioActiveTypeOfAsset();
	$total_vehicles = 0;
	$total_assets = 0;
	$total_radioactives = 0;
	if ($asset_data != null)
	    foreach ($asset_data as $data) {
		if ($data['type_of_asset_id'] == $vehicles) {
		    if ($data['status'] == 'Valid')
			$model->valid_vehicles = $data['count'];
		    if ($data['status'] == 'Grace')
			$model->grace_vehicles = $data['count'];
		    $total_vehicles += $data['count'];
		} else
		if ($data['type_of_asset_id'] == $radioactives) {
		    if ($data['status'] == 'Valid')
			$model->valid_radioactives = $data['count'];
		    if ($data['status'] == 'Grace')
			$model->grace_radioactives = $data['count'];
		    $total_radioactives += $data['count'];
		}
		$total_assets += $data['count'];
	    }

	if ($expired_asset_data != null)
	    foreach ($expired_asset_data as $data) {
		if ($data['type_of_asset_id'] == $vehicles) {
		    if ($data['status'] == 'Expired' && $data['asset_status'] != 'Exported') {
			$model->expired_vehicles = $data['count'];
			$model->expired_vehicle_days_count = $data['expiry_days'];
		    }
		    $total_vehicles += $data['count'];
		} else
		if ($data['type_of_asset_id'] == $radioactives) {
		    if ($data['status'] == 'Expired' && $data['asset_status'] != 'Exported') {
			$model->expired_radioactives = $data['count'];
			$model->expired_radioactive_days_count = $data['expiry_days'];
		    }
		    $total_radioactives += $data['count'];
		}
		$total_assets += $data['count'];
	    }

	$model->total_vehicles = $total_vehicles;
	$model->total_radioactives = $total_radioactives;
	$model->total_assets = $total_assets;


	$model->date = ($is_current) ? 'NULL' : "'" . date("Y-m-t", strtotime("-1 month")) . "'";
	$model->segment_id = ( $segment == 'Total' || $segment == 'Multi Segment' || $segment == 'Non Segment') ? 'NULL' : $id;
	$model->segment_name = "'" . $segment . "'";
	$model->is_total = ( ($segment == 'Total') ? '1' : '0');
	$model->is_current = ($is_current ? '1' : '0');

	if ($model->save()) {
	    if (!SummaryDashboardPerSegmentAndRenewal::createRenewalModels($model->id, $error_msg, $segment_condition))
		return false;

	    return true;
	}

	$error_msg = CHtml::errorSummary($model);
	return false;
    }

    /**
     * This function called to update all current dashboard records to fix them in case any error happened
     * it's called inside automatic process "UpdateTIDandAssetStatus
     */
    public static function UpdateAllDashboardModels(&$error_msg) {
	try {

	    $segment_names = Segment::getNamesForDropDown();
	    $transaction = Yii::app()->db->beginTransaction();
	    //update first Total records
	    $model = SummaryDashboardPerSegment::model()->findByAttributes(array('is_current' => '1', 'is_total' => '1'));
	    if (!SummaryDashboardPerSegment::UpdateDashboardRowModel($model, 'Total', null, $error_msg, true)) {
		$transaction->rollback();
		return false;
	    }
	    //update each segment
	    if ($segment_names != null) {
		foreach ($segment_names as $id => $segment_name) {
		    $model = SummaryDashboardPerSegment::model()->findByAttributes(array('is_current' => '1', 'segment_name' => $segment_name));
		    if (!SummaryDashboardPerSegment::UpdateDashboardRowModel($model, $segment_name, $id, $error_msg, true)) {
			$transaction->rollback();
			return false;
		    }
		}
	    }
	    //update Multi segment records
	    $model = SummaryDashboardPerSegment::model()->findByAttributes(array('is_current' => '1', 'segment_name' => 'Multi Segment'));
	    if (!SummaryDashboardPerSegment::UpdateDashboardRowModel($model, 'Multi Segment', null, $error_msg, true)) {
		$transaction->rollback();
		return false;
	    }
	    //update Non segment records
	    $model = SummaryDashboardPerSegment::model()->findByAttributes(array('is_current' => '1', 'segment_name' => 'Non Segment'));
	    if (!SummaryDashboardPerSegment::UpdateDashboardRowModel($model, 'Non Segment', null, $error_msg, true)) {
		$transaction->rollback();
		return false;
	    }

	    $transaction->commit();
	    return true;
	} catch (Exception $ex) {
	    $error_msg = $ex->__toString();
	    return false;
	}
    }

    /**
     * This function called to update one current dashboard record according to segment name or segment id to fix it in case any error happened
     * fixing means recalculate the current dashbaord and then updating the values of dashboard summary
     */
    public static function UpdateDashboardRowModel($model, $segment, $id, &$error_msg, $is_current) {
	//First we need to check the segment to know which row of the dashboard summary we are working with
	if ($model != null) {
	    $segment_condition = '';
	    $and = ($segment == 'Total') ? '' : ' and ';
	    $where = ($segment == 'Total') ? '' : ' where ';
	    if ($segment == 'Multi Segment')
		$segment_condition = "segment_name like '%,%'";
	    elseif ($segment == 'Non Segment')
		$segment_condition = "segment_name is null";
	    elseif ($segment != 'Total')
		$segment_condition = "segment_name='" . $segment . "'";

	    $grace_period = Setting::getGracePeriod();
	    $condition = '';
	    $valid_condition = '';
	    if ($grace_period != null && $grace_period != '')
		$condition = " and grace_period > 0 and grace_period <=" . $grace_period;
	    if ($grace_period != null && $grace_period != '')
		$valid_condition = " and grace_period > " . $grace_period;



	    //=======This is the query that get the count and fine and expiry days for each statuses of tid according to the segment=========
	    //if the segment or the system not have any tid for example with valid status...there will be no records to the valid status
	    //so it's important to initilaize the each value of tid to set values for statuses that not returned by the query
	    $tid_model = VTidDashboard::model();
	    $cr1 = new CDbCriteria();
	    $cr1->select = "count(*) as count,sum(expiry_days) as expiry_days,ROUND(sum(expiry_days) * (select value from setting where name = 'tid_daily_fine')) as fine, last_status_ti_status";
	    $cr1->condition = $segment_condition;
	    $cr1->group = 'last_status_ti_status';

	    $tid_data = $tid_model->commandBuilder->createFindCommand(
			    $tid_model->tableName(), $cr1)->queryAll();


	    //Initliaze each value of the tid
	    $model->total_tids = 0;
	    $model->valid_tids = 0;
	    $model->grace_period_tids = 0;
	    $model->expired_tids = 0;
	    $model->partially_exported_tids = 0;
	    $model->exported_tids = 0;
	    $model->permanent_declaration_tids = 0;
	    $model->expired_tids_fine = 0;
	    $model->expired_tids_days_count = 0;
	    //=======end of query=======================


	    $total_tids = 0;
	    if ($tid_data != null)
		foreach ($tid_data as $data) {
		    if ($data['last_status_ti_status'] == 'Valid')
			$model->valid_tids = $data['count'];
		    if ($data['last_status_ti_status'] == 'Grace')
			$model->grace_period_tids = $data['count'];
		    if ($data['last_status_ti_status'] == 'Expired') {
			$model->expired_tids = $data['count'];
			$model->expired_tids_fine = $data['fine'];
			$model->expired_tids_days_count = $data['expiry_days'];
		    }
		    if ($data['last_status_ti_status'] == 'Partially Exported')
			$model->partially_exported_tids = $data['count'];
		    if ($data['last_status_ti_status'] == 'Exported')
			$model->exported_tids = $data['count'];
		    if ($data['last_status_ti_status'] == 'Permanent')
			$model->permanent_declaration_tids = $data['count'];
		    $total_tids += $data['count'];
		}

	    $model->total_tids = $total_tids;

	    //=======This is the query that get the count and fine and expiry days for each asset according to the segment=========
	    //if the segment or the system not have any asset for example with valid status...there will be no records to the valid status
	    //so it's important to initilaize the each value of assets to set values for statuses that not returned by the query
	    $asset_model = VAssetDashboard::model();
	    $cr1 = new CDbCriteria();
	    $cr1->select = 'count(*) as count,status,type_of_asset_id';
	    $cr1->condition = "status != 'Expired'" . $and . $segment_condition;
	    $cr1->group = 'status,type_of_asset_id';

	    $asset_data = $asset_model->commandBuilder->createFindCommand(
			    $asset_model->tableName(), $cr1)->queryAll();



	    $cr2 = new CDbCriteria();
	    $cr2->select = 'count(*) as count,status,type_of_asset_id,asset_status,sum(expiry_days) as expiry_days';
	    $cr2->condition = "status = 'Expired'" . $and . $segment_condition;
	    $cr2->group = 'status,type_of_asset_id,asset_status';

	    $expired_asset_data = $asset_model->commandBuilder->createFindCommand(
			    $asset_model->tableName(), $cr2)->queryAll();


	    $model->total_vehicles = 0;
	    $model->valid_vehicles = 0;
	    $model->grace_vehicles = 0;
	    $model->expired_vehicles = 0;

	    $model->total_radioactives = 0;
	    $model->valid_radioactives = 0;
	    $model->grace_radioactives = 0;
	    $model->expired_radioactives = 0;

	    $vehicles = Setting::getVehicleTypeOfAsset();
	    $radioactives = Setting::getRadioActiveTypeOfAsset();
	    $total_vehicles = 0;
	    $total_assets = 0;
	    $total_radioactives = 0;
	    if ($asset_data != null)
		foreach ($asset_data as $data) {
		    if ($data['type_of_asset_id'] == $vehicles) {
			if ($data['status'] == 'Valid')
			    $model->valid_vehicles = $data['count'];
			if ($data['status'] == 'Grace')
			    $model->grace_vehicles = $data['count'];
			$total_vehicles += $data['count'];
		    } else
		    if ($data['type_of_asset_id'] == $radioactives) {
			if ($data['status'] == 'Valid')
			    $model->valid_radioactives = $data['count'];
			if ($data['status'] == 'Grace')
			    $model->grace_radioactives = $data['count'];
			$total_radioactives += $data['count'];
		    }
		    $total_assets += $data['count'];
		}

	    if ($expired_asset_data != null)
		foreach ($expired_asset_data as $data) {
		    if ($data['type_of_asset_id'] == $vehicles) {
			if ($data['status'] == 'Expired' && $data['asset_status'] != 'Exported') {
			    $model->expired_vehicles = $data['count'];
			    $model->expired_vehicle_days_count = $data['expiry_days'];
			}
			$total_vehicles += $data['count'];
		    } else
		    if ($data['type_of_asset_id'] == $radioactives) {
			if ($data['status'] == 'Expired' && $data['asset_status'] != 'Exported') {
			    $model->expired_radioactives = $data['count'];
			    $model->expired_radioactive_days_count = $data['expiry_days'];
			}
			$total_radioactives += $data['count'];
		    }
		    $total_assets += $data['count'];
		}

	    $model->total_vehicles = $total_vehicles;
	    $model->total_radioactives = $total_radioactives;
	    $model->total_assets = $total_assets;


	    $model->date = ($is_current) ? NULL : "'" . date("Y-m-t", strtotime("-1 month")) . "'";
	    $model->segment_id = ( $segment == 'Total' || $segment == 'Multi Segment' || $segment == 'Non Segment') ? NULL : $id;
	    $model->segment_name = $segment;
	    $model->is_total = ( ($segment == 'Total') ? '1' : '0');
	    $model->is_current = ($is_current ? '1' : '0');

	    if ($model->save()) {
		if (!SummaryDashboardPerSegmentAndRenewal::updateRenewalModels($model->id, $error_msg, $segment_condition))
		    return false;

		return true;
	    }

	    $error_msg = CHtml::errorSummary($model);
	    return false;
	}
	return true;
    }

    public function validate($attributes = null, $clearErrors = true) {
	return true;
	;
    }

    /**
     * Get all current dashboard records and filter them according to attributes    
     */
    public static function getCurrentDashboardRecords($attributes = null) {
	if ($attributes != null)
	    $dashboard_summry_records = SummaryDashboardPerSegment::model()->findAllByAttributes(array($attributes));
	else
	    $dashboard_summry_records = SummaryDashboardPerSegment::model()->findAllByAttributes(array('is_current' => '1'));
	return ($dashboard_summry_records == null) ? null : $dashboard_summry_records;
    }

    /**
     * Get all current dashboard records and filter them according to attributes
     */
    public static function getCurrentDashboardIDsAsString() {
	$result = array();
	$model = SummaryDashboardPerSegment::model();
	$criteria = new CDbCriteria;
	$criteria->select = 'id';
	$criteria->condition = 'is_current = 1';
	$result = $model->commandBuilder->createFindCommand($model->tableName(), $criteria)->queryColumn();
	return implode(',', $result);
    }

    /**
     * Remove current summary dashboaord reocrd according to segment ID
     * @param integer $id the ID of the segment to delete its records
     * return -1 if successfully delete dashboard records, otherwise the id of the record that cannot be deleted
     */
    public static function removeSummaryDashboardRecordBySegmentIDs($segment_id, $is_current = null) {
	$attributes = array('segment_id' => $segment_id);
	if ($is_current != null && $is_current == true)
	    $attributes = array('segment_id' => $segment_id, 'is_current' => '1');
	//get all records of summary dashboard for the specified segment
	$dashboard_summry_records = SummaryDashboardPerSegment::model()->findAllByAttributes($attributes);
	if ($dashboard_summry_records != null) {
	    foreach ($dashboard_summry_records as $dashboard_summry_record) {
		if (!$dashboard_summry_record->delete()) {
		    return $dashboard_summry_record->id;
		}
	    }
	}

	if ($is_current == null) {
	    //get all records of tid detailed dashboard for the specified segment
	    $tid_dashboard_detail_records = TidDetailedDashboard::model()->findAllByAttributes($attributes);
	    //get all records of asset detailed dashboard for the specified segment
	    $asset_dashboard_detail_records = AssetDetailedDashboard::model()->findAllByAttributes($attributes);

	    if ($tid_dashboard_detail_records != null) {
		foreach ($tid_dashboard_detail_records as $tid_dashboard_detail_record) {
		    if (!$tid_dashboard_detail_record->delete()) {
			return $tid_dashboard_detail_record->id;
		    }
		}
	    }
	    if ($asset_dashboard_detail_records != null) {
		foreach ($asset_dashboard_detail_records as $asset_dashboard_detail_record) {
		    if (!$asset_dashboard_detail_record->delete()) {
			return $asset_dashboard_detail_record->id;
		    }
		}
	    }
	}
	return -1;
    }

    /**
     * This function is called to modify specific dashboard summary record when the user modify tid information like adding new tid, renew tid, delete tid, update tid status, delete tid status
     * @param TidansActiveRecord $model the model that we need to modify
     * @param Tid $tid tid model that is added , modified , or deleted
     * @param TidStatus $tid_status the status of tid that is added (in renew case), updated or deleted
     * @param String $error_msg the error msg if any error occured
     * @param String $action if null that means that the tid is added or modified, if 'delete' that means that either tid is deleted or its status
     * @param Boolean $delete_tid if null that means that the tid is added or modified, otherwise if its value true then the tid is deleted and if its value is false then tid status is deleted
     *  return true if successfully update dashboard records, otherwise false
     */
    public static function UpdateCurrentDashboardRecordsByTID($model, $tid, $tid_status, &$error_msg, $action =null, $delete_tid = null) {
	if ($model != null) {
	    $segment = $model->segment_name;
	    $and = ($segment == 'Total') ? '' : ' and ';
	    $where = ($segment == 'Total') ? '' : ' where ';
	    $segment_condition = '';
	    if ($segment == 'Multi Segment')
		$segment_condition = "segment_name like '%,%'";
	    elseif ($segment == 'Non Segment')
		$segment_condition = "segment_name is null";
	    elseif ($segment != 'Total')
		$segment_condition = "segment_name='" . $segment . "'";


	    //if Tid is added or modified
	    if ($action != 'delete') {
		//if the user add new tid
		if ($tid->getIsNewRecord()) {
		    $model->total_tids = $model->total_tids + 1;
		} else {
		    //it's called when the user update tid status, because when update tid information there is no effect on dashboard,
		    //but when the user update tid status , the dashboard will be updated according to tid status
		    $old_status = ($tid_status != null) ? $tid_status->old_ti_status : null;
		    $new_status = ($tid_status != null) ? $tid_status->ti_status : null;
		    if ($new_status != $old_status) {
			$tid_data = null;
			//if any of new status or old status is Expired, then we need to recalculate expiry days and fine
			if ($new_status == 'Expired' || $old_status == 'Expired') {
			    $tid_model = VTidDashboard::model();
			    $cr1 = new CDbCriteria();
			    $cr1->select = "sum(expiry_days) as expiry_days,ROUND(sum(expiry_days) * (select value from setting where name = 'tid_daily_fine')) as fine, last_status_ti_status";
			    $extra_condition = ($segment_condition != '') ? " and last_status_ti_status='Expired'" : "last_status_ti_status='Expired'";
			    $cr1->condition = $segment_condition . $extra_condition;
			    $cr1->group = 'last_status_ti_status';
			    $tid_data = $tid_model->commandBuilder->createFindCommand(
					    $tid_model->tableName(), $cr1)->queryAll();
			}
			$model->total_tids = $model->total_tids;
			//if the new status is Valid then we need to increase valid tids by one..but if the old status is valid we need to decrease valid tids by one...same thing applied to all statuses
			$model->valid_tids = ($new_status == 'Valid') ? $model->valid_tids + 1 : (($old_status == 'Valid') ? (($model->valid_tids > 0) ? $model->valid_tids - 1 : 0) : $model->valid_tids);
			$model->grace_period_tids = ($new_status == 'Grace') ? $model->grace_period_tids + 1 : (($old_status == 'Grace') ? (($model->grace_period_tids > 0) ? $model->grace_period_tids - 1 : 0) : $model->grace_period_tids);
			$model->expired_tids = ($new_status == 'Expired') ? $model->expired_tids + 1 : (($old_status == 'Expired') ? (($model->expired_tids > 0) ? $model->expired_tids - 1 : 0) : $model->expired_tids);
			//if there are any expired tid..then tid_data will not be empty..and if tid_data is empty and the old status is Expired ..that mean there is no expired tids so we need to give fine and expiry days zero values
			$model->expired_tids_fine = ($tid_data == null) ? ($old_status != 'Expired' ? $model->expired_tids_fine : 0) : $tid_data[0]['fine']; //
			$model->expired_tids_days_count = ($tid_data == null) ? ($old_status != 'Expired' ? $model->expired_tids_days_count : 0) : $tid_data[0]['expiry_days'];
			$model->partially_exported_tids = ($new_status == 'Partially Exported') ? $model->partially_exported_tids + 1 : (($old_status == 'Partially Exported') ? ($model->partially_exported_tids > 0 ? $model->partially_exported_tids - 1 : 0) : $model->partially_exported_tids);
			$model->exported_tids = ($new_status == 'Exported') ? $model->exported_tids + 1 : (($old_status == 'Exported') ? ($model->exported_tids > 0 ? $model->exported_tids - 1 : 0) : $model->exported_tids);
			$model->permanent_declaration_tids = ($new_status == 'Permanent') ? $model->permanent_declaration_tids + 1 : (($old_status == 'Permanent') ? ($model->permanent_declaration_tids > 0 ? $model->permanent_declaration_tids - 1 : 0) : $model->permanent_declaration_tids);
		    } else
		    //here if any update occured and the status is Expired maybe the expiry days and fine will be increased (renew tid to expired or update expiry date)
		    if ($new_status == 'Expired' || $old_status == 'Expired') {
			$tid_model = VTidDashboard::model();
			$cr1 = new CDbCriteria();
			$cr1->select = "sum(expiry_days) as expiry_days,ROUND(sum(expiry_days) * (select value from setting where name = 'tid_daily_fine')) as fine, last_status_ti_status";
			$extra_condition = ($segment_condition != '') ? " and last_status_ti_status='Expired'" : "last_status_ti_status='Expired'";
			$cr1->condition = $segment_condition . $extra_condition;
			$cr1->group = 'last_status_ti_status';
			$tid_data = $tid_model->commandBuilder->createFindCommand(
					$tid_model->tableName(), $cr1)->queryAll();

			$model->expired_tids_fine = ($tid_data == null) ? $model->expired_tids_fine : $tid_data[0]['fine'];
			$model->expired_tids_days_count = ($tid_data == null) ? $model->expired_tids_days_count : $tid_data[0]['expiry_days'];
		    }
		}
	    } else {

		//if the user delete tid
		if ($delete_tid) {
		    $tid_data = null;
		    $status = ($tid_status != null) ? $tid_status->ti_status : null;
		    if ($status == 'Expired') {
			$tid_model = VTidDashboard::model();
			$cr1 = new CDbCriteria();
			$cr1->select = "sum(expiry_days) as expiry_days,ROUND(sum(expiry_days) * (select value from setting where name = 'tid_daily_fine')) as fine, last_status_ti_status";
			$extra_condition = ($segment_condition != '') ? " and last_status_ti_status='Expired'" : "last_status_ti_status='Expired'";
			$cr1->condition = $segment_condition . $extra_condition;
			$cr1->group = 'last_status_ti_status';
			$tid_data = $tid_model->commandBuilder->createFindCommand(
					$tid_model->tableName(), $cr1)->queryAll();
		    }
		    $model->total_tids = $model->total_tids - 1;
		    $model->valid_tids = ($status == 'Valid') ? $model->valid_tids - 1 : $model->valid_tids;
		    $model->grace_period_tids = ($status == 'Grace') ? $model->grace_period_tids - 1 : $model->grace_period_tids;
		    $model->expired_tids = ($status == 'Expired') ? $model->expired_tids - 1 : $model->expired_tids;
		    $model->expired_tids_fine = ($tid_data == null) ? ($status != 'Expired' ? $model->expired_tids_fine : 0) : $tid_data[0]['fine']; //
		    $model->expired_tids_days_count = ($tid_data == null) ? ($status != 'Expired' ? $model->expired_tids_days_count : 0) : $tid_data[0]['expiry_days']; //
		    $model->partially_exported_tids = ($status == 'Partially Exported') ? $model->partially_exported_tids - 1 : $model->partially_exported_tids;
		    $model->exported_tids = ($status == 'Exported') ? $model->exported_tids - 1 : $model->exported_tids;
		    $model->permanent_declaration_tids = ($status == 'Permanent') ? $model->permanent_declaration_tids - 1 : $model->permanent_declaration_tids;
		} else {
		    //if the user delete tid status
		    $status = $tid->getLastStatus();
		    $old_status = ($tid_status != null) ? $tid_status->ti_status : null;
		    $new_status = ($status != null) ? $status->ti_status : null;
		    $tid_data = null;
		    if ($old_status == 'Expired' || $new_status == 'Expired') {
			$tid_model = VTidDashboard::model();
			$cr1 = new CDbCriteria();
			$cr1->select = "sum(expiry_days) as expiry_days,ROUND(sum(expiry_days) * (select value from setting where name = 'tid_daily_fine')) as fine, last_status_ti_status";
			$extra_condition = ($segment_condition != '') ? " and last_status_ti_status='Expired'" : "last_status_ti_status='Expired'";
			$cr1->condition = $segment_condition . $extra_condition;
			$cr1->group = 'last_status_ti_status';
			$tid_data = $tid_model->commandBuilder->createFindCommand(
					$tid_model->tableName(), $cr1)->queryAll();
		    }
		    if ($new_status != $old_status) {
			$model->total_tids = $model->total_tids;
			$model->valid_tids = ($new_status == 'Valid') ? $model->valid_tids + 1 : (($old_status == 'Valid') ? $model->valid_tids - 1 : $model->valid_tids);
			$model->grace_period_tids = ($new_status == 'Grace') ? $model->grace_period_tids + 1 : (($old_status == 'Grace') ? $model->grace_period_tids - 1 : $model->grace_period_tids);
			$model->expired_tids = ($new_status == 'Expired') ? $model->expired_tids + 1 : (($old_status == 'Expired') ? $model->expired_tids - 1 : $model->expired_tids);
			$model->expired_tids_fine = ($tid_data == null) ? ($old_status != 'Expired' ? $model->expired_tids_fine : 0) : $tid_data[0]['fine']; //
			$model->expired_tids_days_count = ($tid_data == null) ? ($old_status != 'Expired' ? $model->expired_tids_days_count : 0) : $tid_data[0]['expiry_days']; //
			$model->partially_exported_tids = ($new_status == 'Partially Exported') ? $model->partially_exported_tids + 1 : (($old_status == 'Partially Exported') ? $model->partially_exported_tids - 1 : $model->partially_exported_tids);
			$model->exported_tids = ($new_status == 'Exported') ? $model->exported_tids + 1 : (($old_status == 'Exported') ? $model->exported_tids - 1 : $model->exported_tids);
			$model->permanent_declaration_tids = ($new_status == 'Permanent') ? $model->permanent_declaration_tids + 1 : (($old_status == 'Permanent') ? $model->permanent_declaration_tids - 1 : $model->permanent_declaration_tids);
		    } else {
			if ($old_status == 'Expired' || $new_status == 'Expired') {
			    $model->expired_tids_fine = ($tid_data == null) ? $model->expired_tids_fine : $tid_data[0]['fine']; 
			    $model->expired_tids_days_count = ($tid_data == null) ? $model->expired_tids_days_count : $tid_data[0]['expiry_days'];
			}
		    }
		}
	    }

	    if (!$model->save()) {
		$error_msg = CHtml::errorSummary($model);
		return false;
	    }

//	if (!SummaryDashboardPerSegmentAndRenewal::updateRenewalModels($model->id, $error_msg, $segment_condition))
//	    return false;
	}
	return true;
    }

    /**
     * Update current summary dashboaord reocrd according to asset information (add asset, update asset, delete asset , renew asset)
     * @param String $segment_name the segment name or id of the asset
     * @param TidansActiveRecord $model the model that we need to modify
     * @param Asset $asset asset model that is added , modified , or deleted
     * @param AssetStatus $asset_status the status of asset that is added (in renew case), updated or deleted
     * @param String $error_msg the error msg if any error occured
     * @param String $action if null that means that the tid is added or modified, if 'delete' that means that either tid is deleted or its status     
     *  return true if successfully update dashboard records, otherwise false
     */
    public static function UpdateCurrentDashboardRecordsByAsset($segment_name, $model, $asset, $asset_status, &$error_msg, $action =null) {
	if ($model != null) {
	    $segment = $asset->segment_id;

	    $and = ($segment_name != 'Total') ? ' and ' : '';

	    $segment_condition = ($segment_name != 'Total') ? "segment_id=" . $segment : '';

	    $vehicles = Setting::getVehicleTypeOfAsset();
	    $radioactives = Setting::getRadioActiveTypeOfAsset();

	    //the asset is modified or added
	    if ($action != 'delete') {
		if ($asset->getIsNewRecord()) {
		    $model->total_assets = $model->total_assets + 1;
		    if ($asset->type_of_asset_id == $vehicles)
			$model->total_vehicles = $model->total_vehicles + 1;
		    if ($asset->type_of_asset_id == $radioactives)
			$model->total_radioactives = $model->total_radioactives + 1;
		} else {
		    $old_status = ($asset_status != null) ? $asset_status->old_status : null;
		    $new_status = ($asset_status != null) ? $asset_status->getStatusValue() : null;
		    if ($new_status != $old_status) {
			// Vehicle Information
			if ($asset->type_of_asset_id == $vehicles) {
			    $model->valid_vehicles = ($new_status == 'Valid') ? $model->valid_vehicles + 1 : (($old_status == 'Valid') ? $model->valid_vehicles - 1 : $model->valid_vehicles);
			    $model->grace_vehicles = ($new_status == 'Grace') ? $model->grace_vehicles + 1 : (($old_status == 'Grace') ? $model->grace_vehicles - 1 : $model->grace_vehicles);
			    $model->expired_vehicles = ($new_status == 'Expired' && $asset->asset_status != 'Exported') ? $model->expired_vehicles + 1 : (($old_status == 'Expired' && $asset->asset_status != 'Exported') ? $model->expired_vehicles - 1 : $model->expired_vehicles);
			    $model->expired_vehicle_days_count = (($new_status == 'Expired' || $old_status == 'Expired') && $asset->asset_status != 'Exported') ? "(select IF( ISNULL( SUM( expiry_days ) ) ,  '0', SUM( expiry_days ) ) from v_asset_dashboard where status = 'Expired' and asset_status != 'Exported'  and type_of_asset_id = " . $vehicles . $and . $segment_condition . ")" : $model->expired_vehicle_days_count;

			    // Radioactive Information
			} elseif ($asset->type_of_asset_id == $radioactives) {
			    $model->valid_radioactives = ($new_status == 'Valid') ? $model->valid_radioactives + 1 : (($old_status == 'Valid') ? $model->valid_radioactives - 1 : $model->valid_radioactives);
			    $model->grace_radioactives = ($new_status == 'Grace') ? $model->grace_radioactives + 1 : (($old_status == 'Grace') ? $model->grace_radioactives - 1 : $model->grace_radioactives);
			    $model->expired_radioactives = ($new_status == 'Expired' && $asset->asset_status != 'Exported') ? $model->expired_radioactives + 1 : (($old_status == 'Expired' && $asset->asset_status != 'Exported') ? $model->expired_radioactives - 1 : $model->expired_radioactives);
			    $model->expired_radioactive_days_count = (($new_status == 'Expired' || $old_status == 'Expired') && $asset->asset_status != 'Exported') ? "(select IF( ISNULL( SUM( expiry_days ) ) ,  '0', SUM( expiry_days ) ) from v_asset_dashboard where status = 'Expired' and asset_status != 'Exported' and type_of_asset_id = " . $radioactives . $and . $segment_condition . ")" : $model->expired_radioactive_days_count;
			}
		    } else {
			//if the user renew asset to expired or update expiry date
			if ($new_status == 'Expired' || $old_status == 'Expired' && $asset->asset_status != 'Exported')
			    if ($asset->type_of_asset_id == $vehicles)
				$model->expired_vehicle_days_count = "(select IF( ISNULL( SUM( expiry_days ) ) ,  '0', SUM( expiry_days ) ) from v_asset_dashboard where status = 'Expired' and asset_status != 'Exported' and type_of_asset_id = " . $vehicles . $and . $segment_condition . ")";
			    // Radioactive Information
			    elseif ($asset->type_of_asset_id == $radioactives)
				$model->expired_radioactive_days_count = "(select IF( ISNULL( SUM( expiry_days ) ) ,  '0', SUM( expiry_days ) ) from v_asset_dashboard where status = 'Expired' and asset_status != 'Exported' and type_of_asset_id = " . $radioactives . $and . $segment_condition . ")";
		    }
		}
	    } else {
		//the asset is deleted
		$model->total_assets = $model->total_assets - 1;
		$status = $asset->old_status;
		// Vehicle Information
		if ($asset->type_of_asset_id == $vehicles) {
		    $model->total_vehicles = $model->total_vehicles - 1;
		    $model->valid_vehicles = ($status == 'Valid') ? $model->valid_vehicles - 1 : $model->valid_vehicles;
		    $model->grace_vehicles = ($status == 'Grace') ? $model->grace_vehicles - 1 : $model->grace_vehicles;
		    $model->expired_vehicles = ($status == 'Expired' && $asset->asset_status != 'Exported') ? $model->expired_vehicles - 1 : $model->expired_vehicles;
		    $model->expired_vehicle_days_count = ($status == 'Expired' && $asset->asset_status != 'Exported') ? "(select IF( ISNULL( SUM( expiry_days ) ) ,  '0', SUM( expiry_days ) ) from v_asset_dashboard where status = 'Expired' and asset_status != 'Exported' and type_of_asset_id = " . $vehicles . $and . $segment_condition . ")" : $model->expired_vehicle_days_count;

		    // Radioactive Information
		} elseif ($asset->type_of_asset_id == $radioactives) {
		    $model->total_radioactives = $model->total_radioactives - 1;
		    $model->valid_radioactives = ($status == 'Valid') ? $model->valid_radioactives - 1 : $model->valid_radioactives;
		    $model->grace_radioactives = ($status == 'Grace') ? $model->grace_radioactives - 1 : $model->grace_radioactives;
		    $model->expired_radioactives = ($status == 'Expired' && $asset->asset_status != 'Exported') ? $model->expired_radioactives - 1 : $model->expired_radioactives;
		    $model->expired_radioactive_days_count = ($status == 'Expired' && $asset->asset_status != 'Exported') ? "(select IF( ISNULL( SUM( expiry_days ) ) ,  '0', SUM( expiry_days ) ) from v_asset_dashboard where status = 'Expired' and asset_status != 'Exported' and type_of_asset_id = " . $radioactives . $and . $segment_condition . ")" : $model->expired_radioactive_days_count;
		}
	    }
	    if (!$model->save()) {
		$error_msg = CHtml::errorSummary($model);
		return false;
	    }
	}
	return true;
    }

    /**
     * get list of dates that are stored in the dashboard
     */
    public static function getDateList() {
	$date_array = null;

	//get data above 18 months
	$model = SummaryDashboardPerSegment::model();
	$criteria = new CDbCriteria();
	$criteria->select = 'date';
	$criteria->order = 'date desc';
	$criteria->distinct = true;
	$now_minus_18 = date("Y-m-d", strtotime(date("Y-m-d", strtotime(date("Y-m-d"))) . " -18 month"));
	$criteria->condition = "date is not null and date >='" . $now_minus_18 . "'";
	$results = $model->commandBuilder->createFindCommand(
			$model->tableName(), $criteria)->queryColumn();


	$date_array['Today'] = 'Today';
	if ($results != null) {
	    foreach ($results as $result) {
		$date_array[$result] = date("F", strtotime($result)) . '-' . date('Y', strtotime($result));
	    }
	}

	return $date_array;
    }

    /**
     * get list of dates that are stored in the dashboard
     */
    public static function getSegmentList($is_current, $date = null, $use_name_as_key = true) {
	$criteria = new CDbCriteria;
	$criteria->select = 'segment_id,segment_name';
	if ($is_current)
	    $criteria->condition = 'is_current = 1';
	else {
	    if ($date != null)
		$criteria->condition = "date = '" . $date . "'";
	}

	$model = SummaryDashboardPerSegment::model();
	$data = $model->commandBuilder->createFindCommand(
			$model->tableName(), $criteria)->queryAll();
	$Multi_Non_array = array();
	$result = array();
	if ($data != null)
	    foreach ($data as $value) {
		if ($use_name_as_key)
		    if ($value['segment_name'] == 'Multi Segment' || $value['segment_name'] == 'Non Segment')
			$Multi_Non_array[$value['segment_name']] = $value['segment_name'];
		    else
			$result[$value['segment_name']] = $value['segment_name'];
		else {
		    $key = ($value['segment_name'] == 'Total') ? 'Total' : (($value['segment_name'] == 'Multi Segment') ? 'Multi Segment' : (($value['segment_name'] == 'Non Segment') ? 'Non Segment' : $value['segment_id']));
		    if ($key == 'Multi Segment' || $key == 'Non Segment')
			$Multi_Non_array[$key] = $value['segment_name'];
		    else
			$result[$key] = $value['segment_name'];
		}
	    }
	if ($Multi_Non_array != null)
	    foreach ($Multi_Non_array as $key => $element)
		$result[$key] = $element;
	return $result;
    }

    /**
     * build the query that will insert tid detail dashbaord records and execute it
     * return true if successfully add tid datailed dashboard records, false otherwise
     */
    public static function BuildTIDDashboardDetailQuery($date, &$error_msg) {
	$query_string = 'INSERT INTO `tid_detailed_dashboard`(date, `segment_id`, `segment_name`, `tid_id`, `tid_status_id`, `status`, `renewal_stage_id`, `grace_period`, `days_count`, `fine`)';
	$query_string .='Select ';
	$query_string .= "'" . $date . "',";
	$query_string .= "If( LOCATE( ',', segment_name ) , null, segment_id ) ,segment_name,`id`,last_status_id, `last_status_ti_status`, `last_status_renewal_stage_id`,`grace_period`, `expiry_days`, REPLACE(REPLACE(fine,'$',''),',','') FROM `v_tid` ";

	try {
	    $command = Yii::app()->db->createCommand($query_string);
	    $rows = $command->execute();
	    if ($rows <= 0) {
		return false;
	    }
	} catch (Exception $e) {
	    $error_msg = $e->getMessage();
	    return false;
	}
	return true;
    }

    /**
     * build the query that will insert asset detail dashbaord records and execute it
     * return true if successfully add asset datailed dashboard records, false otherwise
     */
    public static function BuildAssetDashboardDetailQuery($date, &$error_msg) {
	$query_string = 'INSERT INTO `asset_detailed_dashboard`(date, `segment_id`, `segment_name`,`asset_id`, `type_of_asset_id`, `expiry_date`, `status`, `grace_period`, `days_count`,asset_status)';
	$query_string .='Select ';
	$query_string .="'" . $date . "',";
	$query_string .= "`segment_id`, `segment_name`,`id`,type_of_asset_id, `expiry_date`, `status`,`grace_period`, `expiry_days`, asset_status FROM `v_asset` ";

	try {
	    $command = Yii::app()->db->createCommand($query_string);
	    $rows = $command->execute();
	    if ($rows <= 0)
		return false;
	} catch (Exception $e) {
	    $error_msg = $e->getMessage();
	    return false;
	}
	return true;
    }

    /**
     * Update current summary dashboaord tid information by asset modification (adding asset or modifying asset will affect tids according to asset segment)<br>
     * the tid maybe moved from Non Segment to a specific segment or from one segment to multi segment
     * @param TidansActiveRecord $model the model that we need to modify
     * @param String $segment the id of segment or (Total for all segment, 'Multi Segment' or 'Non Segment')
     * @param String $status the status of tid (Valid, Grace, Expired....)
     * @param String $is_increased true to increase tids with the specified status, false to decrease tid with the specified status
     * @param String $error_msg the error msg if any error occured
     *  return true if successfully update dashboard records, otherwise false
     */
    public static function UpdateCurrentDashboardTIDInformation($model, $segment, $status, $is_increased, &$error_msg) {
	if ($model != null) {
	    $and = ($segment == 'Total') ? '' : ' and ';
	    $where = ($segment == 'Total') ? '' : ' where ';
	    $segment_condition = '';
	    if ($segment == 'Multi Segment')
		$segment_condition = "segment_name like '%,%'";
	    elseif ($segment == 'Non Segment')
		$segment_condition = "segment_name is null";
	    elseif ($segment != 'Total')
		$segment_condition = "segment_id='" . $segment . "'";

	    $tid_data = null;
	    if ($status == 'Expired') {
		$tid_model = VTidDashboard::model();
		$cr1 = new CDbCriteria();
		$cr1->select = "sum(expiry_days) as expiry_days,ROUND(sum(expiry_days) * (select value from setting where name = 'tid_daily_fine')) as fine, last_status_ti_status";
		$extra_condition = ($segment_condition != '') ? " and last_status_ti_status='" . $status . "'" : "last_status_ti_status='" . $status . "'";
		$cr1->condition = $segment_condition . $extra_condition;
		$cr1->group = 'last_status_ti_status';
		$tid_data = $tid_model->commandBuilder->createFindCommand(
				$tid_model->tableName(), $cr1)->queryAll();
	    }


	    $model->total_tids = ($is_increased) ? $model->total_tids + 1 : $model->total_tids - 1;
	    $model->valid_tids = ($status == 'Valid' && $is_increased) ? $model->valid_tids + 1 : (($status == 'Valid' && !$is_increased) ? $model->valid_tids - 1 : $model->valid_tids);
	    $model->grace_period_tids = ($status == 'Grace' && $is_increased) ? $model->grace_period_tids + 1 : (($status == 'Grace' && !$is_increased) ? $model->grace_period_tids - 1 : $model->grace_period_tids);
	    $model->expired_tids = ($status == 'Expired' && $is_increased) ? $model->expired_tids + 1 : (($status == 'Expired' && !$is_increased) ? $model->expired_tids - 1 : $model->expired_tids);
	    $model->expired_tids_fine = ($tid_data == null) ? ($status != 'Expired' ? $model->expired_tids_fine : 0) : $tid_data[0]['fine']; //
	    $model->expired_tids_days_count = ($tid_data == null) ? ($status != 'Expired' ? $model->expired_tids_days_count : 0 ) : $tid_data[0]['expiry_days']; //
	    $model->partially_exported_tids = ($status == 'Partially Exported' && $is_increased) ? $model->partially_exported_tids + 1 : (($status == 'Partially Exported' && !$is_increased) ? $model->partially_exported_tids - 1 : $model->partially_exported_tids);
	    $model->exported_tids = ($status == 'Exported' && $is_increased) ? $model->exported_tids + 1 : (($status == 'Exported' && !$is_increased) ? $model->exported_tids - 1 : $model->exported_tids);
	    $model->permanent_declaration_tids = ($status == 'Permanent' && $is_increased) ? $model->permanent_declaration_tids + 1 : (($status == 'Permanent' && !$is_increased) ? $model->permanent_declaration_tids - 1 : $model->permanent_declaration_tids);

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

    /**
     * Update current summary dashboaord asset information if segment changed
     * @param TidansActiveRecord $model the model that we need to modify
     * @param String $segment the id of segment or (Total for all segment, 'Multi Segment' or 'Non Segment')
     * @param Asset $asset asset model that is added , modified , or deleted
     * @param String $status the status of asset (Valid, Grace, Expired....)
     * @param String $is_increased true to increase tids with the specified status, false to decrease tid with the specified status
     * @param String $error_msg the error msg if any error occured
     *  return true if successfully update dashboard records, otherwise false
     */
    public static function UpdateCurrentDashboardAssetInformationBySegment($model, $segment, $asset, $status, $is_increased, &$error_msg) {
	if ($model != null) {
	    $and = ($segment == 'Total') ? '' : ' and ';
	    $where = ($segment == 'Total') ? '' : ' where ';
	    $segment_condition = '';
	    if ($segment == 'Multi Segment')
		$segment_condition = "segment_name like '%,%'";
	    elseif ($segment == 'Non Segment')
		$segment_condition = "segment_name is null";
	    elseif ($segment != 'Total')
		$segment_condition = "segment_id=" . $segment;


	    $vehicles = Setting::getVehicleTypeOfAsset();
	    $radioactives = Setting::getRadioActiveTypeOfAsset();


	    $model->total_assets = ($is_increased) ? $model->total_assets + 1 : $model->total_assets - 1;
	    if ($asset->type_of_asset_id == $vehicles)
		$model->total_vehicles = ($is_increased) ? $model->total_vehicles + 1 : $model->total_vehicles - 1;
	    if ($asset->type_of_asset_id == $radioactives)
		$model->total_radioactives = ($is_increased) ? $model->total_radioactives + 1 : $model->total_radioactives - 1;
	    // Vehicle Information
	    if ($asset->type_of_asset_id == $vehicles) {
		$model->valid_vehicles = ($status == 'Valid' && $is_increased) ? $model->valid_vehicles + 1 : (($status == 'Valid' && !$is_increased) ? $model->valid_vehicles - 1 : $model->valid_vehicles);
		$model->grace_vehicles = ($status == 'Grace' && $is_increased) ? $model->grace_vehicles + 1 : (($status == 'Grace' && !$is_increased) ? $model->grace_vehicles - 1 : $model->grace_vehicles);
		$model->expired_vehicles = ($status == 'Expired' && $is_increased && $asset->asset_status != 'Exported') ? $model->expired_vehicles + 1 : (($status == 'Expired' && !$is_increased) ? $model->expired_vehicles - 1 : $model->expired_vehicles);
		$model->expired_vehicle_days_count = ($status == 'Expired' && $asset->asset_status != 'Exported') ? "(select IF( ISNULL( SUM( expiry_days ) ) ,  '0', SUM( expiry_days ) ) from v_asset_dashboard where status = 'Expired' and asset_status != 'Exported' and type_of_asset_id = " . $vehicles . $and . $segment_condition . ")" : $model->expired_vehicle_days_count;

		// Radioactive Information
	    } elseif ($asset->type_of_asset_id == $radioactives) {
		$model->valid_radioactives = ($status == 'Valid' && $is_increased) ? $model->valid_radioactives + 1 : (($status == 'Valid' && !$is_increased) ? $model->valid_radioactives - 1 : $model->valid_radioactives);
		$model->grace_radioactives = ($status == 'Grace' && $is_increased) ? $model->grace_radioactives + 1 : (($status == 'Grace' && !$is_increased) ? $model->grace_radioactives - 1 : $model->grace_radioactives);
		$model->expired_radioactives = ($status == 'Expired' && $is_increased && $asset->asset_status != 'Exported') ? $model->expired_radioactives + 1 : (($status == 'Expired' && !$is_increased) ? $model->expired_radioactives - 1 : $model->expired_radioactives);
		$model->expired_radioactive_days_count = ($status == 'Expired' && $asset->asset_status != 'Exported') ? "(select IF( ISNULL( SUM( expiry_days ) ) ,  '0', SUM( expiry_days ) ) from v_asset_dashboard where status = 'Expired' and asset_status != 'Exported' and type_of_asset_id = " . $radioactives . $and . $segment_condition . ")" : $model->expired_radioactive_days_count;
	    }


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

    /**
     * Update current summary dashboaord tid information according to prevous segment of tid and the asset segment
     * <br> updating asset segment or adding asset to tid (that is not non segment, or the asset segment is different from tid segment) will affect the dashbaord
     * <br> so we need to update both segment and old one
     */
    public static function updateTidRecordsByAssetSegment($asset, $action = null, $tid_modified = null, $old_segment = null, $force_use_old_segment = false) {
	if ($asset != null) {
	    $tid = ($tid_modified == null) ? $asset->invoice->tid : $tid_modified;
	    $tid_no = $tid->tid_no;
	    $last_status = $tid->getLastStatus();
	    $renewal_stage_id = ($last_status != null) ? $last_status->renewal_stage_id : null;
	    if ($tid != null) {
		//if we add new asset or update existing one...it will change tid according to its segment
		if ($action != 'delete') {
		    //get the segment of the tid before updating or adding the asset
		    $tid_segment_id = (!$force_use_old_segment) ? $asset->old_segment : $old_segment;
		    //if the tid has no asset..(i.e it's Non Segment)
		    if ($tid_segment_id == null) {
			//the new added asset segment will consider tid segment
			$model = SummaryDashboardPerSegment::model()->findByAttributes(array('is_current' => '1', 'segment_id' => $asset->segment_id));
			if (!SummaryDashboardPerSegment::UpdateCurrentDashboardTIDInformation($model, $asset->segment_id, (($last_status != null) ? $last_status->ti_status : null), true, $error_msg))
			    return false;
			if ($renewal_stage_id != null) {
			    if (!SummaryDashboardPerSegmentAndRenewal::updateRenewalModelByAssetSegment($model->id, $renewal_stage_id, true, $error_msg))
				return false;
			}
			//the current tid will be removed from Non Segment
			$model = SummaryDashboardPerSegment::model()->findByAttributes(array('is_current' => '1', 'segment_name' => 'Non Segment'));
			if (!SummaryDashboardPerSegment::UpdateCurrentDashboardTIDInformation($model, 'Non Segment', (($last_status != null) ? $last_status->ti_status : null), false, $error_msg))
			    return false;
			if ($renewal_stage_id != null) {
			    if (!SummaryDashboardPerSegmentAndRenewal::updateRenewalModelByAssetSegment($model->id, $renewal_stage_id, false, $error_msg))
				return false;
			}
		    } else {
			//adding asset case
			if ($action != 'update') {
			    //if the tid has a segment and it's not multi segment and the new added asset is with different segment,<br>
			    // the tid will be considered Multi Segment and its information will be removed from the previous segment of the tid
			    if (strpos($tid_segment_id, ',') == false) {
				if ($tid_segment_id != $asset->segment_id) {
				    //the tid become multi segment
				    $model = SummaryDashboardPerSegment::model()->findByAttributes(array('is_current' => '1', 'segment_name' => 'Multi Segment'));
				    if (!SummaryDashboardPerSegment::UpdateCurrentDashboardTIDInformation($model, 'Multi Segment', (($last_status != null) ? $last_status->ti_status : null), true, $error_msg))
					return false;
				    if ($renewal_stage_id != null) {
					if (!SummaryDashboardPerSegmentAndRenewal::updateRenewalModelByAssetSegment($model->id, $renewal_stage_id, true, $error_msg))
					    return false;
				    }
				    //remove its information from its previous segment
				    $model = SummaryDashboardPerSegment::model()->findByAttributes(array('is_current' => '1', 'segment_id' => $tid_segment_id));
				    if (!SummaryDashboardPerSegment::UpdateCurrentDashboardTIDInformation($model, $tid_segment_id, (($last_status != null) ? $last_status->ti_status : null), false, $error_msg))
					return false;
				    if ($renewal_stage_id != null) {
					if (!SummaryDashboardPerSegmentAndRenewal::updateRenewalModelByAssetSegment($model->id, $renewal_stage_id, false, $error_msg))
					    return false;
				    }
				}
			    }
			}
			else {
			    //updating asset case
			    if ($action == 'update') {
				$new_tid_segment_id = null;
				$segment = $tid->getSegmentInfo();
				if ($segment != null) {
				    $new_tid_segment_id = $segment['segment_id'];
				}
				if ($new_tid_segment_id != null) {
//				    //if the tid has a segment and it's not multi segment and tid has only one asset and this asset segment is updated to different segment ,<br>
//				    // the tid will be moved to the new asset segment and its information will be removed from the previous segment of the tid
				    if (strpos($tid_segment_id, ',') == false && strpos($new_tid_segment_id, ',') == false) {
					if ($tid_segment_id != $asset->segment_id) {
					    $model = SummaryDashboardPerSegment::model()->findByAttributes(array('is_current' => '1', 'segment_id' => $asset->segment_id));
					    if (!SummaryDashboardPerSegment::UpdateCurrentDashboardTIDInformation($model, $asset->segment_id, (($last_status != null) ? $last_status->ti_status : null), true, $error_msg))
						return false;
					    if ($renewal_stage_id != null) {
						if (!SummaryDashboardPerSegmentAndRenewal::updateRenewalModelByAssetSegment($model->id, $renewal_stage_id, true, $error_msg))
						    return false;
					    }
					    $model = SummaryDashboardPerSegment::model()->findByAttributes(array('is_current' => '1', 'segment_id' => $tid_segment_id));
					    if (!SummaryDashboardPerSegment::UpdateCurrentDashboardTIDInformation($model, $tid_segment_id, (($last_status != null) ? $last_status->ti_status : null), false, $error_msg))
						return false;
					    if ($renewal_stage_id != null) {
						if (!SummaryDashboardPerSegmentAndRenewal::updateRenewalModelByAssetSegment($model->id, $renewal_stage_id, false, $error_msg))
						    return false;
					    }
					}
				    }
				    //if the tid has a segment and it's not multi segment and tid has more than one asset and one of its asset segment is updated to different segment<br>
//				    // the tid will be moved to the Multi Segment and its information will be removed from the previous segment of the tid
				    elseif (strpos($tid_segment_id, ',') == false && strpos($new_tid_segment_id, ',') != false) {
					$model = SummaryDashboardPerSegment::model()->findByAttributes(array('is_current' => '1', 'segment_name' => 'Multi Segment'));
					if (!SummaryDashboardPerSegment::UpdateCurrentDashboardTIDInformation($model, 'Multi Segment', (($last_status != null) ? $last_status->ti_status : null), true, $error_msg))
					    return false;
					if ($renewal_stage_id != null) {
					    if (!SummaryDashboardPerSegmentAndRenewal::updateRenewalModelByAssetSegment($model->id, $renewal_stage_id, true, $error_msg))
						return false;
					}
					$model = SummaryDashboardPerSegment::model()->findByAttributes(array('is_current' => '1', 'segment_id' => $tid_segment_id));
					if (!SummaryDashboardPerSegment::UpdateCurrentDashboardTIDInformation($model, $tid_segment_id, (($last_status != null) ? $last_status->ti_status : null), false, $error_msg))
					    return false;
					if ($renewal_stage_id != null) {
					    if (!SummaryDashboardPerSegmentAndRenewal::updateRenewalModelByAssetSegment($model->id, $renewal_stage_id, false, $error_msg))
						return false;
					}
				    }
				    //if the tid has more than one asset, and it's multi segment and what make it multi segments only one asset<br>
				    //then update this asset to make its segment the same as other assets
				    // the tid will be moved to a specific segment and its information will be removed from the Multi Segment
				    //example tid has three assets (OFS,OFS,DNM) then update the asset with DNM segment to OFS the tid will be moved to OFS and removed from Multi segment
				    elseif (strpos($tid_segment_id, ',') != false && strpos($new_tid_segment_id, ',') == false) {
					$model = SummaryDashboardPerSegment::model()->findByAttributes(array('is_current' => '1', 'segment_name' => 'Multi Segment'));
					if (!SummaryDashboardPerSegment::UpdateCurrentDashboardTIDInformation($model, 'Multi Segment', (($last_status != null) ? $last_status->ti_status : null), false, $error_msg))
					    return false;
					if ($renewal_stage_id != null) {
					    if (!SummaryDashboardPerSegmentAndRenewal::updateRenewalModelByAssetSegment($model->id, $renewal_stage_id, false, $error_msg))
						return false;
					}
					$model = SummaryDashboardPerSegment::model()->findByAttributes(array('is_current' => '1', 'segment_id' => $new_tid_segment_id));
					if (!SummaryDashboardPerSegment::UpdateCurrentDashboardTIDInformation($model, $new_tid_segment_id, (($last_status != null) ? $last_status->ti_status : null), true, $error_msg))
					    return false;
					if ($renewal_stage_id != null) {
					    if (!SummaryDashboardPerSegmentAndRenewal::updateRenewalModelByAssetSegment($model->id, $renewal_stage_id, true, $error_msg))
						return false;
					}
				    }
				}else {
				    //if the new segment of tid become null..that is mean it will be moved to Non segment
				    $model = SummaryDashboardPerSegment::model()->findByAttributes(array('is_current' => '1', 'segment_name' => 'Non Segment'));
				    if (!SummaryDashboardPerSegment::UpdateCurrentDashboardTIDInformation($model, 'Non Segment', (($last_status != null) ? $last_status->ti_status : null), true, $error_msg))
					return false;
				    if ($renewal_stage_id != null) {
					if (!SummaryDashboardPerSegmentAndRenewal::updateRenewalModelByAssetSegment($model->id, $renewal_stage_id, true, $error_msg))
					    return false;
				    }
				    $model = SummaryDashboardPerSegment::model()->findByAttributes(array('is_current' => '1', 'segment_id' => $tid_segment_id));
				    if (!SummaryDashboardPerSegment::UpdateCurrentDashboardTIDInformation($model, $tid_segment_id, (($last_status != null) ? $last_status->ti_status : null), false, $error_msg))
					return false;
				    if ($renewal_stage_id != null) {
					if (!SummaryDashboardPerSegmentAndRenewal::updateRenewalModelByAssetSegment($model->id, $renewal_stage_id, false, $error_msg))
					    return false;
				    }
				}
			    }
			}
		    }
		} else {
		    //if the user delete an asset
		    $new_tid_segment_id = null;
		    $old_tid_segment_id = $asset->old_segment;
		    $segment = $tid->getSegmentInfo();
		    if ($segment != null) {
			$new_tid_segment_id = $segment['segment_id'];
		    }
		    //if the new segment is empty ...this mean the tid no longer has any asset
		    //the tid will be move to Non Segment and its information will be removed from the asset segment
		    if ($new_tid_segment_id == null) {
			$model = SummaryDashboardPerSegment::model()->findByAttributes(array('is_current' => '1', 'segment_id' => $asset->segment_id));
			if (!SummaryDashboardPerSegment::UpdateCurrentDashboardTIDInformation($model, $asset->segment_id, (($last_status != null) ? $last_status->ti_status : null), false, $error_msg))
			    return false;
			if ($renewal_stage_id != null) {
			    if (!SummaryDashboardPerSegmentAndRenewal::updateRenewalModelByAssetSegment($model->id, $renewal_stage_id, false, $error_msg))
				return false;
			}
			$model = SummaryDashboardPerSegment::model()->findByAttributes(array('is_current' => '1', 'segment_name' => 'Non Segment'));
			if (!SummaryDashboardPerSegment::UpdateCurrentDashboardTIDInformation($model, 'Non Segment', (($last_status != null) ? $last_status->ti_status : null), true, $error_msg))
			    return false;
			if ($renewal_stage_id != null) {
			    if (!SummaryDashboardPerSegmentAndRenewal::updateRenewalModelByAssetSegment($model->id, $renewal_stage_id, true, $error_msg))
				return false;
			}
		    } else {
			//if the tid segment was multi segment and remove the asset that is differnt from other ...this mean the tid will be single segment
			//the tid will be move to a specific segment and its information will be removed from the Multi segment
			if (strpos($old_tid_segment_id, ',') != false && strpos($new_tid_segment_id, ',') == false) {
			    $model = SummaryDashboardPerSegment::model()->findByAttributes(array('is_current' => '1', 'segment_name' => 'Multi Segment'));
			    if (!SummaryDashboardPerSegment::UpdateCurrentDashboardTIDInformation($model, 'Multi Segment', (($last_status != null) ? $last_status->ti_status : null), false, $error_msg))
				return false;
			    if ($renewal_stage_id != null) {
				if (!SummaryDashboardPerSegmentAndRenewal::updateRenewalModelByAssetSegment($model->id, $renewal_stage_id, false, $error_msg))
				    return false;
			    }
			    $model = SummaryDashboardPerSegment::model()->findByAttributes(array('is_current' => '1', 'segment_id' => $new_tid_segment_id));
			    if (!SummaryDashboardPerSegment::UpdateCurrentDashboardTIDInformation($model, $new_tid_segment_id, (($last_status != null) ? $last_status->ti_status : null), true, $error_msg))
				return false;
			    if ($renewal_stage_id != null) {
				if (!SummaryDashboardPerSegmentAndRenewal::updateRenewalModelByAssetSegment($model->id, $renewal_stage_id, true, $error_msg))
				    return false;
			    }
			}
		    }
		}
	    }
	}

	return true;
    }

    /**
     * Update segment name of the dashboard summary
     */
    public static function UpdateSegmentName($segment_id, $segment_name, &$error_msg) {
	$dashboard_summary_models = SummaryDashboardPerSegment::model()->findAllByAttributes(array('is_current' => '1', 'segment_id' => $segment_id));
	if ($dashboard_summary_models != null) {
	    foreach ($dashboard_summary_models as $dashboard_summary_model) {
		$dashboard_summary_model->segment_name = $segment_name;
		if (!$dashboard_summary_model->save()) {
		    $error_msg = CHtml::errorSummary($dashboard_summary_model);
		    return false;
		}
	    }
	}
	return true;
    }

    /**
     * Update current summary dashboaord asset information if type of asset changed
     * @param TidansActiveRecord $model the model that we need to modify
     * @param String $segment the id of segment or (Total for all segment, 'Multi Segment' or 'Non Segment')
     * @param Integer $old_type the old type of asset id
     * @param Integer $new_type the new type of asset id     
     * @param String $status the new status of asset (Valid, Grace, Expired....)
     * @param String $old_status the old status of asset (Valid, Grace, Expired....)
     * @param String $error_msg the error msg if any error occured
     * return true if successfully update dashboard records, otherwise false
     */
    public static function UpdateCurrentDashboardAssetInformationByAssetType($model, $asset, $segment, $old_type, $new_type, $status, $old_status, &$error_msg) {
	if ($model != null) {
	    $and = ($segment == 'Total') ? '' : ' and ';
	    $where = ($segment == 'Total') ? '' : ' where ';
	    $segment_condition = '';
	    if ($segment == 'Multi Segment')
		$segment_condition = "segment_name like '%,%'";
	    elseif ($segment == 'Non Segment')
		$segment_condition = "segment_name is null";
	    elseif ($segment != 'Total')
		$segment_condition = "segment_id=" . $segment;


	    $vehicles = Setting::getVehicleTypeOfAsset();
	    $radioactives = Setting::getRadioActiveTypeOfAsset();

	    if ($old_type == $vehicles && $new_type != $vehicles) {
		$model->total_vehicles = $model->total_vehicles - 1;
		$model->valid_vehicles = ($old_status == 'Valid') ? $model->valid_vehicles - 1 : $model->valid_vehicles;
		$model->grace_vehicles = ($old_status == 'Grace') ? $model->grace_vehicles - 1 : $model->grace_vehicles;
		$model->expired_vehicles = ($old_status == 'Expired' && $asset->asset_status != 'Exported') ? $model->expired_vehicles - 1 : $model->expired_vehicles;
		$model->expired_vehicle_days_count = ($old_status == 'Expired' && $asset->asset_status != 'Exported') ? "(select IF( ISNULL( SUM( expiry_days ) ) ,  '0', SUM( expiry_days ) ) from v_asset_dashboard where status = 'Expired' and asset_status != 'Exported' and type_of_asset_id = " . $vehicles . $and . $segment_condition . ")" : $model->expired_vehicle_days_count;
	    }
	    if ($old_type != $vehicles && $new_type == $vehicles) {
		$model->total_vehicles = $model->total_vehicles + 1;
		$model->valid_vehicles = ($status == 'Valid') ? $model->valid_vehicles + 1 : $model->valid_vehicles;
		$model->grace_vehicles = ($status == 'Grace') ? $model->grace_vehicles + 1 : $model->grace_vehicles;
		$model->expired_vehicles = ($status == 'Expired' && $asset->asset_status != 'Exported') ? $model->expired_vehicles + 1 : $model->expired_vehicles;
		$model->expired_vehicle_days_count = ($status == 'Expired' && $asset->asset_status != 'Exported') ? "(select IF( ISNULL( SUM( expiry_days ) ) ,  '0', SUM( expiry_days ) ) from v_asset_dashboard where status = 'Expired' and asset_status != 'Exported' and type_of_asset_id = " . $vehicles . $and . $segment_condition . ")" : $model->expired_vehicle_days_count;
	    }

	    if ($old_type == $radioactives && $new_type != $radioactives) {
		$model->total_radioactives = $model->total_radioactives - 1;
		$model->valid_radioactives = ($old_status == 'Valid') ? $model->valid_radioactives - 1 : $model->valid_radioactives;
		$model->grace_radioactives = ($old_status == 'Grace') ? $model->grace_radioactives - 1 : $model->grace_radioactives;
		$model->expired_radioactives = ($old_status == 'Expired' && $asset->asset_status != 'Exported') ? $model->expired_radioactives - 1 : $model->expired_radioactives;
		$model->expired_radioactive_days_count = ($old_status == 'Expired' && $asset->asset_status != 'Exported') ? "(select IF( ISNULL( SUM( expiry_days ) ) ,  '0', SUM( expiry_days ) ) from v_asset_dashboard where status = 'Expired' and asset_status != 'Exported' and type_of_asset_id = " . $radioactives . $and . $segment_condition . ")" : $model->expired_radioactive_days_count;
	    }
	    if ($old_type != $radioactives && $new_type == $radioactives) {
		$model->total_radioactives = $model->total_radioactives + 1;
		$model->valid_radioactives = ($status == 'Valid') ? $model->valid_radioactives + 1 : $model->valid_radioactives;
		$model->grace_radioactives = ($status == 'Grace') ? $model->grace_radioactives + 1 : $model->grace_radioactives;
		$model->expired_radioactives = ($status == 'Expired' && $asset->asset_status != 'Exported') ? $model->expired_radioactives + 1 : $model->expired_radioactives;
		$model->expired_radioactive_days_count = ($status == 'Expired' && $asset->asset_status != 'Exported') ? "(select IF( ISNULL( SUM( expiry_days ) ) ,  '0', SUM( expiry_days ) ) from v_asset_dashboard where status = 'Expired' and asset_status != 'Exported' and type_of_asset_id = " . $radioactives . $and . $segment_condition . ")" : $model->expired_radioactive_days_count;
	    }


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

    /**
     * Update current summary dashboaord asset information if asset status changed (In Country ,Exported)
     * @param TidansActiveRecord $model the model that we need to modify
     * @param String $segment the id of segment or (Total for all segment, 'Multi Segment' or 'Non Segment')
     * @param String $status the new status of asset (Valid, Grace, Expired....)
     * @param String $old_status the old status of asset (Valid, Grace, Expired....)
     * @param String $error_msg the error msg if any error occured
     * return true if successfully update dashboard records, otherwise false
     */
    public static function UpdateCurrentDashboardAssetInformationByAssetStatus($model, $segment, $asset, $last_status, $is_increased, &$error_msg) {
	if ($model != null) {
	    $and = ($segment == 'Total') ? '' : ' and ';
	    $where = ($segment == 'Total') ? '' : ' where ';
	    $segment_condition = '';
	    if ($segment == 'Multi Segment')
		$segment_condition = "segment_name like '%,%'";
	    elseif ($segment == 'Non Segment')
		$segment_condition = "segment_name is null";
	    elseif ($segment != 'Total')
		$segment_condition = "segment_id=" . $segment;


	    $vehicles = Setting::getVehicleTypeOfAsset();
	    $radioactives = Setting::getRadioActiveTypeOfAsset();

	    if ($asset->type_of_asset_id == $vehicles) {
		$model->expired_vehicles = ($is_increased) ? $model->expired_vehicles + 1 : $model->expired_vehicles - 1;
		$model->expired_vehicle_days_count = "(select IF( ISNULL( SUM( expiry_days ) ) ,  '0', SUM( expiry_days ) ) from v_asset_dashboard where status = 'Expired' and asset_status != 'Exported' and type_of_asset_id = " . $vehicles . $and . $segment_condition . ")";
	    }

	    if ($asset->type_of_asset_id == $radioactives) {
		$model->expired_radioactives = ($is_increased) ? $model->expired_radioactives + 1 : $model->expired_radioactives - 1;
		$model->expired_radioactive_days_count = "(select IF( ISNULL( SUM( expiry_days ) ) ,  '0', SUM( expiry_days ) ) from v_asset_dashboard where status = 'Expired' and asset_status != 'Exported' and type_of_asset_id = " . $radioactives . $and . $segment_condition . ")";
	    }


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

    /**
     * Get Summary dashboard records By date
     */
    public static function getDashboardReocrdsByDate($date) {
	return SummaryDashboardPerSegment::model()->findAllByAttributes(array('date' => $date, 'is_current' => '0'));
    }

    /**
     * Check if the specific date has reocrds in summary dashboard
     * return true if  if the specific date has reocrds in summary dashboard, otherwise false
     */
    public static function CheckExistingDashboardRecords($date) {
	$models = SummaryDashboardPerSegment::getDashboardReocrdsByDate($date);
	if ($models == null)
	    return false;
	return true;
    }

}
