<?php

class MenuItemController extends RController {

    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) {
        $model = $this->loadModel($id);
        if (Yii::app()->request->isAjaxRequest) {
            $this->renderPartial('view', array(
                'model' => $model,
                    ), false, true);
            Yii::app()->end();
        } else {
            $this->render('view', array(
                'model' => $model,
            ));
        }
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate($menu_id) {
        $menu = Menu::model()->findByPk($menu_id);
        if ($menu === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        $model = new MenuItem;
        if (Yii::app()->options->get('I18N_MULTILINGUAL', 0) == 0) {
            $model->language = Yii::app()->language;
        }
        $model->menu_id = $menu_id;
        $menuItems = MenuItem::model()->findAllByAttributes(array('menu_id' => $menu_id));
        if (isset($_POST['MenuItem'])) {
            $rnd =uniqid();
            $model->attributes = $_POST['MenuItem'];

            $model->image =CUploadedFile::getInstance($model,'image');
			if( $model->image != null && $model->validate(['image']))
			{
                $uploadedFile = $model->image;
				$fileName = "{$rnd}-{$uploadedFile}";  // random number + file name
				$model->image = $fileName;
				$uploadedFile->saveAs(Yii::app()->basePath.'/../uploads/MenuItem/'.$fileName);
			}


			$model->create_datetime=strtotime("now");
			$model->update_datetime=strtotime("now");
			
            if ($model->save()) {
                Yii::app()->user->setFlash('alert-success', Yii::t('admin', 'MenuItem has been successfully created.'));
                $this->redirect(array('create', 'menu_id' => $menu_id));
            }
        }
        $this->render('form', array(
            'model' => $model,
            'menu' => $menu,
            'menuItems' => $menuItems,
        ));
    }

    /**
     * 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, $menu_id) {
        $menu = Menu::model()->findByPk($menu_id);
        if ($menu === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        $model = $this->loadModel($id);
        $old_image=$model->image;
        $model->menu_id = $menu_id;
        $menuItems = MenuItem::model()->findAllByAttributes(array('menu_id' => $menu_id), 'id !=:id', array(':id' => $model->id));
        if (isset($_POST['MenuItem'])) {
            $rnd =uniqid();
            $model->attributes = $_POST['MenuItem'];
            
            $model->image = CUploadedFile::getInstance($model,'image');
           
			if( $model->image != null && $model->validate(['image']))
			{
                $uploadedFile = $model->image;
				$fileName = "{$rnd}-{$uploadedFile}";  // random number + file name
				$model->image = $fileName;
				$uploadedFile->saveAs(Yii::app()->basePath.'/../uploads/MenuItem/'.$fileName);
			}

			//$model->create_datetime=strtotime("now");
			$model->update_datetime=strtotime("now");
			
            
           if($model->validate()){
                if($model->image==null && $old_image!=null)
                    $model->image=$old_image;
                if ($model->save(false)) {

                Yii::app()->user->setFlash('alert-success', Yii::t('admin', 'MenuItem has been successfully updated.'));
                $this->redirect(array('admin', 'menu_id' => $menu_id));
            }
        }
        }
        $this->render('form', array(
            'model' => $model,
            'menu' => $menu,
            'menuItems' => $menuItems,
        ));
    }

    /**
     * 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'));
        }
    }

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

}
