<?php

class SchedulerCommand extends CConsoleCommand {

    public function getHelp() {
	return <<<EOD
USAGE
  Scheduler

DESCRIPTION
  This command responsible for call action which save data consistency .

EOD;
    }
	
	
	 /**
     * The following function is used when the system sync the persons (LDAP persons) with LDAP,
     * Check if any LDAP info is changed and reflect that change to system LDAP Persons
     */
    public function actionSyncLDAPInfo() {

        // Abort The Transaction If There Is Validate Error Or Connection To LDAP Error
        Yii::log('Start Syncing LDAP Persons', 'info', 'system.Scheduler.SyncingLDAPInfo');
        $transaction = Yii::app()->db->beginTransaction();
        $isRollBack = false;
        try {
            $persons = Person::getLDAPPersons();
            foreach ($persons as $Person_model) {
                $error_message = LDAP::getPersonByAlias($Person_model->number, $LDAPPerson);

                if ($error_message == '') {
                    $Person_model->name = $LDAPPerson['cn'];
                    $manager = $LDAPPerson['manager'];
                    if ($manager) {
                        // Searching for manager information at LDAP System and set manager value at sysytem as 'cn-number'
                        $error_message = LDAP::getPersonByCn($manager, $LDAP_manager);
                        if ($LDAP_manager != null) {
                            $Person_model->manager = $LDAP_manager['cn']. "-". $LDAP_manager['employeenumber'];
                        } else {
                            Yii::log('RollBack ', 'error', 'system.Scheduler.SyncingLDAPInfo');
                            Yii::log('Error Message :' . $error_message.$manager, 'error', 'system.Scheduler.SyncingLDAPInfo');
                            $isRollBack = true;
                            $transaction->rollback();
                            break;
                        }
                    } else {
                        $Person_model->manager = "";
                    }

                    $Person_model->person_type_id = PersonType::getLDAPTypeID($LDAPPerson['employeetype']);
                    $Person_model->email = $LDAPPerson['mail'];
                    $Person_model->mobile = $LDAPPerson['mobile'];
                    $Person_model->alias = $LDAPPerson['alias'];
                    if (!$Person_model->save()) {
                        Yii::log('RollBack ', 'error', 'system.Scheduler.SyncingLDAPInfo');
                        Yii::log('Error Message :' . CHtml::errorSummary($Person_model), 'error', 'system.Scheduler.SyncingLDAPInfo');
                        $isRollBack = true;
                        $transaction->rollback();
                        break;
                    }
                } else if ($error_message == yii::t('default', 'Cannot connect to the LDAP server, please contact the system administrator.')) {
                    Yii::log(' RollBack ', 'error', 'system.Scheduler.SyncingLDAPInfo');
                    Yii::log('Error Message :' . $error_message, 'error', 'system.Scheduler.SyncingLDAPInfo');
                    $isRollBack = true;
                    $transaction->rollback();
                    break;
                }
            }
            If (!$isRollBack) {
                $transaction->commit(); // commit transactions now
                Yii::log('End Syncing LDAP Persons', 'info', 'system.Scheduler.SyncingLDAPInfo');
                return;
            }
        } catch (Exception $ex) {
            $transaction->rollback();
            Yii::log(' RollBack ', 'error', 'system.Scheduler.SyncingLDAPInfo');
            Yii::log($ex->__toString(), 'error', 'system.Scheduler.SyncingLDAPInfo');            
            return;
        }
    }


    /*
     * The following function is used when the system sync the persons (LDAP persons) with LDAP,
     * the direction of the syncing operation will be from the system to the directory
     */

