<?php

class CurrencyController 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 Currency;

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

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

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

	public function actionExport()
	{

		$model=new Currency;
		 
		$d= $model->search();
  

		$attributes=array(

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

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

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

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

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

			  [
                   'label' =>Yii::t("Currency","up_down"),
                   'exp' => '$obj->up_down'
             ],
		
			);
			
		$fileName='Currency';
		$this->exportDataProviderAsExcel( $d,$attributes,$fileName);
		
	}

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

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

		if(isset($_POST['Currency']))
		{
			$model->attributes=$_POST['Currency'];
			
				
			//   if($model->validate())
			//   {
                $xlsFile=CUploadedFile::getInstance($model,'import_file');  
				// init phpexcel
				Yii::import ( 'ext.phpexcel.XPHPExcel' );
				XPHPExcel::init ();
				// read file
				
				if($xlsFile!=Null){
				$phpExcel = PHPExcel_IOFactory::load ( $xlsFile->getTempName());
				try {
					//delete all currency
					Currency::model()->deleteAll();
					
					$worksheet = $phpExcel->setActiveSheetIndex ( 0 );
					//get first row
					$issue_number=$worksheet->getCellByColumnAndRow ( 0, 2)->getValue ();
					$issue_date=$worksheet->getCellByColumnAndRow ( 1, 2)->getValue ();
					$issue_time=$worksheet->getCellByColumnAndRow ( 2, 2)->getValue ();
					$issue_AmPmtime=$worksheet->getCellByColumnAndRow ( 3, 2)->getValue ();

					$option= new Option;
					$option->updateCurrencyIssue($issue_number,$issue_date,$issue_time,$issue_AmPmtime);

					//get the html content

					//update html content

					//save
					for($row = 4; $row <= $worksheet->getHighestDataRow (); $row ++) {
						//add new currency for each record
						$curr= new Currency;
						$curr->symbol_code=$worksheet->getCellByColumnAndRow ( 0, $row )->getValue ();
						$curr->title=$worksheet->getCellByColumnAndRow ( 1, $row )->getValue ();
						$curr->en_title=$worksheet->getCellByColumnAndRow ( 2, $row )->getValue ();
						$curr->Buy_rate=$worksheet->getCellByColumnAndRow ( 3, $row )->getValue ();
						$curr->Sell_rate=$worksheet->getCellByColumnAndRow ( 4, $row )->getValue ();
						$curr->up_down=$worksheet->getCellByColumnAndRow ( 5, $row )->getValue ();
						
						//example how to get the data cell from the record
						// $worksheet->getCellByColumnAndRow ( 0, $row )->getValue ();
						 if(!$curr->save())
						 	var_dump($curr->getErrors());
						
					}
				}
				catch ( Exception $ex ) {
					var_dump($ex);
				}
				$this->redirect(array('admin', 'id' => $model->id));
				  }


		}

		$this->render('import',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['Currency']))
		{
			$model->attributes=$_POST['Currency'];
			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('Currency');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

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

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

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



		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;
//issue_number
		$option_issue_numberModel=option::model()->findByAttributes(array('key'=>'ISSUE_NUMBER' ));
        // $option_issue_numberModel->value=$issue_number;

		$sheet->setCellValueByColumnAndRow ( 0, 1, 'رقم الإصدار' );
		$sheet->getColumnDimensionByColumn ( 0 )->setWidth ( 20 );
		$sheet->getStyleByColumnAndRow ( 0, 1 )->applyFromArray ( [ 
				'fill' => [ 
						'type' => PHPExcel_Style_Fill::FILL_SOLID,
						'color' => array (
								'rgb' => 'CCCCCC' 
						) 
				] 
		] );
		$sheet->setCellValueByColumnAndRow ( 0, 2, $option_issue_numberModel->value );
//issue_date
		$option_issue_dateModel=option::model()->findByAttributes(array('key'=>'ISSUE_DATE' ));

		$sheet->setCellValueByColumnAndRow ( 1, 1, 'تاريخ النشرة' );
		$sheet->getColumnDimensionByColumn ( 1 )->setWidth ( 20 );
		$sheet->getStyleByColumnAndRow ( 1, 1 )->applyFromArray ( [ 
				'fill' => [ 
						'type' => PHPExcel_Style_Fill::FILL_SOLID,
						'color' => array (
								'rgb' => 'CCCCCC' 
						) 
				] 
		] );
		$sheet->setCellValueByColumnAndRow ( 1, 2, $option_issue_dateModel->value );

//issue_time
		$option_issue_timeModel=option::model()->findByAttributes(array('key'=>'ISSUE_TIME' ));

		$sheet->setCellValueByColumnAndRow ( 2, 1, 'الساعة' );
		$sheet->getColumnDimensionByColumn ( 2 )->setWidth ( 20 );
		$sheet->getStyleByColumnAndRow ( 2, 1 )->applyFromArray ( [ 
				'fill' => [ 
						'type' => PHPExcel_Style_Fill::FILL_SOLID,
						'color' => array (
								'rgb' => 'CCCCCC' 
						) 
				] 
		] );
		$sheet->setCellValueByColumnAndRow ( 2, 2, $option_issue_timeModel->value );

//issue_AmPmtime
  		$option_issue_AmPmtimeModel=option::model()->findByAttributes(array('key'=>'ISSUE_AM_PM_TIME' ));

		$sheet->setCellValueByColumnAndRow ( 3, 1, 'am or pm' );
		$sheet->getColumnDimensionByColumn ( 3 )->setWidth ( 20 );
		$sheet->getStyleByColumnAndRow ( 3, 1 )->applyFromArray ( [ 
				'fill' => [ 
						'type' => PHPExcel_Style_Fill::FILL_SOLID,
						'color' => array (
								'rgb' => 'CCCCCC' 
						) 
				] 
		] );
		$sheet->setCellValueByColumnAndRow ( 3, 2, $option_issue_AmPmtimeModel->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 ( 20 );
			$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 ();
	}
}
