<?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
 */

class BadgeController extends Controller
{


    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';

    /**
     * @return array action filters
     */
    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules()
    {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('index', 'view', 'create', 'update', 'delete',
                    'addBatch', 'download', 'assignPersonToBadge', 'assignBadgeToPerson', 'batchExtendBadges',
                    'getMaxServedMeals', 'unAssignBadge', 'renew', 'getActivatedPeriod', 'ExportToExcel', 'AddAndAssign'),
                'roles' => array('System Admin', 'Facility Admin', 'Super Admin'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /*
     * The Following Action is responsible for taking the selected person value (formatted as : "name-number") then split it and
     * search for people by his number and get the max served meals  for writing it to text filed
     */

    public function actionGetMaxServedMeals($person_id, $badge_number)
    {
        try
        {
            $max_served_meals = 0;
            //Check if the person_id is number
            if (is_numeric($person_id))
            {
                $person_model = Person::model()->findByPk($person_id);
            }
            else
            {
                // Split between name and number
                $array_attributes = explode("-", $person_id);
                // Take number cell
                $person_number = end($array_attributes);
                $person_model = Person::model()->findByAttributes(array('number' => $person_number));
            }
            $badge = Badge::model()->findByAttributes(array('number' => $badge_number));
            $max_served_meals = Badge::getMaxServedMeals($person_model, $badge);
            echo $max_served_meals;
        }
        catch (Exception $exc)
        {
            echo"";
        }
    }

    /*
     * The Following Action is responsible for taking the selected Badge Number value and Start Activation Date
     * then get Activation Period and set End Activation Date
     */

    public function actionGetActivatedPeriod($start_date, $badge_number)
    {
        try
        {
            $end_date = "";
            if ($badge_number != "")
            {
                $badge = Badge::model()->findByAttributes(array('number' => $badge_number));
                $activation_start_date = date($start_date);
                $activation_period = $badge->type->activation_period;
                $end_date = date("Y-m-d", strtotime(date("Y-m-d", strtotime($activation_start_date)) . " +$activation_period month"));
            }
            echo $end_date;
        }
        catch (Exception $exc)
        {
            echo"";
        }
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate()
    {
        $model = new Badge;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Badge']))
        {
            $model->attributes = $_POST['Badge'];
            if ($model->save())
            {
                Yii::app()->user->setFlash('success', Yii::t('default', 'The Badge has been added successfully'));
                $this->redirect(array('view', 'id' => $model->id));
            }
            else
            {
                Yii::app()->user->setFlash('error', CHtml::errorSummary($model));
            }
        }

        $this->render('create', array(
            'model' => $model,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id, $person_id=null)
    {
        $model = $this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);
        $number = $model->number;
        $type = $model->type_id;
        if (isset($_POST['Badge']))
        {
            $model->attributes = $_POST['Badge'];
            // Cannot updtae number and type badge have relation with tickets
            if (isset($model->tickets) && (count($model->tickets) > 0))
            {
                if ($number != $model->number)
                {
                    Yii::app()->user->setFlash('error', Yii::t('default', 'You cannot update badge have issued ticket based on it '));
                    $model->number = $number;
                }
                else if ($type != $model->type_id)
                {
                    Yii::app()->user->setFlash('error', Yii::t('default', 'You cannot update badge have issued ticket based on it '));
                    $model->type_id = $type;
                }
                else
                {
                    if ($model->save())
                    {
                        Yii::app()->user->setFlash('success', Yii::t('default', 'The Badge has been updated successfully'));
                        if ($person_id == null)
                        {
                            $this->redirect(array('view', 'id' => $model->id));
                        }
                        else
                        {
                            $this->redirect(array('/person/manageBadges', 'id' => $person_id));
                        }
                    }
                    else
                    {
                        Yii::app()->user->setFlash('error', CHtml::errorSummary($model));
                    }
                }
            }
            else
            {
                if ($model->save())
                {
                    Yii::app()->user->setFlash('success', Yii::t('default', 'The Badge has been updated successfully'));
                    if ($person_id == null)
                    {
                        $this->redirect(array('view', 'id' => $model->id));
                    }
                    else
                    {
                        $this->redirect(array('/person/manageBadges', 'id' => $person_id));
                    }
                }
                else
                {
                    Yii::app()->user->setFlash('error', CHtml::errorSummary($model));
                }
            }
        }

        $this->render('update', array(
            'model' => $model,
            'person_id' => $person_id,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id)
    {
        $model = $this->loadModel($id);
        $success_msg = Yii::t('default', 'The Badge ({n}) has been deleted successfully ', $model->number);
        $failer_msg = Yii::t('default', 'You cannot delete this element because it is referenced by other element');
        try
        {
            $model->delete();
            if (!isset($_GET['ajax']))
            { // Check Wether the data grid will be updated through AJAX or Not
                Yii::app()->user->setFlash('success', $success_msg);
            }
            else
            {
                Yii::app()->user->setFlash('success', $success_msg);
                echo "<div class='flash-msg'>" . "<br>";
                $this->widget('bootstrap.widgets.TbAlert');
                echo "</div>";
            }
        }
        catch (CDbException $e)
        { // here the item is referenced by another item
            if (!isset($_GET['ajax']))
            {
                Yii::app()->user->setFlash('error', $failer_msg);
            }
            else
            {
                Yii::app()->user->setFlash('error', $failer_msg);
                echo "<div class='flash-msg'>" . "<br>";
                $this->widget('bootstrap.widgets.TbAlert');
                echo "</div>";
            }
        }
    }

    /**
     * Lists all models.
     */
    public function actionIndex()
    {
        $model = new Badge('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['Badge']))
            $model->attributes = $_GET['Badge'];

        $this->render('index', array(
            'model' => $model,
        ));
    }

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

    public function actionExportToExcel()
    {
        $model = new Badge('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['Badge']))
            $model->attributes = $_GET['Badge'];


        $columns = array(
            array('header' => 'Number', 'name' => 'number'),
            array('header' => 'Badge Type', 'name' => 'type.name'),
            array('header' => 'Activation Start Date', 'name' => 'activation_start_date'),
            array('header' => 'Activation End Date', 'name' => 'activation_end_date'),
            array('header' => 'Meals Number', 'name' => 'max_served_meals'),
            array('header' => 'Person Geomarket', 'name' => 'person.department.location.geomarket.name'),
            array('header' => 'Person Location', 'name' => 'person.department.location.code'),
            array('header' => 'Person Department', 'name' => 'person.department.name'),
            array('header' => 'Person Name', 'name' => 'person.name'),
            array('header' => 'Person Email', 'name' => 'person.email'),
            array('header' => 'Status', 'name' => 'status'),
        );
        $data = $model->with(array('person', 'type'))->search();
        $data->pagination->pageSize = $data->getTotalItemCount();
        $this->toExcel($data, $columns, Yii::t('default', 'Badges'), array('creator' => 'LSMS',), 'Excel5');
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id)
    {
        $model = $this->loadModel($id);
        if (($model->status == 'Free') || (isset($model->person_id) && ($model->person_id == null)) || (!isset($model->person_id)))
        {
            $this->render('viewFreeBadge', array(
                'model' => $this->loadModel($id),
            ));
        }
        else
        {
            $this->render('view', array(
                'model' => $this->loadModel($id),
            ));
        }
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id)
    {
        $model = Badge::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model)
    {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'badge-form')
        {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    /**
     * The Following Action Responsible for Upload Excel file to server and
     * Extend end activation data for badges in file .
     */
    public function actionBatchExtendBadges()
    {
        $file_model = new File;

        if (isset($_POST['File']))
        {
            $file_model->attributes = $_POST['File'];
            // get file name and upload it to server at foler /protected/upload/ldapbatch
            $file_model->file = CUploadedFile::getInstance($file_model, 'file');
            if (isset($file_model->file) && ($file_model->file != null))
            {
                $formatted_file_name = $file_model->file->name;
                $file_name = str_replace(":", "_", $formatted_file_name); // the ":" is not allowed in the file name
                $file_model->file->saveAs('./protected/upload/extendbadges/' . $file_name);
                //Read Excel File and Fetch data
                $filePath = './protected/upload/extendbadges/' . $file_name;
                Yii::import('ext.phpexcelreader.JPhpExcelReader');
                $data = new JPhpExcelReader();
                 $data->Spreadsheet_Excel_Reader($filePath);
                // Begin DataBase Transaction
                $transaction = Yii::app()->db->beginTransaction();
                $isRollBack = false;
                try
                {
                    for ($i = 2; $i <= count($data->sheets[0]['cells']); $i++)
                    {
                        //check if the row is empty
                        $is_empty = TRUE;
                        for ($j = 1; $j <= 2; $j++)
                        {
                            if (isset($data->sheets[0]['cells'][$i][$j]) && ($data->sheets[0]['cells'][$i][$j] != ""))
                            {
                                $is_empty = FALSE;
                                break;
                            }
                        }

                        if (!$is_empty)
                        {
                            $number = isset($data->sheets[0]['cells'][$i][1]) ? $data->sheets[0]['cells'][$i][1] : null;
                            $extend_activation_period = isset($data->sheets[0]['cells'][$i][2]) ? $data->sheets[0]['cells'][$i][2] : "";
                            if ($number != null)
                            {
                                if ($extend_activation_period != null)
                                {
                                    if (is_numeric($extend_activation_period))
                                    {
                                        $model = Badge::model()->findByAttributes(array('number' => $number));
                                        if ($model != null)
                                        {
                                            if (($model->status != 'Active' ) && ( $model->status != 'Inactive' ))
                                            {
                                                $isRollBack = true;
                                                $transaction->rollback();
                                                Yii::app()->user->setFlash('error', Yii::t('default', 'The Badge (number)space cannot be extended because its status is (badge_status) .', array('number' => $number, 'badge_status' => $model->status)));
                                                break;
                                            }
                                            else
                                            {

                                                $activation_period = $model->type->activation_period;
                                                if ($activation_period < $extend_activation_period)
                                                {
                                                    $isRollBack = true;
                                                    $transaction->rollback();
                                                    Yii::app()->user->setFlash('error', Yii::t('default', 'The Activation Period  for the badge (number) cannot exceed badge_activation_period month(s)', array('number' => $number, 'badge_activation_period' => $activation_period)));
                                                    break;
                                                }
                                                else
                                                {
                                                    $now_date = date("Y-m-d"); // current date
                                                    $activation_end_date = date("Y-m-d", strtotime(date("Y-m-d", strtotime($model->activation_end_date)) . " +$extend_activation_period month"));
                                                    $model->activation_end_date = $activation_end_date;

                                                    $now_datetime = new DateTime($now_date);
                                                    $activation_end_datetime = new DateTime($model->activation_end_date);
                                                    $interval = $now_datetime->diff($activation_end_datetime);
                                                    $months = $interval->y * 12 + $interval->m;

                                                    // Denay user renew badge more than once
                                                    if ($months >= $activation_period * 2)
                                                    {
                                                        $isRollBack = true;
                                                        $transaction->rollback();
                                                        Yii::app()->user->setFlash('error', Yii::t('default', 'The badge (number) has been already renewed', array('number' => $number)));
                                                        break;
                                                    }
                                                    else
                                                    {
                                                        if (!$model->save())
                                                        {
                                                            $isRollBack = true;
                                                            $transaction->rollback();
                                                            Yii::app()->user->setFlash('error', CHtml::errorSummary($model));
                                                            break;
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                        else
                                        {
                                            $isRollBack = true;
                                            $transaction->rollback();
                                            Yii::app()->user->setFlash('error', Yii::t('default', 'The Badge ({n}) is not found in the system.', $number));
                                            break;
                                        }
                                    }
                                    else
                                    {
                                        $isRollBack = true;
                                        $transaction->rollback();
                                        Yii::app()->user->setFlash('error', yii::t('default', 'This Activation period at row ({n}) must be number .', $i));
                                        break;
                                    }
                                }
                                else
                                {
                                    $isRollBack = true;
                                    $transaction->rollback();
                                    Yii::app()->user->setFlash('error', yii::t('default', 'This Activation period at row ({n}) is empty .', $i));
                                    break;
                                }
                            }
                            else
                            {
                                $isRollBack = true;
                                $transaction->rollback();
                                Yii::app()->user->setFlash('error', yii::t('default', 'This Badge Number at row ({n}) is empty .', $i));
                                break;
                            }
                        }
                    }
                    If (!$isRollBack)
                    {
                        Yii::app()->user->setFlash('success', Yii::t('default', 'The batch badges have been extended successfully'));
                        $transaction->commit(); // commit transactions now
                        unlink($filePath);
                        $this->redirect(array('/badge/index'));
                    }
                    unlink($filePath);
                }
                catch (Exception $ex)
                {
                    $transaction->rollback();
                    Yii::app()->user->setFlash('error', CHtml::errorSummary($model));
                    unlink($filePath);
                    return;
                }
            }
            else
            {
                Yii::app()->user->setFlash('error', yii::t("default", "Please browse a file"));
            }
        }
        $this->render('batchExtend', array(
            'model' => $file_model,
        ));
    }

    /**
     * The Following Action Responsible for Upload Excel file to server and
     * add all LDAP person in file to system and update who exist before .
     */
    public function actionAddBatch()
    {
        $file_model = new File;

        if (isset($_POST['File']))
        {
            $file_model->attributes = $_POST['File'];
            // get file name and upload it to server at foler /protected/upload/ldapbatch
            $file_model->file = CUploadedFile::getInstance($file_model, 'file');
            if (isset($file_model->file) && ($file_model->file != null))
            {
                $formatted_file_name = $file_model->file->name;
                $file_name = str_replace(":", "_", $formatted_file_name); // the ":" is not allowed in the file name
                $file_model->file->saveAs('./protected/upload/badges/' . $file_name);
                //Read Excel File and Fetch data
                $filePath = './protected/upload/badges/' . $file_name;
                Yii::import('ext.phpexcelreader.JPhpExcelReader');
                $data = new JPhpExcelReader();
                 $data->Spreadsheet_Excel_Reader($filePath);
                // Begin Transaction For Add ALL Badges In Excel File
                // Abort The Transaction If There Is Validate Error
                $transaction = Yii::app()->db->beginTransaction();
                $isRollBack = false;
                try
                {
                    for ($i = 2; $i <= count($data->sheets[0]['cells']); $i++)
                    {
                        //check if the row is empty
                        $is_empty = TRUE;
                        for ($j = 1; $j <= 2; $j++)
                        {
                            if (isset($data->sheets[0]['cells'][$i][$j]) && ($data->sheets[0]['cells'][$i][$j] != ""))
                            {
                                $is_empty = FALSE;
                                break;
                            }
                        }

                        if (!$is_empty)
                        {
                            $number = isset($data->sheets[0]['cells'][$i][1]) ? $data->sheets[0]['cells'][$i][1] : null;
                            $type = isset($data->sheets[0]['cells'][$i][2]) ? $data->sheets[0]['cells'][$i][2] : "";
                            if (($number != null))
                            {
                                $model = Badge::model()->findByAttributes(array('number' => $number));
                                if ($model == null)
                                {
                                    $model = new Badge;
                                    $model->number = $number;
                                    $model->status = 'Free';
                                    // Check if the type_id  is Exist at system
                                    $type_model = BadgeType::model()->findByattributes(array('name' => $type));
                                    if ($type_model == null)
                                    {
                                        $isRollBack = true;
                                        $transaction->rollback();
                                        Yii::app()->user->setFlash('error', Yii::t('default', 'The Badge Type ({n}) is not found in the system.', $type));
                                        break;
                                    }
                                    else
                                    {
                                        $model->type_id = $type_model->id;
                                    }
                                    if (!$model->save())
                                    {
                                        $isRollBack = true;
                                        $transaction->rollback();
                                        Yii::app()->user->setFlash('error', CHtml::errorSummary($model));
                                        break;
                                    }
                                }
                            }
                            else
                            {
                                $isRollBack = true;
                                $transaction->rollback();
                                Yii::app()->user->setFlash('error', yii::t('default', 'This Badge Number at row ({n}) is empty .', $i));
                                break;
                            }
                        }
                    }
                    If (!$isRollBack)
                    {
                        Yii::app()->user->setFlash('success', Yii::t('default', 'The batch of badges has been added successfully'));
                        $transaction->commit(); // commit transactions now
                        unlink($filePath);
                        $this->redirect(array('/badge/index'));
                    }
                    unlink($filePath);
                }
                catch (Exception $ex)
                {
                    $transaction->rollback();
                    Yii::app()->user->setFlash('error', CHtml::errorSummary($model));
                    unlink($filePath);
                    return;
                }
            }
            else
            {
                Yii::app()->user->setFlash('error', yii::t("default", "Please browse a file"));
            }
        }
        $this->render('addBatch', array(
            'model' => $file_model,
        ));
    }

    /*
     *  The Follwoing Action responsible for download Batch-Badge-emplate file
     */

    function actionDownload($filename)
    {
        $filecontent = file_get_contents($filename);
        header("Content-Type: text/plain");
        $list = explode("/", $filename);
        $saved_file_name = $list[4];
        header("Content-disposition: attachment; filename=" . $saved_file_name);
        header("Pragma: no-cache");
        echo $filecontent;
        exit;
    }

    /*
     * The following action is responsible for Add badge and assign it to person
     */

    function actionAddAndAssign($badge_number=null, $person_id=null, $add=false)
    {
        //Add badge to the system before assign it
        if ($add == true)
        {
            if (isset($_POST['badge_type']) && $_POST['badge_type'] != '')
            {
                $badge_type_id = $_POST['badge_type'];
                $Badge_model = new Badge;
                $Badge_model->number = $badge_number;
                $Badge_model->type_id = $badge_type_id;
                $Badge_model->status = 'Free';
                if (!$Badge_model->save())
                {
                    Yii::app()->user->setFlash('error', CHtml::errorSummary($Badge_model));
                }
            }
            else
            {
                Yii::app()->user->setFlash('error', yii::t('default', 'Please select badge type to add it to the system'));
                $this->redirect(array('/LDAPperson/view', 'id' => $person_id));
            }
        }


        //Assign badge to person
        $person_model = Person::model()->findByPk($person_id);
        $model = Badge::model()->findByAttributes(array('number' => $badge_number));
        //Default value for Activation Period
        $activation_period = $model->type->activation_period;
        $model->max_served_meals = $model->type->non_manager_meals;
        if ($person_id != null)
        {
            $model->person_id = $person_model->identifier;
        }
        if (isset($_POST['Badge']))
        {
            $model->attributes = $_POST['Badge'];

            //Set scenario as assignment for applying specific validation rules
            $model->setScenario('assignment');
            $model->status = 'Active';
            //Convert person_id value from string "name-number" (GUI) to ID (model)
            $person_model = null;
            if ($model->person_id != "" && !is_numeric($model->person_id))
            {
                $attributes_array = explode("-", $model->person_id);
                $person_number = end($attributes_array);
                $person_model = Person::model()->findByAttributes(array('number' => $person_number));
                if ($person_model != null)
                    $model->person_id = $person_model->id;
                else
                    $model->person_id = null;
            }
            if ($model->save())
            {
                Yii::app()->user->setFlash('success', Yii::t('default', 'The Badge has been assigned successfully'));
                $this->redirect(array('/LDAPperson/view', 'id' => $model->person_id));
            }
            else
            {
                //Convert person_id value from ID (model) to string "name-number" (GUI)
                if ($person_model != null)
                {
                    $model->person_id = $person_model->identifier;
                }
                Yii::app()->user->setFlash('error', CHtml::errorSummary($model));
            }
        }


        $this->render('addAndAssign', array(
            'model' => $model,
            'activation_period' => $activation_period,
        ));
    }

    /*
     * The following action is responsible for assign person to badge
     */

    function actionAssignPersonToBadge($id)
    {
        $model = $this->loadModel($id);
        //Default value for Activation Period
        $activation_period = 0;
        if ($model != null)
        {
            $activation_period = $model->type->activation_period;
            $model->max_served_meals = $model->type->non_manager_meals;
        }
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Badge']))
        {
            $badge_history = new BadgeHistory();
            if ($model->person != null)
            {
                $badge_history->badge_id = $model->id;
                $badge_history->person_id = $model->person_id;
                $badge_history->activation_start_date = $model->activation_start_date;
                $badge_history->activation_end_date = $model->activation_end_date;
                $badge_history->max_served_meals = $model->max_served_meals;
            }


            $model->attributes = $_POST['Badge'];

            //Set scenario as assignment for applying specific validation rules
            $model->setScenario('assignment');
            $model->status = 'Active';
            //Convert person_id value from string "name-number" (GUI) to ID (model)
            $person_model = null;
            if ($model->person_id != "" && !is_numeric($model->person_id))
            {
                $attributes_array = explode("-", $model->person_id);
                $person_number = end($attributes_array);
                $person_model = Person::model()->findByAttributes(array('number' => $person_number));
                if ($person_model != null)
                    $model->person_id = $person_model->id;
                else
                    $model->person_id = null;
            }
            if ($model->save())
            {
                // add old badge assignment to badge history when reassign the badge
                if ($model->person != null)
                {
                    if ($badge_history->save())
                    {
                        Yii::app()->user->setFlash('success', Yii::t('default', 'The Badge has been updated successfully'));
                        $this->redirect(array('view', 'id' => $model->id));
                    }
                    else
                    {
                        Yii::app()->user->setFlash('error', CHtml::errorSummary($badge_history));
                    }
                }
                else
                {
                    Yii::app()->user->setFlash('success', Yii::t('default', 'The Badge has been updated successfully'));
                    $this->redirect(array('view', 'id' => $model->id));
                }
            }
            else
            {
                //Convert person_id value from ID (model) to string "name-number" (GUI)
                if ($person_model != null)
                    $model->person_id = $person_model->identifier;
                Yii::app()->user->setFlash('error', CHtml::errorSummary($model));
            }
        }else
        {
            if ($model->person != null)
                $model->person_id = $model->person->identifier;
        }

        $this->render('assignPersonToBadge', array(
            'model' => $model,
            'activation_period' => $activation_period,
        ));
    }

    /*
     * The following action is responsible for assign badge to person
     */

    function actionAssignBadgeToPerson($id)
    {
        $person = Person::model()->findByPk($id);

        $model = new Badge;

        $activation_period = 0;
        if (isset($_POST['Badge']))
        {
            $model->attributes = $_POST['Badge'];
            if ($model->number != "")
            {
                $Badge = Badge::model()->findByAttributes(array('number' => $model->number));
                if ($Badge != null)
                {
                    $Badge->setScenario('assignment');
                    $Badge->status = 'Active';
                    $Badge->person_id = $id;
                    $Badge->max_served_meals = $model->max_served_meals;
                    $Badge->activation_start_date = $model->activation_start_date;
                    $Badge->activation_end_date = $model->activation_end_date;

                    if ($Badge->save())
                    {
                        Yii::app()->user->setFlash('success', Yii::t('default', 'The badge ({badge_number}) has been assigned successfully to ({person_name})', array('{badge_number}' => $Badge->number, '{person_name}' => $person->identifier)));
                        $this->redirect($person->getViewUrl());
                    }
                    else
                    {
                        //Convert person_id value from ID (model) to string "name-number" (GUI)
                        $model->person_id = $person->identifier;
                        Yii::app()->user->setFlash('error', CHtml::errorSummary($Badge));
                    }
                }
                else
                {
                    Yii::app()->user->setFlash('error', Yii::t('default', 'The badge ({badge_number}) didn`t exist', array('{badge_number}' => $model->number)));
                    $model->person_id = $person->identifier;
                }
            }else  //Convert person_id value from ID (model) to string "name-number" (GUI)
                $model->person_id = $person->identifier;
        }
        else
        {
            //Convert person_id value from ID (model) to string "name-number" (GUI)
            $model->person_id = $person->identifier;
        }

        $this->render('assignBadgeToPerson', array(
            'model' => $model,
            'id' => $id,
        ));
    }

    /*
     * The following action is responsible for Un-assign person to badge
     */

    function actionUnAssignBadge($id, $person_id=null)
    {
        $model = $this->loadModel($id);

        if ($model != null)
        {
            $badge_history = new BadgeHistory();
            $badge_history->badge_id = $model->id;
            $badge_history->person_id = $model->person_id;
            $badge_history->activation_start_date = $model->activation_start_date;
            $badge_history->activation_end_date = $model->activation_end_date;
            $badge_history->max_served_meals = $model->max_served_meals;


            $person_name = $model->person->name;
            $model->person_id = null;
            $model->activation_start_date = null;
            $model->activation_end_date = null;
            $model->max_served_meals = null;
            $model->status = 'Free';
            if ($model->save())
            {
                if ($badge_history->save())
                {
                    Yii::app()->user->setFlash('success', Yii::t('default', 'The Badge {badge_number} has been un-asigned successfully from {person_name}', array('{badge_number}' => $model->number, '{person_name}' => $person_name)));
                }
                else
                {
                    Yii::app()->user->setFlash('error', CHtml::errorSummary($badge_history));
                }
            }
            else
            {
                Yii::app()->user->setFlash('error', CHtml::errorSummary($model));
            }
        }
        //Check the returned url to the badge index page or to person management badge page
        if ($person_id == null)
        {
            $this->redirect(array('index'));
        }
        else
        {
            $this->redirect(array('/person/manageBadges', 'id' => $person_id));
        }
    }

    /*
     * The following action is responsible for Renew person to badge
     */

    function actionRenew($id, $person_id=null)
    {
        $model = $this->loadModel($id);
        if ($model != null)
        {
            $activation_period = $model->type->activation_period;
            $now_date = date("Y-m-d"); // current date
            $activation_end_date = date("Y-m-d", strtotime(date("Y-m-d", strtotime($model->activation_end_date)) . " +$activation_period month"));
            $model->activation_end_date = $activation_end_date;

            $now_datetime = new DateTime($now_date);
            $activation_end_datetime = new DateTime($model->activation_end_date);
            $interval = $now_datetime->diff($activation_end_datetime);
            $months = $interval->y * 12 + $interval->m;

            // Denay user renew badge more than once
            if ($months >= $activation_period * 2)
            {
                Yii::app()->user->setFlash('error', Yii::t('default', 'The badge has been already renewed'));
            }
            else
            {
                if ($model->save())
                {
                    Yii::app()->user->setFlash('success', Yii::t('default', 'The Badge {n} has been renewed successfully', $model->number));
                }
                else
                {
                    Yii::app()->user->setFlash('error', CHtml::errorSummary($model));
                }
            }
        }

        //Check the returned url to the badge index page or to person management badge page
        if ($person_id == null)
        {
            $this->redirect(array('index'));
        }
        else
        {
            $this->redirect(array('/person/manageBadges', 'id' => $person_id));
        }
    }

}

