<?php

class SuggestionsController 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 Suggestions;

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

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

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
	
		$model=new Suggestions('search');
		
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Suggestions'])){
			$model->attributes=$_GET['Suggestions'];
		}
			
		$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 Suggestions the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Suggestions::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

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


	public function actions()
	{
		return array(
			'captcha'=>array(
			'class'=>'CCaptchaAction',
			'backColor'=>0xFFFFFF,
			),
		);
	}

	public function actionExport()
	{
		
		$model=new Suggestions;
		
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Suggestions'])){
			$model->attributes=$_GET['Suggestions'];
			$startDate=$model->startDate;
			$endDate=$model->endDate;
		}
		 
		$d= $model->searchExport($startDate,$endDate);
  

		$attributes=array(

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

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

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

			 [
                   'label' =>Yii::t("suggestion","mail"),
                   'exp' => '$obj->mail'
             ],
			 [
                   'label' =>Yii::t("suggestion","phone"),
                   'exp' => '$obj->phone'
             ],
			  [
                   'label' =>Yii::t("suggestion","call_time"),
                   'exp' => '$obj->call_time'
             ],
			  [
                   'label' =>Yii::t("suggestion","note_date"),
                   'exp' => '$obj->note_date'
             ],

			  [
                   'label' =>Yii::t("suggestion","place"),
                   'exp' => '$obj->place'
             ],
			[
                   'label' =>Yii::t("suggestion","relat"),
                   'exp' => '$obj->relat'
             ],

			  [
                   'label' =>Yii::t("suggestion","message"),
                   'exp' => '$obj->message'
             ],
		
			);
			
		$fileName='Suggestions from '.$startDate.' to '.$endDate;
		$this->exportDataProviderAsExcel( $d,$attributes,$fileName,$startDate,$endDate);
		
	}

	public static function exportDataProviderAsExcel($dataProvider, $attributes, $fileName,$startDate,$endDate) {
		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
		// $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, $startDate );
//issue_date

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

//issue_time


//issue_AmPmtime


		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 ();
	}




}
