<?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_and_renewal".
 *
 * The followings are the available columns in table 'summary_dashboard_per_segment_and_renewal':
 * @property integer $id
 * @property integer $summary_dashboard_per_segment_id
 * @property integer $renewal_stage_id
 * @property integer $tids_count
 *
 * The followings are the available model relations:
 * @property SummaryDashboardPerSegment $summaryDashboardPerSegment
 * @property RenewalStage $renewalStage
 * @property TidDetailedDashboard[] $tidDetailedDashboards
 */
class SummaryDashboardPerSegmentAndRenewal extends TidansDashboardActiveRecord {

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

    /**
     * @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('summary_dashboard_per_segment_id, renewal_stage_id, tids_count', 'required'),
//			array('summary_dashboard_per_segment_id, renewal_stage_id, tids_count', 'numerical', 'integerOnly'=>true),
//			// The following rule is used by search().
//			// @todo Please remove those attributes that should not be searched.
//			array('id, summary_dashboard_per_segment_id, renewal_stage_id, tids_count', 'safe', 'on'=>'search'),
	);
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
	// NOTE: you may need to adjust the relation name and the related
	// class name for the relations automatically generated below.
	return array(
	    'summaryDashboardPerSegment' => array(self::BELONGS_TO, 'SummaryDashboardPerSegment', 'summary_dashboard_per_segment_id'),
	    'renewalStage' => array(self::BELONGS_TO, 'RenewalStage', 'renewal_stage_id'),
	    'tidDetailedDashboards' => array(self::HAS_MANY, 'TidDetailedDashboard', 'summary_dashboard_per_segment_and_renewal_id'),
	);
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
	return array(
	    'id' => 'ID',
	    'summary_dashboard_per_segment_id' => 'Summary Dashboard Per Segment',
	    'renewal_stage_id' => 'Processing Stages',
	    'tids_count' => 'TIDs Count',
	    'total_renewal' => 'Total Processing Stages',
	);
    }

    /**
     * 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('summary_dashboard_per_segment_id', $this->summary_dashboard_per_segment_id);
	$criteria->compare('renewal_stage_id', $this->renewal_stage_id);
	$criteria->compare('tids_count', $this->tids_count);

	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 SummaryDashboardPerSegmentAndRenewal the static model class
     */
    public static function model($className=__CLASS__) {
	return parent::model($className);
    }

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

    /**
     * Returns thethe models related to specific summary dashboard per segment
     * @param Integer $id the id of the summary dashboard per segment
     * @return SummaryDashboardPerSegmentAndRenewal[] the models related to specific summary dashboard per segment
     */
    public static function getRenewalModelByDashboardSummaryID($id) {
	return SummaryDashboardPerSegmentAndRenewal::model()->findAllByAttributes(array('summary_dashboard_per_segment_id' => $id));
    }

    /**
     * Update Summary Dashboard renewal Models
     * @param Integer $id the id of the summary dashboard per segment
     * @return Boolean true if successfully updating summary dashboard renewal models, false otherwise
     */
    public static function updateRenewalModels($id, &$error_msg, $segment_condition) {
	$tid_model = VTidDashboard::model();
	$cr1 = new CDbCriteria();
	$cr1->select = 'count(*) as count,renewal_stage_id';
	$cr1->condition = $segment_condition;
	$cr1->group = 'renewal_stage_id';

	$count_array = array();

	$tid_renewal_data = $tid_model->commandBuilder->createFindCommand(
			$tid_model->tableName(), $cr1)->queryAll();
	$total_renewal = 0;
	if ($tid_renewal_data != null)
	    foreach ($tid_renewal_data as $data) {
		if (array_key_exists('renewal_stage_id', $data) && $data['renewal_stage_id'] != null) {
		    $count_array[$data['renewal_stage_id']] = $data['count'];
		    $total_renewal += $data['count'];
		}
	    }

	$summary_renewal_models = SummaryDashboardPerSegmentAndRenewal::getRenewalModelByDashboardSummaryID($id);
	if ($summary_renewal_models != null) {
	    foreach ($summary_renewal_models as $renewal) {
		if ($renewal->renewal_stage_id != null) {
		    $renewal->tids_count = array_key_exists($renewal->renewal_stage_id, $count_array) ? $count_array[$renewal->renewal_stage_id] : 0;
		}
		else
		    $renewal->tids_count = $total_renewal;
		if (!$renewal->save()) {
		    $error_msg = CHtml::errorSummary($renewal);
		    return false;
		}
	    }
	}
	return true;
    }

