<?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
 */
 
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

class DashboardUpdater extends CActiveRecordBehavior {

    public $allowedClasses = array();
    public $transaction = null;

    /**
     * This is responisble for opening transaction before saving model <br/>
     * so that the model will not be saved if there is any error while updating the dashboard<br/>
     * if the model is asset or tid , the transaction will be opened in the controller so we will not open trasnaction here <br/>
     * because we can't open two transaction at the same time
     */
    public function beforeSave($event) {
	$allowedClasses = $this->allowedClasses;
	// Lets check if the whole class should be ignored
	//This will be applied only for classes that affect the dashboard (Segment, Renewal Stage,TID,TID Status,Asset and Asset Status)
	if (sizeof($allowedClasses) > 0) {
	    if (array_search(get_class($this->getOwner()), $allowedClasses) === false)
		return true;
	}

	//the controller of tid and asset already start a transaction so we don't need other transaction
	if (!($this->getOwner() instanceof Tid) && !($this->getOwner() instanceof TidStatus) && !($this->getOwner() instanceof Asset) && !($this->getOwner() instanceof AssetStatus))
	    $this->transaction = Yii::app()->db->beginTransaction();
	return parent::beforeSave($event);
    }

    /**
     * This is responisble for updating the dashboard for the models that affect the dashboard <br/>
     * and if there is no error , it will commit the transaction that is started in the beforeSave event <br/>
     * otherwise the transaction will be rollbacked <br/>
     * 
     */
    public function afterSave($event) {
	$allowedClasses = $this->allowedClasses;
	// Lets check if the whole class should be ignored

	$class_name = get_class($this->getOwner());
	//This will be applied only for classes that affect the dashboard (Segment, Renewal Stage,TID,TID Status,Asset and Asset Status)
	if (sizeof($allowedClasses) > 0) {
	    if (array_search(get_class($this->getOwner()), $allowedClasses) === false)
		return true;
	}


	if ($this->getOwner()->hasErrors())
	    return true;
	try {

	    //=========================Segment Processing=====================================
	    if ($this->getOwner() instanceof Segment) {
		//if we add new segment, its status must be active..since inactive segment will not be display in the current dashboard
		if ($this->getOwner()->getIsNewRecord() && $this->getOwner()->status == 'Active') {
		    if (!SummaryDashboardPerSegment::BuildDashboardRowModel($this->getOwner()->name, $this->getOwner()->id, $error_msg, true)) {
			$this->getOwner()->addError('id', $error_msg);
			$this->transaction->rollback();
			return false;
		    }
		} else {
		    //here is we update the segment
		    if (!$this->getOwner()->getIsNewRecord()) {
			//update process change the name of the segment
			if ($this->getOwner()->name != $this->getOwner()->old_name) {
			    if (!SummaryDashboardPerSegment::UpdateSegmentName($this->getOwner()->id, $this->getOwner()->name, $error_msg)) {
				$this->getOwner()->addError('id', $error_msg);
				$this->transaction->rollback();
				return false;
			    }
			}
			//update process change the status of the segment to inactive (the segment will be removed from dashboard summary)
			if ($this->getOwner()->status != $this->getOwner()->old_status && $this->getOwner()->status == 'Inactive') {
			    if (SummaryDashboardPerSegment::removeSummaryDashboardRecordBySegmentIDs($this->getOwner()->id, true) != -1) {
				$this->getOwner()->addError('id', $error_msg);
				$this->transaction->rollback();
				return false;
			    }
			}
			//update process change the status of the segment to active (the segment will be added to dashboard summary)
			else
			if ($this->getOwner()->status != $this->getOwner()->old_status && $this->getOwner()->status == 'Active') {
			    if (!SummaryDashboardPerSegment::BuildDashboardRowModel($this->getOwner()->name, $this->getOwner()->id, $error_msg, true)) {
				$this->getOwner()->addError('id', $error_msg);
				$this->transaction->rollback();
				return false;
			    }
			}
		    }
		}
	    }


	    //============================Renewal Processing=================================
	    //if we add new renewal stage, its status must be active..since inactive renewal stage will not be display in the current dashboard
	    if ($this->getOwner()->getIsNewRecord() && $this->getOwner() instanceof RenewalStage && $this->getOwner()->status == 'Active') {
		if (!SummaryDashboardPerSegmentAndRenewal::createRenewalRow($this->getOwner()->id, $error_msg)) {
		    $this->transaction->rollback();
		    return false;
		}
	    } elseif (!$this->getOwner()->getIsNewRecord() && $this->getOwner() instanceof RenewalStage) {
		//here is the update process, change renewal stage status to inactive so that its information will be removed from the dashboard summary
		if ($this->getOwner()->status != $this->getOwner()->old_status && $this->getOwner()->status == 'Inactive') {
		    //first we will get the ids of the current dashboard summary records..to get its related records from dashboard summary for renewal
		    $criteria = new CDbCriteria();
		    $current_summary_dashboard_rows = '(' . SummaryDashboardPerSegment::getCurrentDashboardIDsAsString() . ')';
		    $criteria->condition = 'renewal_stage_id =' . $this->getOwner()->id . (($current_summary_dashboard_rows != null && $current_summary_dashboard_rows != '') ? ' and summary_dashboard_per_segment_id in ' . $current_summary_dashboard_rows : '');
		    //here we get the information of the dashboard summary for renewal records to delete them
		    $renewal_dashboard_Summmary_models = SummaryDashboardPerSegmentAndRenewal::model()->findAll($criteria);
		    if ($renewal_dashboard_Summmary_models != null) {
			foreach ($renewal_dashboard_Summmary_models as $renewal_dashboard_Summmary_model) {
			    if (!$renewal_dashboard_Summmary_model->delete()) {
				$this->getOwner()->addError('id', $error_msg);
				$this->transaction->rollback();
				return false;
			    }
			}
		    }
		} else
		if ($this->getOwner()->status != $this->getOwner()->old_status && $this->getOwner()->status == 'Active') {
		    //the update process will update the status of renewal stage to active so we will add its infornation to the dashboard summary for renewal
		    if (!SummaryDashboardPerSegmentAndRenewal::createRenewalRow($this->getOwner()->id, $error_msg)) {
			$this->transaction->rollback();
			return false;
		    }
		}
	    }


	    //================================TID Processing======================================
	    //if we add new tid, add tid status(renew tid) or update tid status
	    if (($this->getOwner() instanceof Tid && $this->getOwner()->getIsNewRecord()) || $this->getOwner() instanceof TidStatus) {
		$tid = ($this->getOwner() instanceof Tid) ? $this->getOwner() : $this->getOwner()->tid;
		$tid_status = ($this->getOwner() instanceof Tid) ? null : $this->getOwner();

		$last_tid_status = ($tid != null) ? $tid->getLastStatus() : null;
		//if the tid status that is modified is not the last status..its modification must not be applied
		//(so we need to compare the last status of the tid with the current status that is modified)
		if ((TidStatus::isEqual($tid_status, $last_tid_status) && $this->getOwner() instanceof TidStatus) || $this->getOwner() instanceof Tid) {
		    //get all current summary dashbaord to update them if necessary
		    $dashboard_summary_records = SummaryDashboardPerSegment::getCurrentDashboardRecords();

		    if ($dashboard_summary_records != null) {
			//get the segment of the tid, to know exactly which record of the current dashboard summary will be affected by the modification
			$segment_id = null;
			$segment_name = 'Non Segment';
			//Segemnet info will contain segment id and name.
			$segment = $tid->getSegmentInfo();
			if ($segment != null) {
			    $segment_id = $segment['segment_id'];
			    $segment_name = ($segment['segment_name'] != null) ? (strpos($segment['segment_name'], ',') ? 'Multi Segment' : $segment['segment_name']) : ($segment['segment_name'] == null ? 'Non Segment' : 'Total');
			}
			foreach ($dashboard_summary_records as $dashboard_summary_record) {
			    //here is the case where the we don't update or add tid and its tid status
			    //here we add or update asset and that affect tid status and tid segment
			    //so we need to update dashboard information that is related to the old segment of the tid
			    //because the new segment information will be updated in the asset update section
			    if ($this->getOwner() instanceof TidStatus && $this->getOwner()->is_updated_from_asset == true) {
				$old_tid_segment = ($this->getOwner()->old_tid_segment != null) ? (strpos($this->getOwner()->old_tid_segment, ',') ? 'Multi Segment' : $this->getOwner()->old_tid_segment) : 'Non Segment';
				//change only total column and the tid segment column
				if ($dashboard_summary_record->is_total == '1' || $old_tid_segment == $dashboard_summary_record->segment_name) {
				    if (!SummaryDashboardPerSegment::UpdateCurrentDashboardRecordsByTID($dashboard_summary_record, $tid, $tid_status, $error_msg)) {
					$this->getOwner()->addError('id', $error_msg);
					return false;
				    }
				    //update renewal stage information if there is any update in its information inside tid status
				    if ($tid_status != null)
					if ($tid_status->renewal_stage_id != $tid_status->old_renewal_stage_id || $tid_status->under_processing != $tid_status->old_under_processing) {
					    //if renewal stage id is changed or the under processing field changed....we need to update renewal stage information
					    //if the old value of renewal stage is not null..
					    //that is mean that the value of under processing wasn't no or null
					    //and the value of the renewal stage also is not null
					    if ($tid_status->old_renewal_stage_id != null)
						if (!SummaryDashboardPerSegmentAndRenewal::updateRenewalModelByAssetSegment($dashboard_summary_record->id, $tid_status->old_renewal_stage_id, false, $error_msg))
						    return false;

					    //if the new value of renewal stage is not null..
					    //that is mean that the value of under processing is Yes
					    //and the value of the renewal stage is not null
					    //otherwise if the new value is null ...only old value will be affected and that will remove the information of the renewal stage
					    if ($tid_status->renewal_stage_id != null)
						if (!SummaryDashboardPerSegmentAndRenewal::updateRenewalModelByAssetSegment($dashboard_summary_record->id, $tid_status->renewal_stage_id, true, $error_msg))
						    return false;
					}
				}
			    } else {
				//here the case of adding tid , or renew tid or update tid status
				//change only total column and the tid segment column
				if ($dashboard_summary_record->is_total == '1' || $segment_name == $dashboard_summary_record->segment_name) {
				    if (!SummaryDashboardPerSegment::UpdateCurrentDashboardRecordsByTID($dashboard_summary_record, $tid, $tid_status, $error_msg)) {
					$this->getOwner()->addError('id', $error_msg);
					return false;
				    }
				    if ($tid_status != null)
					if ($tid_status->renewal_stage_id != $tid_status->old_renewal_stage_id || $tid_status->under_processing != $tid_status->old_under_processing) {
					    //if renewal stage id is changed or the under processing field changed....we need to update renewal stage information
					    //if the old value of renewal stage is not null..
					    //that is mean that the value of under processing wasn't no or null
					    //and the value of the renewal stage also is not null
					    if ($tid_status->old_renewal_stage_id != null)
						if (!SummaryDashboardPerSegmentAndRenewal::updateRenewalModelByAssetSegment($dashboard_summary_record->id, $tid_status->old_renewal_stage_id, false, $error_msg))
						    return false;

					    //if the new value of renewal stage is not null..
					    //that is mean that the value of under processing is Yes
					    //and the value of the renewal stage is not null
					    //otherwise if the new value is null ...only old value will be affected and that will remove the information of the renewal stage
					    if ($tid_status->renewal_stage_id != null)
						if (!SummaryDashboardPerSegmentAndRenewal::updateRenewalModelByAssetSegment($dashboard_summary_record->id, $tid_status->renewal_stage_id, true, $error_msg))
						    return false;
					}
				}
			    }
			}
		    }
		}
	    }


	    //================================Asset Processing=============================================
	    //create new asset or new asset status (renew) or update asset status
	    if (($this->getOwner() instanceof Asset && $this->getOwner()->getIsNewRecord()) || $this->getOwner() instanceof AssetStatus) {
		$asset = ($this->getOwner() instanceof Asset) ? $this->getOwner() : $this->getOwner()->asset;
		$asset_status = ($this->getOwner() instanceof Asset) ? null : $this->getOwner();
		$last_asset_status = ($asset != null) ? $asset->getLastStatus() : null;
		//check if the status that is updated is the last status of the asset
		//(when renew asset, we will update fine and expiry days of the status before renew  which is not the last one...and that will not affect the dashboard so we need to skip it)
		if ((TidStatus::isEqual($asset_status, $last_asset_status) && $this->getOwner() instanceof AssetStatus) || $this->getOwner() instanceof Asset) {
		    //get all current summary dashbaord to update them if necessary
		    $dashboard_summary_records = SummaryDashboardPerSegment::getCurrentDashboardRecords();
		    if ($dashboard_summary_records != null) {
			foreach ($dashboard_summary_records as $dashboard_summary_record) {
			    //change only total column and the asset segment column
			    if ($dashboard_summary_record->is_total == '1' || $asset->segment_id == $dashboard_summary_record->segment_id) {
				if (!SummaryDashboardPerSegment::UpdateCurrentDashboardRecordsByAsset($dashboard_summary_record->segment_name, $dashboard_summary_record, $asset, $asset_status, $error_msg)) {
				    $this->getOwner()->addError('id', $error_msg);
				    return false;
				}
			    }
			}
			//updating asset will also affect tid (status, segment) so we need to update tid according to asset segment and status
			if ($this->getOwner() instanceof Asset)
			    if (!SummaryDashboardPerSegment::updateTidRecordsByAssetSegment($asset)) {
				$this->getOwner()->addError('id', $error_msg);
				return false;
			    }
		    }
		}
		//update asset (update asset segment, tid, type of asset or asset status (In country, exported)
	    } elseif ($this->getOwner() instanceof Asset && !$this->getOwner()->getIsNewRecord()) {
		//if the asset status changeed (from in country to exported or vice versa)
		if ($this->getOwner()->old_asset_status != $this->getOwner()->asset_status) {
		    //get the last status of the asset... to know its status (valid, grace or expired)
		    $last_status = $this->getOwner()->getLastStatus();
		    //if the type of asset is vehicle or radioactive so it has a status
		    if ($last_status != null) {
			//here we get the actual status of asset according to type of asset (vehicle book status or radioactive license status)
			$status = $last_status->getStatusValue();
			//change asset to exported or in country or vice versa affect only expired vehicles or radioactives
			//because dashboard  displays expired assets vehicles or radioactives that is not exported
			if ($status == 'Expired') {
			    //here we update cuurent dashbaord summary records that is related to asset segment..and of course the total records
			    //(($this->getOwner()->asset_status == 'Exported') ? false : true) this mean that we need to increase the expired vehicles or radioactives if the status from exported to in country
			    //and decrease the expired vehicles or radioactives if the status is changed from in country to exported
			    $model = SummaryDashboardPerSegment::model()->findByAttributes(array('is_current' => '1', 'segment_id' => $this->getOwner()->segment_id));
			    if (!SummaryDashboardPerSegment::UpdateCurrentDashboardAssetInformationByAssetStatus($model, $this->getOwner()->segment_id, $this->getOwner(), $last_status, (($this->getOwner()->asset_status == 'Exported') ? false : true), $error_msg))
				return false;
			    $model = SummaryDashboardPerSegment::model()->findByAttributes(array('is_current' => '1', 'is_total' => '1'));
			    if (!SummaryDashboardPerSegment::UpdateCurrentDashboardAssetInformationByAssetStatus($model, 'Total', $this->getOwner(), $last_status, (($this->getOwner()->asset_status == 'Exported') ? false : true), $error_msg))
				return false;
			}
		    }
		}
		//if the segment of the asset is changed
		if ($this->getOwner()->segment_id != $this->getOwner()->asset_old_segment) {
		    $last_status = $this->getOwner()->getLastStatus();
		    //change information for the new segment (increase the information of asset)
		    $model = SummaryDashboardPerSegment::model()->findByAttributes(array('is_current' => '1', 'segment_id' => $this->getOwner()->segment_id));
		    if (!SummaryDashboardPerSegment::UpdateCurrentDashboardAssetInformationBySegment($model, $this->getOwner()->segment_id, $this->getOwner(), (($last_status != null) ? $last_status->getStatusValue() : null), true, $error_msg))
			return false;
		    //change information for the old segment (decrease the information of asset)
		    $model = SummaryDashboardPerSegment::model()->findByAttributes(array('is_current' => '1', 'segment_id' => $this->getOwner()->asset_old_segment));
		    if (!SummaryDashboardPerSegment::UpdateCurrentDashboardAssetInformationBySegment($model, $this->getOwner()->asset_old_segment, $this->getOwner(), (($last_status != null) ? $last_status->getStatusValue() : null), false, $error_msg))
			return false;
		}

		//if the type of the asset is changed
		if ($this->getOwner()->type_of_asset_id != $this->getOwner()->old_type_of_asset) {
		    $last_status = $this->getOwner()->getLastStatus();
		    //change information for the old and new type of asset according to asset segment (the dashboard summary records that is related to asset segment)
		    $model = SummaryDashboardPerSegment::model()->findByAttributes(array('is_current' => '1', 'segment_id' => $this->getOwner()->segment_id));
		    if (!SummaryDashboardPerSegment::UpdateCurrentDashboardAssetInformationByAssetType($model, $this->getOwner(), $this->getOwner()->segment_id, $this->getOwner()->old_type_of_asset, $this->getOwner()->type_of_asset_id, (($last_status != null) ? $last_status->getStatusValue() : null), $this->getOwner()->old_status, $error_msg))
			return false;

		    //change information for the old and new type of asset according to asset segment (the total dashboard summary records)
		    $model = SummaryDashboardPerSegment::model()->findByAttributes(array('is_current' => '1', 'is_total' => '1'));
		    if (!SummaryDashboardPerSegment::UpdateCurrentDashboardAssetInformationByAssetType($model, $this->getOwner(), 'Total', $this->getOwner()->old_type_of_asset, $this->getOwner()->type_of_asset_id, (($last_status != null) ? $last_status->getStatusValue() : null), $this->getOwner()->old_status, $error_msg))
			return false;
		}


		if ($this->getOwner()->old_tid_id != $this->getOwner()->tid_id && $this->getOwner()->old_tid_id != null && $this->getOwner()->tid_id != null) {
		    $tid = Tid::model()->findByAttributes(array('tid_no' => $this->getOwner()->tid_id));
		    $old_segment_id = $tid->getOldSegmentInfoWithoutSpecificAsset($this->getOwner());
		    //update tid information for old segment (the tid may be one segment and converted to multi segment or vice versa or even stay one segment but the segment changed according to asset segment).
		    if (!SummaryDashboardPerSegment::updateTidRecordsByAssetSegment($this->getOwner(), 'update', $tid, (($old_segment_id != null) ? $old_segment_id['segment_id'] : null), true)) {
			$this->getOwner()->addError('id', $error_msg);
			return false;
		    }
		    //update tid information for new segment (the tid may be one segment and converted to multi segment or vice versa or even stay one segment but the segment changed according to asset segment).
		    if (!SummaryDashboardPerSegment::updateTidRecordsByAssetSegment($this->getOwner(), 'update', Tid::model()->findByAttributes(array('tid_no' => $this->getOwner()->old_tid_id)))) {
			$this->getOwner()->addError('id', $error_msg);
			return false;
		    }
		} else {
		    //if the tid of the asset is not changed..but asset segment and status affect tid information
		    if (!SummaryDashboardPerSegment::updateTidRecordsByAssetSegment($this->getOwner(), 'update')) {
			$this->getOwner()->addError('id', $error_msg);
			return false;
		    }
		}
	    }

	    parent::afterSave($event);
	    if (!($this->getOwner() instanceof Tid) && !($this->getOwner() instanceof TidStatus) && !($this->getOwner() instanceof Asset) && !($this->getOwner() instanceof AssetStatus))
		$this->transaction->commit();
	    return true;
	} catch (Exception $e) {
	    $this->getOwner()->addError('id', "We're Sorry...An error occured while updating the system dashboard, please contact the system admin");
	    if (!($this->getOwner() instanceof Tid) && !($this->getOwner() instanceof TidStatus) && !($this->getOwner() instanceof Asset) && !($this->getOwner() instanceof AssetStatus))
		$this->transaction->rollback();
	    return false;
	}
    }

