<?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 ItemRequestHeaderController 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', 'GetDepartments', 'GetItems', 'ConvertToPDF', 'Details', 'viewItemRequestHeaderDetail', 'SendEmail', 'ExportToExcel'),
		'roles' => array('Super Admin', 'System Admin', 'Food Manager', 'Facility Admin', 'Finance'),
	    ),
	    array('allow', // allow all users to perform 'index' and 'view' actions
		'actions' => array('cancelled'),
		'roles' => array('Super Admin', 'System Admin'),
	    ),
	    array('deny', // deny all users
		'users' => array('*'),
	    ),
	);
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id, $new_request = 0) {
	$this->render('view', array(
	    'model' => $this->loadModel($id),
	    'new_request' => $new_request,
	));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
	$model = new ItemRequestHeader('add');
	if (Yii::app()->user->checkAccess('Food Manager')) {
	    $user_model = User::model()->findByPk(Yii::app()->user->id);
	    $person_model = Person::model()->findByAttributes(array('alias' => $user_model->username));
	    if ($person_model->is_food_manager == 0)
		$this->redirect(array('index'));
	    $model->location_id = $user_model->location->id;
	    $model->department_id = $person_model->department->id;
	}
	if (isset($_POST['ItemRequestHeader'])) {
	    $model->attributes = $_POST['ItemRequestHeader'];
	    $transaction = Yii::app()->db->beginTransaction();
	    if (isset($_POST['location']) && ($_POST['location'] != ''))
		$model->location_id = $_POST['location'];

	    if ($model->save()) {
		$error_message = "";
		ItemRequestDetail::saveItemsDetail($error_message, $model);
		if ($error_message == "") {
		    Yii::app()->user->setFlash('success', Yii::t('default', 'The Item has been requested successfully'));
		    $transaction->commit();
		    echo $model->id;
		    $this->layout = '//layouts/pdfLayout';
		    $this->saveAsPdf('itemPDF', array('id' => $model->id), array(), 'protected\upload\pdfs\Item-' . $model->id . '.pdf');
		    return;
		} else {
		    $transaction->rollback();
		    Yii::app()->user->setFlash('error', $error_message);
		    echo "<div class='flash-msg'>" . "<br>";
		    $this->widget('bootstrap.widgets.TbAlert');
		    echo "</div>";
		    return;
		}
	    } else {
		$transaction->rollback();
		Yii::app()->user->setFlash('error', CHtml::errorSummary($model));
		echo "<div class='flash-msg'>" . "<br>";
		$this->widget('bootstrap.widgets.TbAlert');
		echo "</div>";
		return;
	    }
	}

	$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) {
	$model = $this->loadModel($id);
	if (isset($_POST['ItemRequestHeader'])) {
	    $model->attributes = $_POST['ItemRequestHeader'];
	    if ($model->save())
		$this->redirect(array('view', 'id' => $model->id));
	}

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

    /**
     * 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) {
	$this->loadModel($id)->delete();

	// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
	if (!isset($_GET['ajax']))
	    $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
    }

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

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

    /**
     * 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 $id the ID of the model to be loaded
     * @return ItemRequestHeader the loaded model
     * @throws CHttpException
     */
    public function loadModel($id) {
	$model = ItemRequestHeader::model()->findByPk($id);
	if ($model === null)
	    throw new CHttpException(404, 'The requested page does not exist.');
	return $model;
    }

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

    public function behaviors() {
	return array(
	    'pdfable' => array(
		'class' => 'ext.pdfable.Pdfable',
		'pdfOptions' => array(
		    'bin' => __DIR__ . '/../extensions/pdfable/wkhtmltopdf/wkhtmltopdf.exe',
		    'page-size' => 'A4',
		),
	    ),
	);
    }

    public function actionConvertToPDF($preview = 0, $download = 0, $id = 0) {
	$this->layout = '//layouts/pdfLayout';
	if ($preview)
	// Render this view as PDF and display in the browser tab:
	    $this->render('itemPDF', array('id' => $id), array());
	else
	// Render this view as PDF and display inline in the browser:
	    $this->renderPdf('itemPDF', array('id' => $id), array(), $download ? 'Item-' . $id . '.pdf' : null);
    }

    /**
     * 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 actionCancelled($id) {
	$model = $this->loadModel($id);

	if ($model->cancelled == 1) {
	    $model->cancelled = 0;
	    $message = Yii::t('default', 'The Item ({n}) has been activated successfully', $model->id);
	} elseif ($model->cancelled == 0) {
	    $model->cancelled = 1;
	    $message = Yii::t('default', 'The Item ({n}) has been cancelled successfully', $model->id);
	}
	if ($model->save()) {
	    Yii::app()->user->setFlash('success', $message);
	    $this->redirect(array('index'));
	} else {
	    Yii::app()->user->setFlash('error', CHtml::errorSummary($model));
	}


	$this->redirect(array('/itemRequestHeader/index'));
    }

    /*
     * Action for return department in selected location  in cascading dropdown list
     */

    public function actionGetDepartments() {
	if (isset($_POST['location_id'])) {
	    $selected_location = Location::model()->findByPk($_POST['location_id']);
	    echo CHtml::tag('option', array('value' => ""), CHtml::encode('Select Department'), true);
	    if (isset($selected_location->departments) && ($selected_location->departments != null)) {
		foreach ($selected_location->departments as $department) {
		    echo CHtml::tag('option', array('value' => $department->id), CHtml::encode($department->name), true);
		}
	    }
	    // echo "###";
//
//	    $items = Item::getNameLists($_POST['location_id']);
//	    foreach ($items as $key => $item) {
//		echo '<li class="ui-menu-item" role="presentation"><a id="ui-id-' . ($key + 2) . '" class="ui-corner-all" tabindex="-1">' . $item . "</a></li>";
//	    }
//	   
	    //echo Yii::app()->controller->renderPartial('/itemRequestDetail/index', array('model' => new ItemRequestHeader, 'from_view_page' => 'false', 'location_id' => $_POST['location_id']), true, true);
	}
    }

    public function actionDetails($data) {
	$result = explode('##', $data);
	$array = json_decode($result[0]);
	$model_id = $result[1];
	$location_id = $result[2];
	$dataArray = array();
	foreach ($array as $value) {
	    if ($value != null) {
		$columns = array();
		$columns['id'] = $value->id;
		$columns['item_id'] = $value->item_name;
		$columns['quantity'] = $value->quantity;
		$dataArray[] = $columns;
	    }
	}

	$dataProvider = new CArrayDataProvider($dataArray, array('id' => 'attachments'));

	Yii::app()->controller->renderPartial('/itemRequestDetail/_grid', array('dataProvider' => $dataProvider, 'model_id' => $model_id, 'from_view_page' => 'false', 'location_id' => $location_id));
    }

    /**
     * Render role details
     */
    public function actionViewItemRequestHeaderDetail($id) {
	$model = $this->loadModel($id);

	Yii::app()->controller->renderPartial('/itemRequestDetail/index', array('model' => $model, 'from_view_page' => 'detail', 'location_id' => $model->location_id));
    }

    public function actionSendEmail($id) {
	if ($id != '') {
	    $model = ItemRequestHeader::model()->findByPk($id);
	    if ($model != null) {
		$department_name = $model->department->name;
		$id = $model->id;

		$user_model = User::model()->findByPk(Yii::app()->user->id);
		$person_model = null;
		$cc_email = array();
		$person_model_alias = $user_model->identifier;
		if (Yii::app()->user->checkAccess('Food Manager')) {
		    $person_model = Person::model()->findByAttributes(array('alias' => $user_model->username));
		    if (($person_model != null) && ($person_model->is_food_manager == 1)) {
			$manager_food_manager = $person_model->manager;
			if (($manager_food_manager != '')) {
			    $manager_info = explode('-', $manager_food_manager);
			    $manager_food_model = Person::model()->findByAttributes(array('number' => $manager_info[1]));
			    if ($manager_food_model != null)
				$cc_email[] = $manager_food_model->email;
			}
			$person_model_alias = $person_model->alias;
		    }
		}
		$item_html = ItemRequestDetail::getItemDetailHtml($model->id);

		User::getAllFacilityAdmin($model->location_id, $id, $department_name, $item_html);

		$user_model_email = $user_model->email;

		if ($cc_email == null) {
		    LSMSMail::sendMail('Items requested for ' . $department_name . '–' . $id, 'Dear ' . $person_model_alias . ',<br/><br/> You have successfully requested the items below for the department (' . $department_name . '): <br/>' . $item_html . '<br/> The attached file contains full details about the request.', $user_model_email, null, 'protected\upload\pdfs\Item-' . $id . '.pdf');
		} else {
		    LSMSMail::sendMail('Items requested for ' . $department_name . '–' . $id, 'Dear ' . $person_model_alias . ',<br/><br/> You have successfully requested the items below for the department (' . $department_name . '): <br/>' . $item_html . '<br/> The attached file contains full details about the request.', $user_model_email, null, 'protected\upload\pdfs\Item-' . $id . '.pdf', $cc_email);
		}
		unlink('protected\upload\pdfs\Item-' . $id . '.pdf');
	    }
	}
    }

    /*
     * Action for return department in selected location  in cascading dropdown list
     */

    public function actionGetItems() {
	if (isset($_POST['location_id'])) {
	    $item_name = null;
	    if (isset($_POST['item_name']))
		$item_name = $_POST['item_name'];
	    $items = Item::getNameLists($_POST['location_id'], $item_name);
	    echo CJSON::encode($items);
	    Yii::app()->end();
	}
    }

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

	$header = array(
	    'id',
	    'user_id',
	    'location_id',
	    'department_id',
	    'date_time',
	    'cancelled',
	);
	$column = "t.id,
            user.username as user_id,
	    location.code,
            department.name as department_id,
            date_time,
            cancelled";
	
	$model->exportToExcel(Yii::t('default', 'Items'), $model, $header, $column, $model->ModelCriteria());
    }

}