    public function actionSyncingPersons() {
	// Begin Transaction For Add ALL Person In Excel File AS LDAP Person In System
	// Abort The Transaction If There Is Validate Error Or Connection To LDAP Error
	Yii::log('Start Syncing Persons', 'info', 'system.Scheduler.SyncingPersons');
	$transaction = Yii::app()->db->beginTransaction();
	$isRollBack = false;
	try {
	    $persons = Person::getLDAPPersons();
	    foreach ($persons as $Person_model) {
//                 Yii::log(' Person: ' . $Person_model->name, 'info', 'system.Scheduler.SyncingPersons');
//                 Yii::log(' Status: ' . $Person_model->status, 'info', 'system.Scheduler.SyncingPersons');
		$error_message = LDAP::getPersonByAlias($Person_model->alias, $LDAPPerson);
		if ($error_message == yii::t('default', 'There is no result matching the requesting criteria')) {
		    if ($Person_model->status == 'Active') {
			$Person_model->status = 'Inactive';
			if ($Person_model->save()) {
			    //Send Email to the deactivated persons in the "SyncPerson"
			    if ($Person_model->receive_emails == 1)
				LSMSMail::sendMail('LSMS - Your Information Deactivated ', 'Dear ' . $Person_model->name . ',<br/>Your information has been deactivated on the life support management system because your information is no longer available on the SLB LDAP directory. <br/>Please note that your active badges will be deactivated accordingly.', $Person_model->email, null, null);
//                             Yii::log(' New Status: ' . $Person_model->status, 'info', 'system.Scheduler.SyncingPersons');
			    if (isset($Person_model->badges) && count($Person_model->badges) > 0) {
				Person::updateBadgesStatus($Person_model->badges, 'Active', 'Inactive');
//                                 Yii::log(' Badges Number: ' . count($Person_model->badges), 'info', 'system.Scheduler.SyncingPersons');
			    }
			} else {
			    Yii::log('RollBack ', 'error', 'system.Scheduler.SyncingPersons');
			    Yii::log('Error Message :' . CHtml::errorSummary($Person_model), 'error', 'system.Scheduler.SyncingPersons');
			    $isRollBack = true;
			    $transaction->rollback();
			    break;
			}
		    }
		} else if ($error_message == yii::t('default', 'Cannot connect to the LDAP server, please contact the system administrator.')) {
		    Yii::log(' RollBack ', 'error', 'system.Scheduler.SyncingPersons');
		    Yii::log('Error Message :' . $error_message, 'error', 'system.Scheduler.SyncingPersons');
		    $isRollBack = true;
		    $transaction->rollback();
		    break;
		}
	    }
	    If (!$isRollBack) {
		$transaction->commit(); // commit transactions now
		Yii::log(' Commit Done ', 'info', 'system.Scheduler.SyncingPersons');
		return;
	    }
	} catch (Exception $ex) {
	    $transaction->rollback();
	    Yii::log(' RollBack ', 'error', 'system.Scheduler.SyncingPersons');
	    Yii::log($ex->__toString(), 'error', 'system.Scheduler.SyncingPersons');
	    return;
	}
    }

    /*
     * The following function is called when the system check for
     * and deactivate (change the badge status to inactive) the expired badges
     */

    public function actionDeactiveExpiredBadges() {
	Yii::log('Start Deactive Expired Badges', 'info', 'system.Scheduler.DeactiveExpiredBadges');
	try {
	    $badges = Badge::model()->findAllByAttributes(
			    array(),
			    $condition = 'status = "Active" ');

	    foreach ($badges as $badge_model) {
//                 Yii::log('Badge Number : ' . $badge_model->number . ' Badge Status : ' . $badge_model->status, 'info', 'system.Scheduler.DeactiveExpiredBadges');
		if ($badge_model->isExpired()) {
		    $badge_model->status = 'Inactive';
		    if ($badge_model->save()) {
//                         Yii::log('Deactive Status to  : ' . $badge_model->status, 'info', 'system.Scheduler.DeactiveExpiredBadges');
		    } else {
			Yii::log('Error Message :' . CHtml::errorSummary($badge_model), 'error', 'system.Scheduler.DeactiveExpiredBadges');
		    }
		}
//                 else
//                 {
//                     Yii::log('Not Expired ', 'info', 'system.Scheduler.SynciDeactiveExpiredBadgesngPersons');
//                 }
	    }
	    Yii::log('End Deactive Expired Badges', 'info', 'system.Scheduler.DeactiveExpiredBadges');
	} catch (Exception $ex) {
	    Yii::log('Error :' . $ex->__toString(), 'error', 'system.Scheduler.DeactiveExpiredBadges');
	    return;
	}
    }

