<?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
 */
 
/**
 *  Asset
 *
 * Yii controller to control asset actions
 *
 * @version 1.0
 *
 * @author Amaney
 * @package application.controllers
 */
class AssetController 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
	//'postOnly + delete', // we only allow deletion via POST request
	);
    }

    /**
     * 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('create', 'update', 'delete', 'processTypeOfAsset', 'processPONumber', 'renew', 'generalRenew'),
		'roles' => array(User::SYSTEM_ADMIN_ROLE, User::LOGISTICS_ADMIN_ROLE),
	    ),
	    array('allow', // allow all users to perform 'index' and 'view' actions
		'actions' => array('index', 'view', 'viewInvoiceInTid', 'exportToExcel'),
		'users' => array('*'),
	    ),
	    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) {
	$this->render('view', array(
	    'model' => VAsset::model()->findByPk($id),
	));
    }

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

	// Uncomment the following line if AJAX validation is needed
	// $this->performAjaxValidation($model);
	if ($invoice_id != null && $tid_id != null) {
	    $model->invoice_id = $invoice_id;
	    $model->tid_id = Tid::getNumberfromId($tid_id);
	} else
	if ($tid_id != null)
	    $model->tid_id = Tid::getNumberfromId($tid_id);

	if (isset($_POST['Asset'])) {
	    $model->attributes = $_POST['Asset'];
	    $model->setModelScenario();
	    $transaction = Yii::app()->db->beginTransaction();
	    if ($model->save()) {
		if ($model->createUpdateStatus(true, $error_msg)) {
		    if ($model->warning_msg != '' && !isset($_POST['dialogResult'])) {
			echo "dialog#" . $model->warning_msg;
			return;
		    } else {
			$transaction->commit();
			Yii::app()->user->setFlash('success', Yii::t('default', 'The asset has been added successfully'));
			echo $model->invoice_id . "#" . $invoice_id . "#" . $model->invoice->tid_id;
			return; //
		    }
		} else {
		    $transaction->rollback();
		    $model->setWarningMsg();
		    Yii::app()->user->setFlash('error', $error_msg);
		    echo "<div class='flash-msg'>" . "<br>";
		    $this->widget('bootstrap.widgets.TbAlert');
		    echo "</div>";
		    return;
		}
	    } else {
		$transaction->rollback();
		$model->setWarningMsg();
		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,
	    'invoice_id' => $invoice_id,
	    'tid_id' => $tid_id,
	));
    }

    /**
     * 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, $from = null) {
	$model = $this->loadModel($id);
	$model->tid_id = $model->invoice->tid->tid_no;
	$model->vehicle_book_expiry_date = VAsset::model()->findByPk($id)->vehicle_book_expiry_date;
	$model->radioactive_license_expiry_date = VAsset::model()->findByPk($id)->radioactive_license_expiry_date;

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

	if (isset($_POST['Asset'])) {
	    $model->attributes = $_POST['Asset'];
	    $model->setModelScenario();
	    $transaction = Yii::app()->db->beginTransaction();
	    if ($model->save()) {
		if ($model->createUpdateStatus(false, $error_msg)) {
		    if ($model->warning_msg != '' && !isset($_POST['dialogResult'])) {
			echo "dialog#" . $model->warning_msg;
			return;
		    } else {
			$transaction->commit();
			Yii::app()->user->setFlash('success', Yii::t('default', 'The asset has been updated successfully'));
			echo $model->invoice_id . "#" . $model->invoice_id . "#" . $model->invoice->tid_id;
			return; //
		    }
		} else {
		    $transaction->rollback();
		    $model->setWarningMsg();
		    Yii::app()->user->setFlash('error', $error_msg);
		    echo "<div class='flash-msg'>" . "<br>";
		    $this->widget('bootstrap.widgets.TbAlert');
		    echo "</div>";
		    return;
		}
	    } else {
		$transaction->rollback();
		$model->setWarningMsg();
		Yii::app()->user->setFlash('error', CHtml::errorSummary($model));
		echo "<div class='flash-msg'>" . "<br>";
		$this->widget('bootstrap.widgets.TbAlert');
		echo "</div>";
		return;
	    }
	}

	$this->render('update', array(
	    'model' => $model,
	    'invoice_id' => '',
	    'tid_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 asset ({n}) has been deleted successfully', $model->asset_number);
	$failer_msg = Yii::t('default', 'You cannot delete this element because it is referenced by dashboard reports');
	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);
		$this->redirect(array('index'));
	    } 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);
		$this->redirect(array('view', 'id' => $model->id));
	    } else {
		Yii::app()->user->setFlash('error', $failer_msg);
		echo "<div class='flash-msg'>" . "<br>";
		$this->widget('bootstrap.widgets.TbAlert');
		echo "</div>";
	    }
	} catch (Exception $e) { // here the item is referenced by another item
	    if (!isset($_GET['ajax'])) {
		Yii::app()->user->setFlash('error', $e->getMessage());
		$this->redirect(array('view', 'id' => $model->id));
	    } else {
		Yii::app()->user->setFlash('error', $e->getMessage());
		echo "<div class='flash-msg'>" . "<br>";
		$this->widget('bootstrap.widgets.TbAlert');
		echo "</div>";
	    }
	}
    }

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

	if ($from != null)
	    $this->render('viewAssetInInvoice', array(
		'model' => $model,
		'invoice_id' => $invoice_id,
		'page_name'=>$rendered_from
	    ));
	else
	    $this->render('index', array(
		'model' => $model,
		'invoice_id' => $invoice_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 $id the ID of the model to be loaded
     * @return Asset the loaded model
     * @throws CHttpException
     */
    public function loadModel($id) {
	$model = Asset::model()->findByPk($id);
	if ($model === null)
	    throw new CHttpException(404, 'The requested page does not exist.');
	return $model;
    }

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

    /**
     * The Following Action is for get cascading drop down options according to selected tid
     */
    public function actionViewInvoiceInTid() {
	$invoices = Invoice::model()->with('tid')->findAll('tid_no=:tid_id', array(':tid_id' => $_POST['tid_id']));
	$data = array();
	$data[0] = Yii::t('default', 'Select Invoice');
	foreach ($invoices as $invoice) {
	    $data[$invoice->id] = $invoice->number;
	}

	foreach ($data as $value => $name) {
	    echo CHtml::tag('option', array('value' => $value), CHtml::encode($name), true);
	}
    }

    /**
     * The Following Action is for check if the type of asset is Vehicle or Radio active or other
     */
    public function actionProcessTypeOfAsset() {
	if (isset($_POST['type_of_asset'])) {
	    $type_of_asset = $_POST['type_of_asset'];
	    $vehicle_id = Setting::getVehicleTypeOfAsset();
	    $racioactive_id = Setting::getRadioActiveTypeOfAsset();
	    if ($type_of_asset == $vehicle_id)
		echo 'Vehicle';
	    else
	    if ($type_of_asset == $racioactive_id)
		echo 'RadioActive';
	    else
		echo 'Other';
	}
    }

    /**
     * The Following Action is for set segment value according to po number
     */
    public function actionProcessPONumber() {
	if (isset($_POST['po_number'])) {
	    $po_number = $_POST['po_number'];
	    $model = Segment::model();
	    $criteria = new CDbCriteria;
	    $criteria->select = 'id,po_segment_code';
	    $result = $model->commandBuilder->createFindCommand($model->tableName(), $criteria)->queryAll();
	    $po_segments = array();
	    $segment = '';
	    foreach ($result as $res) {
		if ($res['po_segment_code'] != '' && strtolower($res['po_segment_code']) == strtolower(substr($po_number, 0, strlen($res['po_segment_code']))))
		    $po_segments[] = $res;
	    }
	    if (!empty($po_segments)) {
		if (count($po_segments) == 1) {
		    echo $po_segments[0]['id'];
		    return;
		} else {
		    $len = 0;
		    $segment = $po_segments[0];
		    foreach ($po_segments as $po_segment) {
			if ($len < strlen($po_segment['po_segment_code']))
			    $segment = $po_segment;
		    }
		    echo $segment['id'];
		}
	    }
	}
	echo '';
    }

    /**
     * Export Asset info to excel
     */
    public function actionExportToExcel($invoice_id = null) {
	$model = new VAsset('search');
	$model->unsetAttributes();  // clear any default values
	if (isset($_GET['VAsset']))
	    $model->attributes = $_GET['VAsset'];

	//Export Data to Excel File
	$header = array(
	    'tid_no' => Yii::t('default', 'TID No'),
	    'invoice_number' => Yii::t('default', 'Invoice Number'),
	    'po_number' => Yii::t('default', 'PO Number'),
	    'segment_name' => Yii::t('default', 'Segment'),
	    'serial_number' => Yii::t('default', 'Serial Number'),
	    'asset_number' => Yii::t('default', 'Asset Number'),
	    'part_number' => Yii::t('default', 'Part Number'),
	    'type_of_asset_name' => Yii::t('default', 'Type of Asset'),
	    'description' => Yii::t('default', 'Description'),
	    'asset_status' => Yii::t('default', 'Asset Status'),
	    'plate_number' => Yii::t('default', 'Plate Number'),
	    'chassis_number' => Yii::t('default', 'Chassis Number'),
	    'vehicle_book_expiry_date' => Yii::t('default', 'Vehicle Book Expiry Date'),
	    'vehicle_book_status' => Yii::t('default', 'Vehicle Book Status'),
	    'radioactive_license_number' => Yii::t('default', 'Radioactive License Number'),
	    'radioactive_license_expiry_date' => Yii::t('default', 'Radioactive License Expiry Date'),
	    'radioactive_license_status' => Yii::t('default', 'Radioactive License Status'),
	    'username' => Yii::t('default', 'Asset Updated By'),
	);

	$column = "tid_no,invoice_number,po_number,segment_name,serial_number,asset_number,part_number,
	    type_of_asset_name,description,asset_status,plate_number,chassis_number,vehicle_book_expiry_date,vehicle_book_status,
	    radioactive_license_number,radioactive_license_expiry_date,radioactive_license_status,username";

	$excel_file_name = Yii::t('default', 'Assets');
	$model->exportToExcel($excel_file_name, $model, $header, $column, $model->ModelCriteria($invoice_id));
    }

    /**
     * Renew Asset
     */
    public function actionRenew() {
	if (isset($_POST['id'])) {
	    $asset = $this->loadModel($_POST['id']);

	    $this->render('renew', array(
		'model' => $asset,
		'asset_id' => $_POST['id']
	    ));
	}
	if (isset($_POST['model_id']) && isset($_POST['vehicle_expiry_date']) && isset($_POST['radioactive_expiry_date'])) {
	    $asset = $this->loadModel($_POST['model_id']);
	    $asset->vehicle_book_expiry_date = $_POST['vehicle_expiry_date'];
	    $asset->radioactive_license_expiry_date = $_POST['radioactive_expiry_date'];
	    if ($asset->createUpdateStatus(true, $error_msg,'renew')) {
		Yii::app()->user->setFlash('success', Yii::t('default', 'The asset has been renewed successfully'));
		echo "<div class='renew-flash-msg'>" . "<br>";
		$this->widget('bootstrap.widgets.TbAlert');
		echo "</div>";
		//$this->redirect(array('view', 'id' => $model->tid_id));
	    } else {
		Yii::app()->user->setFlash('error', $error_msg);
		echo "<div class='renew-flash-msg'>" . "<br>";
		$this->widget('bootstrap.widgets.TbAlert');
		echo "</div>";
	    }
	}
    }

    /**
     * Renew Asset
     */
    public function actionGeneralRenew($from = null) {
	$model = new Asset();

	if (isset($_POST['Asset'])) {
	    $model->attributes = $_POST['Asset'];
	    $error_msg = '';
	    $model = $model->getAssetByNumber($error_msg);
	    if ($error_msg == '') {
		if ($model->createUpdateStatus(true, $error_msg,'renew',$model->plate_number_auto_complete,$model->radioactive_license_number_auto_complete)) {
		    Yii::app()->user->setFlash('success', Yii::t('default', 'The asset has been renewed successfully'));
		    if ($from != null)
			$this->redirect(array('generalRenew'));
		    $this->redirect(array('view', 'id' => $model->id));
		} else
		    Yii::app()->user->setFlash('error', $error_msg);
	    }
	    else
		Yii::app()->user->setFlash('error', $error_msg);
	}

	$this->render('general_renew', array(
	    'model' => ($model == null) ? new Asset() : $model
	));
    }

}
