<?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
 */
 
/**
 *  Invoice
 *
 * Yii controller to control invoice actions
 *
 * @version 1.0
 *
 * @author Amaney
 * @package application.controllers
 */
class InvoiceController 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'),
		'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', 'DetailExportToExcel', 'SummaryExportToExcel'),
		'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' => $this->loadModel($id),
	));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate($from = null, $tid_id = null) {
	$model = new Invoice;
	if ($tid_id != null)
	    $model->tid_id = Tid::getNumberfromId($tid_id);
	// Uncomment the following line if AJAX validation is needed
	// $this->performAjaxValidation($model);

	if (isset($_POST['Invoice'])) {
	    $model->attributes = $_POST['Invoice'];
	    $model->tid_identifier = $model->tid_id;
	    $model->tid_id = Tid::getIdfromNumber($model->tid_id);
	    if ($model->validate()) {
		// Yii::app()->user->setFlash('success', Yii::t('default', 'The invoice has been added successfully'));
		if ($model->warning_msg != '' && !isset($_POST['dialogResult'])) {
		    echo "dialog#" . $model->warning_msg;
		    return;
		} else {
		    if ($model->save()) {
			Yii::app()->user->setFlash('success', Yii::t('default', 'The invoice has been added successfully'));
			echo $model->id . "#" . $model->tid_id . "#" . $tid_id;
			return;
		    } else {
			$model->tid_id = Tid::getNumberfromId($model->tid_id);
			Yii::app()->user->setFlash('error', CHtml::errorSummary($model));
			$model->setWarningMsg();
			echo "<div class='flash-msg'>" . "<br>";
			$this->widget('bootstrap.widgets.TbAlert');
			echo "</div>";
			return;
		    }
		}
	    } else {
		$model->tid_id = Tid::getNumberfromId($model->tid_id);
		Yii::app()->user->setFlash('error', CHtml::errorSummary($model));
		$model->setWarningMsg();
		echo "<div class='flash-msg'>" . "<br>";
		$this->widget('bootstrap.widgets.TbAlert');
		echo "</div>";
		return;
	    }
	}

	$this->render('create', array(
	    'model' => $model,
	    '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, $tid_id = null) {
	$model = $this->loadModel($id);
	$model->tid_id = Tid::getNumberfromId($model->tid_id);

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

	if (isset($_POST['Invoice'])) {
	    $model->attributes = $_POST['Invoice'];
	    $model->tid_identifier = $model->tid_id;
	    $model->tid_id = Tid::getIdfromNumber($model->tid_id);
	    if ($model->save()) {
		//Yii::app()->user->setFlash('success', Yii::t('default', 'The invoice has been updated successfully'));
		if ($model->warning_msg != '' && !isset($_POST['dialogResult'])) {
		    echo "dialog#" . $model->warning_msg;
		    return;
		} else {
		    Yii::app()->user->setFlash('success', Yii::t('default', 'The invoice has been updated successfully'));
		    echo $model->id . "#" . $model->tid_id . "#" . $tid_id;
		    return;
		}
	    } else {
		Yii::app()->user->setFlash('error', CHtml::errorSummary($model));
		$model->setWarningMsg();
		echo "<div class='flash-msg'>" . "<br>";
		$this->widget('bootstrap.widgets.TbAlert');
		echo "</div>";
		return;
	    }
	}

	$this->render('update', array(
	    'model' => $model,
	    'tid_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 invoice ({n}) has been deleted successfully', $model->number);
	$failer_msg = Yii::t('default', 'You cannot delete this element, you need to delete its assets first');
	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($tid_id = null, $from = null, $rendered_from=null) {
	$model = new Invoice('search');
	$model->unsetAttributes();  // clear any default values
	if (isset($_GET['Invoice']))
	    $model->attributes = $_GET['Invoice'];

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

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

    /**
     * Export Invoices summary info to excel
     */
    public function actionSummaryExportToExcel($tid_id = null) {
	$model = new Invoice('search');
	$model->unsetAttributes();  // clear any default values
	if (isset($_GET['Invoice']))
	    $model->attributes = $_GET['Invoice'];

	//Export Data to Excel File
	$header = array(
	    'tid_id' => Yii::t('default', 'TID No'),
	    'number' => Yii::t('default', 'Invoice Number'),
	    'value' => Yii::t('default', 'Invoice Value'),
	    'description' => Yii::t('default', 'Description'),
	    'comments' => Yii::t('default', 'Comments'),
	    'last_edited_by' => Yii::t('default', 'Updated By')
	);

	$column = "tid.tid_no,t.number,if(isnull(t.value) || t.value = '','',CONCAT('$',t.value)) ,t.description,t.comments,user.username";

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

    /**
     * Export invoices detailed info to excel
     */
    public function actionDetailExportToExcel($tid_id = null) {
	$model = new Invoice('search');
	$model->unsetAttributes();  // clear any default values
	if (isset($_GET['Invoice']))
	    $model->attributes = $_GET['Invoice'];

	//Export Data to Excel File
	$header = array(
	    'tid_no' => Yii::t('default', 'TID No'),
	    'number' => Yii::t('default', 'Invoice Number'),
	    'value' => Yii::t('default', 'Invoice Value'),
	    'description' => Yii::t('default', 'Description'),
	    'comments' => Yii::t('default', 'Comments'),
	    'last_edited_by' => Yii::t('default', 'Updated By'),
	    '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'),
	    'asset_description' => Yii::t('default', 'Asset 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.tid_no,t.number,if(isnull(t.value) || t.value = '','',CONCAT('$',t.value)),t.description,t.comments,user.username,po_number,segment_name,serial_number,asset_number,part_number,
	    type_of_asset_name,v_asset.description as asset_description,asset_status,plate_number,chassis_number,vehicle_book_expiry_date,vehicle_book_status,
	    radioactive_license_number,radioactive_license_expiry_date,radioactive_license_status,v_asset.username as asset_updated_by";

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

}