    /*
     * The following function is called when the system check if there is a badge that will be expired
     *  after a few days (configured by the facility admin),And then notifiy person and his facility admin
     */

    public function actionNotifyExpiredBadges() {
	// Begin Transaction For Add ALL Person In Excel File AS LDAP Person In System
	// Abort The Transaction If There Is Validate Error Or Connection To LDAP Error
	Yii::log('Start Notify Expired Badges', 'info', 'system.Scheduler.NotifyExpiredBadges');

	try {
	    $now_date = date("Y-m-d");
	    $badges = Badge::model()->with('type')->findAllByAttributes(array(),
			    $condition = '(t.status = "Active") and (type.notify_before_badge_expire = 1) and (DATEDIFF(activation_end_date,\'' . $now_date . '\') <= type.start_notify_from_x_days_before_expiry) ');
	    foreach ($badges as $badge_mode) {
		if (!$badge_mode->isExpired()) {
		    $number = $badge_mode->number;
		    $activation_end_date = $badge_mode->activation_end_date;
		    $notify_before_badge_expire = $badge_mode->type->notify_before_badge_expire;
		    $start_notify_from_x_days_before_expiry = $badge_mode->type->start_notify_from_x_days_before_expiry;
		    if ($badge_mode->person != null) {
			$person_model = $badge_mode->person;
			$name = $person_model->name;
			$person_department_id = $person_model->department->id;
			$department_model = Department::model()->findByPk($person_department_id);
			$location_id = $department_model->location->id;
			$users = User::model()->findAllByAttributes(array('location_id' => $location_id, 'status' => 'Active'));
			//Send Email to person wich his badge will be expired
			if ($person_model->receive_emails == 1)
			    LSMSMail::sendMail('LSMS - Badge Will Expire Shortly', 'Dear ' . $name . ',<br/>Your badge (' . $number . ') will expire on (' . $activation_end_date . ').<br/><br/>If you want to stop receiving this email please contact the facility admin.', $person_model->email, null, null);
			foreach ($users as $user_model) {
			    if (($user_model->role == 'Facility Admin') || ($user_model->role == 'System Admin')) {
				$user_email = $user_model->email;
				$user_identifier = $user_model->identifier;
				//Send Email to person's Facility Admin and System Admin
				LSMSMail::sendMail('LSMS - Badge Will Expire Shortly', 'Dear ' . $user_identifier . ',<br/>The badge (' . $number . ') will expire on (' . $activation_end_date . ').', $user_email, null, null);
			    }
			}
		    }
		}
	    }
	    Yii::log('End Notify Expired Badges', 'info', 'system.Scheduler.NotifyExpiredBadges');
	} catch (Exception $ex) {
	    Yii::log(' RollBack ', 'error', 'system.Scheduler.NotifyExpiredBadges');
	    Yii::log($ex->__toString(), 'error', 'system.Scheduler.NotifyExpiredBadges');
	    return;
	}
    }