    /**
     * Update Summary Dashboard renewal Model by summary dashboard and renewal id
     * @param Integer $id the id of the summary dashboard per segment
     * @return Boolean true if successfully updating summary dashboard renewal models, false otherwise
     */
    public static function updateRenewalModelByAssetSegment($id, $renewal_stage_id, $is_increase, &$error_msg) {
	$summary_renewal_model = SummaryDashboardPerSegmentAndRenewal::model()->findByAttributes(array('summary_dashboard_per_segment_id' => $id, 'renewal_stage_id' => $renewal_stage_id));
	if ($summary_renewal_model != null) {
	    $summary_renewal_model->tids_count = ($is_increase) ? $summary_renewal_model->tids_count + 1 : $summary_renewal_model->tids_count - 1;
	    if (!$summary_renewal_model->save()) {
		$error_msg = CHtml::errorSummary($renewal);
		return false;
	    }
	}
	$summary_renewal_model = SummaryDashboardPerSegmentAndRenewal::model()->findByAttributes(array('summary_dashboard_per_segment_id' => $id, 'renewal_stage_id' => null));
	if ($summary_renewal_model != null) {
	    $summary_renewal_model->tids_count = ($is_increase) ? $summary_renewal_model->tids_count + 1 : $summary_renewal_model->tids_count - 1;
	    if (!$summary_renewal_model->save()) {
		$error_msg = CHtml::errorSummary($renewal);
		return false;
	    }
	}
//	if ($summary_renewal_models != null) {
//	    foreach ($summary_renewal_models as $renewal) {
//		if ($renewal->renewal_stage_id != null) {
//		    if ($renewal_stage_id == $renewal->renewal_stage_id)
//			$renewal->tids_count = array_key_exists($renewal->renewal_stage_id, $count_array) ? $count_array[$renewal->renewal_stage_id] : 0;
//		} else
//		    if($action == 'delete')
//		    $renewal->tids_count = $total_renewal;
//		if (!$renewal->save()) {
//		    $error_msg = CHtml::errorSummary($renewal);
//		    return false;
//		}
//	    }
//	}
	return true;
    }

