<?php

class CommissionController extends RController
{
	/**
	 * @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(
			'rights',
			'postOnly + delete', // we only allow deletion via POST request
		);
	}



	/**
	 * 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()
	{
		$model = new Commission;

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

		if (isset($_POST['Commission'])) {
			$model->attributes = $_POST['Commission'];
			if ($model->save())
				$this->redirect(array('view', 'id' => $model->id));
		}

		$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);

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

		if (isset($_POST['Commission'])) {
			$model->attributes = $_POST['Commission'];
			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'])) {
			Yii::app()->user->setFlash('alert-success', Yii::t('admin', 'Item has been successfully deleted.'));
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider = new CActiveDataProvider('Commission');
		$this->render('index', array(
			'dataProvider' => $dataProvider,
		));
	}

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

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

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


	public function actionExport()
	{

		$model = new Commission;

		$d = $model->search();


		$attributes = array(

			[
				'label' => Yii::t("commission", "declaration_ar"),
				'exp' => '$obj->declaration_ar'
			],

			[
				'label' => Yii::t("commission", "declaration_en"),
				'exp' => '$obj->declaration_en'
			],

			[
				'label' => Yii::t("commission", "amount_ar"),
				'exp' => '$obj->amount_ar'
			],

			[
				'label' => Yii::t("commission", "amount_en"),
				'exp' => '$obj->amount_en'
			],

			[
				'label' => Yii::t("commission", "note_ar"),
				'exp' => '$obj->note_ar'
			],

			[
				'label' => Yii::t("commission", "note_en"),
				'exp' => '$obj->note_en'
			],

		);

		$fileName = 'Commission';
		$this->exportDataProviderAsExcel($d, $attributes, $fileName);
	}

	public function actionImport()
	{
		$model = new Commission('import');

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

		if (isset($_POST['Commission'])) {
			$model->attributes = $_POST['Commission'];

			$xlsFile = CUploadedFile::getInstance($model, 'import_file');
			// init phpexcel
			Yii::import('ext.phpexcel.XPHPExcel');
			XPHPExcel::init();
			// read file
			$phpExcel = PHPExcel_IOFactory::load($xlsFile->getTempName());
			try {
				//delete all Commission
				Commission::model()->deleteAll();
				// Commission::model()->truncateTable();

				$worksheet = $phpExcel->setActiveSheetIndex(0);

				$MINIMUM_TO_OPEN_CURRENT_ACCOUNT = $worksheet->getCellByColumnAndRow(0, 2)->getValue();
				$MINIMUM_PROFIT_CALCULATION = $worksheet->getCellByColumnAndRow(1, 2)->getValue();
				$MINIMUM_INVESTMENT_ACCOUNT_OPENING = $worksheet->getCellByColumnAndRow(2, 2)->getValue();
				// $issue_AmPmtime=$worksheet->getCellByColumnAndRow ( 3, 2)->getValue ();

				$option = new Option;
				$option->updateCommission(
					$MINIMUM_TO_OPEN_CURRENT_ACCOUNT,
					$MINIMUM_PROFIT_CALCULATION,
					$MINIMUM_INVESTMENT_ACCOUNT_OPENING
				);




				for ($row = 4; $row <= $worksheet->getHighestDataRow(); $row++) {
					//add new Commission for each record
					$comm = new Commission;
					$comm->declaration_ar = $worksheet->getCellByColumnAndRow(0, $row)->getValue();
					$comm->declaration_en = $worksheet->getCellByColumnAndRow(1, $row)->getValue();
					$comm->amount_ar = $worksheet->getCellByColumnAndRow(2, $row)->getValue();
					$comm->amount_en = $worksheet->getCellByColumnAndRow(3, $row)->getValue();
					$comm->note_ar = $worksheet->getCellByColumnAndRow(4, $row)->getValue();
					$comm->note_en = $worksheet->getCellByColumnAndRow(5, $row)->getValue();

					//example how to get the data cell from the record
					// $worksheet->getCellByColumnAndRow ( 0, $row )->getValue ();
					if (!$comm->save())
						var_dump($comm->getErrors());
				}
			} catch (Exception $ex) {
				var_dump($ex);
			}
			$this->redirect(array('admin', 'id' => $model->id));
		}

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

	//////////////////////////////Export///////////////////////////////////////////////////////

	public static function exportDataProviderAsExcel($dataProvider, $attributes, $fileName)
	{
		Yii::import('ext.phpexcel.XPHPExcel');
		// create excel object
		$objPHPExcel = XPHPExcel::createPHPExcel();
		$sheet = $objPHPExcel->setActiveSheetIndex(0);
		if (Yii::app()->getLocale(Yii::app()->getLanguage())->getOrientation() == 'rtl')
			$sheet->setRightToLeft(true);
		// add header
		$model = $dataProvider->model;


		//MINIMUM_TO_OPEN_CURRENT_ACCOUNT
		$MINIMUM_TO_OPEN_CURRENT_ACCOUNT_Model = option::model()->findByAttributes(array('key' => 'MINIMUM_TO_OPEN_CURRENT_ACCOUNT'));
		// $option_issue_numberModel->value=$issue_number;

		$sheet->setCellValueByColumnAndRow(0, 1, 'الحد الأدنى لفتح حساب جاري');
		$sheet->getColumnDimensionByColumn(0)->setWidth(40);
		$sheet->getStyleByColumnAndRow(0, 1)->applyFromArray([
			'fill' => [
				'type' => PHPExcel_Style_Fill::FILL_SOLID,
				'color' => array(
					'rgb' => 'CCCCCC'
				)
			]
		]);
		$sheet->setCellValueByColumnAndRow(0, 2, $MINIMUM_TO_OPEN_CURRENT_ACCOUNT_Model->value);

		//MINIMUM_PROFIT_CALCULATION
		$MINIMUM_PROFIT_CALCULATION_Model = option::model()->findByAttributes(array('key' => 'MINIMUM_PROFIT_CALCULATION'));

		$sheet->setCellValueByColumnAndRow(1, 1, 'الحد الأدنى لاحتساب الربح على حساب التوفير');
		$sheet->getColumnDimensionByColumn(1)->setWidth(40);
		$sheet->getStyleByColumnAndRow(1, 1)->applyFromArray([
			'fill' => [
				'type' => PHPExcel_Style_Fill::FILL_SOLID,
				'color' => array(
					'rgb' => 'CCCCCC'
				)
			]
		]);
		$sheet->setCellValueByColumnAndRow(1, 2, $MINIMUM_PROFIT_CALCULATION_Model->value);

		//MINIMUM_INVESTMENT_ACCOUNT_OPENING
		$MINIMUM_INVESTMENT_ACCOUNT_OPENING_Model = option::model()->findByAttributes(array('key' => 'MINIMUM_INVESTMENT_ACCOUNT_OPENING'));

		$sheet->setCellValueByColumnAndRow(2, 1, 'الحد الأدنى لفتح حساب استثماري');
		$sheet->getColumnDimensionByColumn(2)->setWidth(40);
		$sheet->getStyleByColumnAndRow(2, 1)->applyFromArray([
			'fill' => [
				'type' => PHPExcel_Style_Fill::FILL_SOLID,
				'color' => array(
					'rgb' => 'CCCCCC'
				)
			]
		]);
		$sheet->setCellValueByColumnAndRow(2, 2, $MINIMUM_INVESTMENT_ACCOUNT_OPENING_Model->value);



		for ($i = 0; $i < count($attributes); $i++) {
			$label = is_array($attributes[$i]) ? $attributes[$i]['label'] : $model->getAttributeLabel($attributes[$i]);
			$sheet->setCellValueByColumnAndRow($i, 3, $label);
			$sheet->getColumnDimensionByColumn($i)->setWidth(40);
			$sheet->getStyleByColumnAndRow($i, 3)->applyFromArray([
				'fill' => [
					'type' => PHPExcel_Style_Fill::FILL_SOLID,
					'color' => array(
						'rgb' => 'CCCCCC'
					)
				]
			]);
		}
		// add data
		$dataProvider->setPagination([
			'pageSize' => 100
		]);
		$dataIterator = new CDataProviderIterator($dataProvider);
		$row_index = 3;
		foreach ($dataIterator as $obj) {
			$row_index++;
			for ($j = 0; $j < count($attributes); $j++) {
				$attribute = $attributes[$j];
				$val = is_array($attribute) ? eval('return ' . $attribute['exp'] . ';') : $obj->getAttributeValueLabel($attribute, $obj->$attribute);
				$sheet->setCellValueByColumnAndRow($j, $row_index, $val);
			}
		}
		// write file to output stream
		header('Content-type: application/vnd.ms-excel');
		header('Content-Disposition: attachment; filename="' . $fileName . '.xlsx"');
		$writer = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
		$writer->save('php://output');
		Yii::app()->end();
	}
}