    public function actionSendReport() {
	Yii::log('Start Send Report ', 'info', 'system.Scheduler.SendReport');
	try {
	    $columns = array(
		array('header' => 'Ticket Type', 'name' => 'ticket_type'),
		array('header' => 'Department', 'name' => 'department'),
		array('header' => 'Accounting Unit', 'name' => 'accounting_unit'),
		array('header' => 'System User', 'name' => 'user_name'),
		array('header' => 'Person', 'name' => 'person'),
		array('header' => 'POS', 'name' => 'pos'),
		array('header' => 'Badge', 'name' => 'badge', 'type' => 'text'),
		array('header' => 'Schedule', 'name' => 'schedule'),
		array('header' => 'Number Of Tickets', 'name' => 'number_of_tickets'),
	    );
	    $from_date = date('Y-m-d', strtotime('first day of last month'));
	    $to_date = date('Y-m-d', strtotime('last day of last month'));
	    $locations = Location::getAll('Active');
	    foreach ($locations as $location_model) {
		$location_id = $location_model->id;
		//Export Excel File
		$model = new VReportTicketSummaryForDepartment('search');
		$model->unsetAttributes();
		$model->location = $location_id;
		$model->department = '';
		$model->from_date = $from_date;
		$model->to_date = $to_date;
		$data = $model->search();
		$data->pagination->pageSize = $data->getTotalItemCount();
		$file_name = Yii::t('default', 'Ticket Summary For Department in location (' . $location_model->code . ')');
		$this->toExcel($data, $columns, $file_name, array('creator' => 'LSMS',), 'Excel5', true);
		//Get Facility admin and finance in Location
		$users = User::model()->findAllByAttributes(array('location_id' => $location_id, 'status' => 'Active'));
		foreach ($users as $user_model) {
		    if (($user_model->role == 'Facility Admin') || ($user_model->role == 'Finance')) {
			LSMSMail::sendMail('LSMS Reports - ' . $file_name, 'Dear ' . $user_model->identifier . ',<br/>The attached file is the (Tickets Summary For Department) report for the period (' . $from_date . ', ' . $to_date . ').', $user_model->email, null, dirname(__FILE__) . '/../upload/reports/' . $file_name . '.xls');
		    }
		}
		//Remove exported file
		unlink(dirname(__FILE__) . '/../upload/reports/' . $file_name . '.xls');

		//Get Departments In location
		$departments = Department::model()->findAllByAttributes(array('status' => 'Active', 'location_id' => $location_id));
		foreach ($departments as $department_model) {
		    $department_id = $department_model->id;
		    $persons = Person::model()->findAllByAttributes(array('status' => 'Active', 'is_manager' => 1, 'receive_emails' => 1, 'department_id' => $department_id));
		    //Export Excel File For each Department
		    $model = new VReportTicketSummaryForDepartment('search');
		    $model->unsetAttributes();
		    $model->location = $location_id;
		    $model->department = $department_id;
		    $model->from_date = $from_date;
		    $model->to_date = $to_date;
		    $data = $model->search();
		    $data->pagination->pageSize = $data->getTotalItemCount();
		    $file_name = Yii::t('default', 'Ticket Summary For Department (' . $department_model->name . ')');
		    $this->toExcel($data, $columns, $file_name, array('creator' => 'LSMS',), 'Excel5', true);
		    //Get Manager in Department
		    foreach ($persons as $person_model) {
			LSMSMail::sendMail('LSMS Reports - ' . $file_name, 'Dear ' . $person_model->name . ',<br/>The attached file is the (Tickets Summary For Department) report for the period (' . $from_date . ', ' . $to_date . ').<br/><br/>If you want to stop receiving this email please contact the facility admin.', $person_model->email, null, dirname(__FILE__) . '/../upload/reports/' . $file_name . '.xls');
		    }
		    //Remove exported file
		    unlink(dirname(__FILE__) . '/../upload/reports/' . $file_name . '.xls');
		}
	    }
	    Yii::log('End Send Report ', 'info', 'system.Scheduler.SendReport');
	} catch (Exception $ex) {
	    Yii::log(' RollBack ', 'error', 'system.Scheduler.SendReport');
	    Yii::log($ex->__toString(), 'error', 'system.Scheduler.SendReport');
	    return;
	}
    }

    /*
     * the following function is called when the system make full Backup
     */