    /**
     * Create Summary Dashboard renewal Models
     * @param Integer $dashboard_summary_id the id of the summary dashboard per segment
     * @param String $error_msg the error message if any error happend   
     * @return Boolean true if successfully updating summary dashboard renewal models, false otherwise
     */
    public static function createRenewalModels($dashboard_summary_id, &$error_msg, $segment_condition) {

//	$renewals = RenewalStage::getNamesForDropDown();
//	if ($renewals != null) {
//	    foreach ($renewals as $id => $renewal) {
//		$renewal_model = new SummaryDashboardPerSegmentAndRenewal();
//		$renewal_model->summary_dashboard_per_segment_id = $dashboard_summary_id;
//		$renewal_model->renewal_stage_id = $id;
//		$renewal_model->tids_count = "(select count(*) from v_tid where last_status_renewal_stage_id = " . $id . $segment_condition . ")";
//		if (!$renewal_model->save()) {
//		    $error_msg = CHtml::errorSummary($renewal_model);
//		    return false;
//		}
//	    }
//	}
//		foreach ($renewals as $id => $renewal) {
//		    $renewal_model = new SummaryDashboardPerSegmentAndRenewal();
//		    $renewal_model->summary_dashboard_per_segment_id = $dashboard_summary_id;
//		    $renewal_model->renewal_stage_id = $id;
//		    $renewal_model->tids_count = "(select count(*) from v_tid where last_status_renewal_stage_id = " . $id . $segment_condition . ")";
//		    if (!$renewal_model->save()) {
//			$error_msg = CHtml::errorSummary($renewal_model);
//			return false;
//		    }
//		}
	$renewals = RenewalStage::getNamesForDropDown();

	$tid_model = VTidDashboard::model();
	$cr1 = new CDbCriteria();
	$cr1->select = 'count(*) as count,renewal_stage_id';
	$cr1->condition = $segment_condition;
	$cr1->group = 'renewal_stage_id';

	$tid_renewal_data = $tid_model->commandBuilder->createFindCommand(
			$tid_model->tableName(), $cr1)->queryAll();
	if ($renewals != null) {

	    $total_renewal = 0;
	    foreach ($renewals as $id => $renewal) {
		$renewal_model = new SummaryDashboardPerSegmentAndRenewal();
		$renewal_model->summary_dashboard_per_segment_id = $dashboard_summary_id;
		$renewal_model->renewal_stage_id = $id;
		$renewal_model->tids_count = 0;
		if ($tid_renewal_data != null) {
		    foreach ($tid_renewal_data as $data) {
			if ($data['renewal_stage_id'] == $id) {
			    $renewal_model->tids_count = $data['count'];
			    $total_renewal += $data['count'];
			}
		    }
		    if (!$renewal_model->save()) {
			$error_msg = CHtml::errorSummary($renewal_model);
			return false;
		    }
		} else {
		    $renewal_model = new SummaryDashboardPerSegmentAndRenewal();
		    $renewal_model->summary_dashboard_per_segment_id = $dashboard_summary_id;
		    $renewal_model->renewal_stage_id = $id;
		    $renewal_model->tids_count = 0;
		    if (!$renewal_model->save()) {
			$error_msg = CHtml::errorSummary($renewal_model);
			return false;
		    }
		}
	    }

	    $renewal_model = new SummaryDashboardPerSegmentAndRenewal();
	    $renewal_model->summary_dashboard_per_segment_id = $dashboard_summary_id;
	    $renewal_model->renewal_stage_id = 'null';
	    $renewal_model->tids_count = $total_renewal;
	    if (!$renewal_model->save()) {
		$error_msg = CHtml::errorSummary($renewal_model);
		return false;
	    }
	}
	return true;
    }

    /**
     * Create Summary Dashboard renewal row
     * @param Integer $dashboard_summary_id the id of the summary dashboard per segment
     * @param Integer $renewal_Stage_id the id of the renewal stage
     * @param String $error_msg the error message if any error happend
     * @return Boolean true if successfully updating summary dashboard renewal row, false otherwise
     */
    public static function createRenewalRow($renewal_Stage_id, &$error_msg) {
	$dashboard_summary_records = SummaryDashboardPerSegment::getCurrentDashboardRecords();
	if ($dashboard_summary_records != null) {
	    foreach ($dashboard_summary_records as $dashboard_summary_record) {
		$segment = $dashboard_summary_record->segment_name;
		$segment_condition = '';
		$and = ($segment == 'Total') ? '' : ' and ';
		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 . "'";
		$renewal_model = new SummaryDashboardPerSegmentAndRenewal();
		$renewal_model->summary_dashboard_per_segment_id = $dashboard_summary_record->id;
		$renewal_model->renewal_stage_id = $renewal_Stage_id;
		$renewal_model->tids_count = "(select count(*) from v_tid where last_status_renewal_stage_id = " . $renewal_Stage_id . $and . $segment_condition . ")";
		if (!$renewal_model->save()) {
		    $error_msg = CHtml::errorSummary($renewal_model);
		    return false;
		}
	    }
	}
	return true;
    }

}