    /**
     * This is responisble for opening transaction before deleting model <br/>
     * so that the model will not be deleted if there is any error while updating the dashboard<br/>
     */
    public function beforeDelete($event) {
	$allowedClasses = $this->allowedClasses;
	// Lets check if the whole class should be ignored
	if (sizeof($allowedClasses) > 0) {
	    if (array_search(get_class($this->getOwner()), $allowedClasses) === false)
		return true;
	}

	$this->transaction = Yii::app()->db->beginTransaction();
	return parent::beforeDelete($event);
    }

    /**
     * This is responisble for updating the dashboard for the models that affect the dashboard <br/>
     * and if there is no error , it will commit the transaction that is started in the beforeSave event <br/>
     * otherwise the transaction will be rollbacked <br/>
     *
     */
    public function afterDelete($event) {
	$allowedClasses = $this->allowedClasses;
	// Lets check if the whole class should be ignored
	if (sizeof($allowedClasses) > 0) {
	    if (array_search(get_class($this->getOwner()), $allowedClasses) === false)
		return true;
	}
	try {
	    $error_msg = Yii::t('default', "We're Sorry...An error occured while updating the system dashboard, please contact the system admin");
	    //==========================segment Proessing===================================
	    //if we delete a segment...its information will be removed from dashboard
	    if ($this->getOwner() instanceof Segment) {
		if (SummaryDashboardPerSegment::removeSummaryDashboardRecordBySegmentIDs($this->getOwner()->id) != -1) {
		    $this->getOwner()->addError('id', $error_msg);
		    $this->transaction->rollback();
		    return false;
		}
	    }


	    //=============================TID Processing===================================
	    //if we delete TID or TID status
	    if ($this->getOwner() instanceof Tid || $this->getOwner() instanceof TidStatus) {
		$tid = ($this->getOwner() instanceof Tid) ? $this->getOwner() : $this->getOwner()->tid;
		$tid_status = ($this->getOwner() instanceof Tid) ? null : $this->getOwner();
		$last_tid_status = $tid->getLastStatus(true);
		//if the status that is removed is the last status of the tid
		$condition = ($last_tid_status == null) ? true :
			(TidStatus::isEqual($tid_status, $last_tid_status) && $this->getOwner() instanceof TidStatus)
			//when remove the last status ..and the tid has other statues...it will no longer be the last status but we have to update tid information because the status is changed
			|| ($tid_status != null && $tid_status->id == $tid_status->old_ti_status_id);

		if ($condition || $this->getOwner() instanceof Tid) {
		    $dashboard_summary_records = SummaryDashboardPerSegment::getCurrentDashboardRecords();
		    if ($dashboard_summary_records != null) {
			//get the segment of the tid, to know exactly which record of the current dashboard summary will be affected by the modification
			$segment_id = null;
			$segment_name = 'Non Segment';
			//Segemnet info will contain segment id and name.
			$segment = $tid->getSegmentInfo();
			if ($segment != null) {
			    $segment_id = $segment['segment_id'];
			    $segment_name = ($segment['segment_name'] != null) ? (strpos($segment['segment_name'], ',') ? 'Multi Segment' : $segment['segment_name']) : 'Non Segment';
			}
			foreach ($dashboard_summary_records as $dashboard_summary_record) {
			    //here is the case where the we don't delete tid or its tid status
			    //here we delete asset and that affect tid status and tid segment
			    //so we need to update dashboard information that is related to the old segment of the tid if it's changed according to asset segment
			    //because the new segment information will be updated in the asset delete section
			    if ($this->getOwner() instanceof TidStatus && $this->getOwner()->is_updated_from_asset == true) {
				$old_tid_segment = ($this->getOwner()->old_tid_segment != null) ? (strpos($this->getOwner()->old_tid_segment, ',') ? 'Multi Segment' : $this->getOwner()->old_tid_segment) : 'Non Segment';
				if ($dashboard_summary_record->is_total == '1' || $old_tid_segment == $dashboard_summary_record->segment_name) {
				    if (!SummaryDashboardPerSegment::UpdateCurrentDashboardRecordsByTID($dashboard_summary_record, $tid, $tid_status, $error_msg)) {
					$this->getOwner()->addError('id', $error_msg);
					return false;
				    }
				    //update renewal stage information if there is any update in its information inside tid status
				    if ($tid_status != null)
					if ($tid_status->renewal_stage_id != $tid_status->old_renewal_stage_id || $tid_status->under_processing != $tid_status->old_under_processing) {
					    //if renewal stage id is changed or the under processing field changed according to delete tid ....we need to update renewal stage information
					    //if the old value of renewal stage is not null..
					    //that is mean that the value of under processing and renewal stage has a value so deleting tid will remove these information
					    if ($tid_status->old_renewal_stage_id != null)
						if (!SummaryDashboardPerSegmentAndRenewal::updateRenewalModelByAssetSegment($dashboard_summary_record->id, $tid_status->old_renewal_stage_id, false, $error_msg))
						    return false;

					    //if the new value of renewal stage is not null..
					    //that is mean that the value of under processing is Yes
					    //and the value of the renewal stage is not null
					    //otherwise if the new value is null ...only old value will be affected and that will remove the information of the renewal stage
					    if ($tid_status->renewal_stage_id != null)
						if (!SummaryDashboardPerSegmentAndRenewal::updateRenewalModelByAssetSegment($dashboard_summary_record->id, $tid_status->renewal_stage_id, true, $error_msg))
						    return false;
					}
				}
			    } else {
				//here the case of deleting tid or tid status
				//change only total column and the tid segment column
				if ($dashboard_summary_record->is_total == '1' || $segment_name == $dashboard_summary_record->segment_name) {
				    if (!SummaryDashboardPerSegment::UpdateCurrentDashboardRecordsByTID($dashboard_summary_record, $tid, $tid_status, $error_msg, 'delete', ($this->getOwner() instanceof Tid) ? true : false)) {
					$this->getOwner()->addError('id', $error_msg);
					$this->transaction->rollback();
					return false;
				    }
				    //here is the case of deleting tid status (not tid) and the tid status is the last one
				    //so we need to remove its information if there is no other status to the tid
				    //$tid_status is the tid status that is removed which was the last status and $last_tid_status is the tid status that  become the last status
				    //so we need to reduce $tid_status information and increase $last_tid_status information
				    if (!TidStatus::isEqual($tid_status, $last_tid_status) && $this->getOwner() instanceof TidStatus) {
					if ($tid_status != null)
					    if ($tid_status->renewal_stage_id != null)
						if (!SummaryDashboardPerSegmentAndRenewal::updateRenewalModelByAssetSegment($dashboard_summary_record->id, $tid_status->renewal_stage_id, false, $error_msg))
						    return false;
					//if we delete the last status of the tid and the tid has no other statues..then the new last status will become null
					if ($last_tid_status != null)
					    if ($last_tid_status->renewal_stage_id != null)
						if (!SummaryDashboardPerSegmentAndRenewal::updateRenewalModelByAssetSegment($dashboard_summary_record->id, $last_tid_status->renewal_stage_id, true, $error_msg))
						    return false;
				    }
				    else
				    if ($tid_status != null)
					if ($tid_status->renewal_stage_id != $tid_status->old_renewal_stage_id || $tid_status->under_processing != $tid_status->old_under_processing) {
					    if ($tid_status->old_renewal_stage_id != null)
						if (!SummaryDashboardPerSegmentAndRenewal::updateRenewalModelByAssetSegment($dashboard_summary_record->id, $tid_status->old_renewal_stage_id, false, $error_msg))
						    return false;
					    if ($tid_status->renewal_stage_id != null)
						if (!SummaryDashboardPerSegmentAndRenewal::updateRenewalModelByAssetSegment($dashboard_summary_record->id, $tid_status->renewal_stage_id, true, $error_msg))
						    return false;
					}
				}
			    }
			}
		    }
		}
	    }


	    //======================================Asset Processing===================================================
	    if (($this->getOwner() instanceof Asset) || $this->getOwner() instanceof AssetStatus) {
		$asset = ($this->getOwner() instanceof Asset) ? $this->getOwner() : $this->getOwner()->asset;
		$asset_status = ($this->getOwner() instanceof Asset) ? null : $this->getOwner();
		$dashboard_summary_records = SummaryDashboardPerSegment::getCurrentDashboardRecords();
		if ($dashboard_summary_records != null) {
		    foreach ($dashboard_summary_records as $dashboard_summary_record) {
			if ($dashboard_summary_record->is_total == '1' || $asset->segment_id == $dashboard_summary_record->segment_id) {
			    if (!SummaryDashboardPerSegment::UpdateCurrentDashboardRecordsByAsset($dashboard_summary_record->segment_name, $dashboard_summary_record, $asset, $asset_status, $error_msg, 'delete')) {
				$this->getOwner()->addError('id', $error_msg);
				$this->transaction->rollback();
				return false;
			    }
			}
		    }
		    //deleting asset will also affect tid so we need to update tid according to asset segment and status
		    if ($this->getOwner() instanceof Asset)
			if (!SummaryDashboardPerSegment::updateTidRecordsByAssetSegment($asset, 'delete')) {
			    $this->getOwner()->addError('id', $error_msg);
			    $this->transaction->rollback();
			    return false;
			}
		}
	    }


	    //===========================================Renewal Processing=====================================================
	    if ($this->getOwner() instanceof RenewalStage) {
		$renewal_dashboard_Summmary_models = SummaryDashboardPerSegmentAndRenewal::model()->findAllByAttributes(array('renewal_stage_id' => $this->getOwner()->id));
		if ($renewal_dashboard_Summmary_models != null) {
		    foreach ($renewal_dashboard_Summmary_models as $renewal_dashboard_Summmary_model) {
			if (!$renewal_dashboard_Summmary_model->delete()) {
			    $this->getOwner()->addError('id', $error_msg);
			    $this->transaction->rollback();
			    return false;
			}
		    }
		}
	    }


	    parent::afterDelete($event);

	    $this->transaction->commit();
	    return true;
	} catch (Exception $e) {
	    $this->getOwner()->addError('id', "We're Sorry...An error occured while updating the system dashboard, please contact the system admin");
	    $this->transaction->rollback();
	    return false;
	}
    }

}
?>