    public function actionFullBackup() {
	Yii::log('Start Full Backup ', 'info', 'system.Scheduler.FullBackup');
	try {
	    $settings_array = Setting::getSettingsArray();
	    $backupDataBase_path = (isset($settings_array["backup_file_path"]) && ($settings_array["backup_file_path"] != null) && ($settings_array["backup_file_path"] != '')) ? $settings_array["backup_file_path"] : '/../backup/';
	    $mysqldump_file_path = Yii::app()->params['mysqldump_file_path'];
	    $backupDataBase_host = Yii::app()->db->host;
	    $backupDataBase_user = Yii::app()->db->username;
	    $backupDataBase_pass = Yii::app()->db->password;	    
	    $backupDataBase_db = Yii::app()->db->dbname;
	    Yii::log('User_name '.$backupDataBase_user.' Password '.$backupDataBase_pass.'DB '.$backupDataBase_db, 'info', 'system.Scheduler.FullBackup');
	    $file_name = date('Y.m.d_H.i.s') . '__FullBackup.sql';
	    $command = "$mysqldump_file_path/mysqldump -h " . $backupDataBase_host . " -u " . $backupDataBase_user . " -p" . $backupDataBase_pass . " --no-create-db --no-create-info " . $backupDataBase_db . ' > "' . $backupDataBase_path . "/$file_name" . '"';
	    Yii::log($command, 'info', 'system.Scheduler.FullBackup');
	    exec($command);
	    Yii::log('End Full Backupt ', 'info', 'system.Scheduler.FullBackup');
	} catch (Exception $ex) {
	    Yii::log(' RollBack ', 'error', 'system.Scheduler.FullBackup');
	    Yii::log($ex->__toString(), 'error', 'system.Scheduler.FullBackup');
	    return;
	}
    }

    /*
     * the following function is called when the system make monthly Backup
     * the backup file contains the inserted data in last month (example: if we are in April the
     * backup file contain data wich inserted from 01/03 until  31/03 )
     */

    public function actionMonthlyBackup() {
	Yii::log('Start Monthly Backup ', 'info', 'system.Scheduler.MonthlyBackup');
	try {
	    $backupDataBase = new BackupDataBase;
	    $settings_array = Setting::getSettingsArray();
	    $backupDataBase->path = (isset($settings_array["backup_file_path"]) && ($settings_array["backup_file_path"] != null) && ($settings_array["backup_file_path"] != '')) ? $settings_array["backup_file_path"] : '/../backup/';
	    $from_date = date('Y-m-d H:i:s', strtotime('first day of last month'));
	    $to_date = date('Y-m-d H:i:s', strtotime('last day of last month'));
	    $backupDataBase->partialBackup(false, true, $from_date, $to_date, '_OneMonthBackup');
	    Yii::log('End Monthly Backupt ', 'info', 'system.Scheduler.MonthlyBackup');
	} catch (Exception $ex) {
	    Yii::log(' RollBack ', 'error', 'system.Scheduler.MonthlyBackup');
	    Yii::log($ex->__toString(), 'error', 'system.Scheduler.MonthlyBackup');
	    return;
	}
    }

    /*
     * the following function is called when the system make weekly Backup
     * the backup file contains the inserted data in last week (means: backup file
     * contain data wich inserted from lasuntil  31/03 )
     */

    public function actionDailyBackup() {
	Yii::log('Start Weekly Backup ', 'info', 'system.Scheduler.WeeklyBackup');
	try {
	    $backupDataBase = new BackupDataBase;
	    $settings_array = Setting::getSettingsArray();
	    $backupDataBase->path = (isset($settings_array["backup_file_path"]) && ($settings_array["backup_file_path"] != null) && ($settings_array["backup_file_path"] != '')) ? $settings_array["backup_file_path"] : '/../backup/';
//            $backupDataBase->path = dirname(__FILE__) . '/../backup/';
	    $from_date = date('Y-m-d H:i:s', strtotime('yesterday'));
	    $to_date = date('Y-m-d H:i:s');

	    $backupDataBase->partialBackup(false, true, $from_date, $to_date, '_OneDayBackup');
	    Yii::log('End Weekly Backupt ', 'info', 'system.Scheduler.WeeklyBackup');
	} catch (Exception $ex) {
	    Yii::log(' RollBack ', 'error', 'system.Scheduler.WeeklyBackup');
	    Yii::log($ex->__toString(), 'error', 'system.Scheduler.WeeklyBackup');
	    return;
	}
    }

    // for excel export extension
    public function behaviors() {
	return array(
	    'eexcelview' => array(
		'class' => 'ext.eexcelview.EExcelBehavior',
	    ),
	);
    }

}

