<?php
class ArticleController extends RController
{

    /**
     * @return array action filters
     */
    public function filters()
    {
        return array(
            'rights',
            'postOnly + delete', // we only allow deletion via POST request
        );
    }

    public function actions()
    {
        return array(
            'batchOperation' => array(
                'class' => 'admin.components.actions.BatchOperationAction',
            ),
            'export' => array(
                'class' => 'admin.components.actions.ExportAction',
                'modelClass' => 'Article',
            ),
            'upload' => array(
                'class' => 'xupload.actions.XArticleAlbumUploadAction',
                'path' => Yii::app()->params['uploadDir'] . 'ArticleAlbum',
                'publicPath' => Yii::app()->params['uploadUrl'] . 'ArticleAlbum',
                'subfolderVar' => false,
            ),
        );
    }

    public function actionSuggestLink($q, $limit)
    {

        if (($q = trim($q)) !== '') {

            $models = Article::model()->findAll(array(
                'condition' => "t.title LIKE :keyword",
                'order' => "t.title",
                'limit' => $limit,
                'params' => array(":keyword" => "%{$q}%")
            ));

            $suggest = array();
            if ($models) {
                foreach ($models as $model) {
                    $suggest[] = $model->title . '|' . MenuItem::stripBaseUrl($this->createUrl('/article/view', array('slug' => $model->slug)));
                }
            }
            echo implode("\n", $suggest);
        }
    }

    /**
     * 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()
    {
        Yii::import("ext.xupload.models.XUploadForm");
        $uploader = new XUploadForm;

        $model = new Article('ceate');

        if (Yii::app()->options->get('I18N_MULTILINGUAL', 0) == 0) {
            $model->language = Yii::app()->language;
        }

        if (isset($_POST['Article'])) {
            $model->attributes = $_POST['Article'];
            $baseUrl = Yii::app()->basePath;
            $model->attachment_url = CUploadedFile::getInstance($model, 'attachment_url');
            if ($model->attachment_url != null && $model->validate(['attachment_url'])) {
                $file = $model->attachment_url;
                $filename = uniqid('attachment') . '.pdf';
                $test = $baseUrl . '/../uploads/Article/files/' . $filename;
                $model->attachment_url = $test;
                $model->attachment_title = $filename;
                $file->saveAs($test);
            }

            //// flash file
            $model->flash_file = CUploadedFile::getInstance($model, 'flash_file');

            if ($model->flash_file != null && $model->validate(['flash_file'])) {
                $flash_file = $model->flash_file;
                $filename = uniqid('flash_file') . '.' . $flash_file->getExtensionName();
                $flash_path = $baseUrl . '/../uploads/Article/files/' . $filename;
                $model->flash_file = $filename;
                if (!$flash_file->saveAs($flash_path)) {
                    var_dump($flash_file->getErrors());
                    die;
                }
            }

            try {
                ImageHelper::resize($model, 'image');
            } catch (Exception $e) {
                $model->addError('image', $e->getMessage());
                $this->render('create', array(
                    'model' => $model,
                    'uploader' => $uploader,
                ));
                return;
            }

            if ($model->save()) {

                $article_id = Yii::app()->request->getPost('article_id', false);

                if ($article_id) {
                    $images = ArticleAlbum::model()->findAllByAttributes(array('article_id' => $article_id));
                    foreach ($images as $image) {
                        $image->article_id = $model->id;
                        $image->save();
                    }
                }

                Yii::app()->user->setFlash('alert-success', Yii::t('admin', 'Item has been successfully created.'));
                $this->redirect(array('admin'));
            }
        }
        $this->render('create', array(
            'model' => $model,
            'uploader' => $uploader,
        ));
    }

    /**
     * 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)
    {
        Yii::import("xupload.models.XUploadForm");
        $uploader = new XUploadForm;

        $model = $this->loadModel($id);
        $model->scenario = 'ceate';
        $old_value = $model->image;
        $old_pdf = $model->attachment_url;
        $old_flash = $model->flash_file;
        // var_dump( $old_value);

        $old_value_background = $model->background;
        if (isset($_POST['Article'])) {

            $model->attributes = $_POST['Article'];
            // var_dump($model->en_title);
            $model->create_datetime = $model->published_time;
            try {
                ImageHelper::resize($model, 'image', $old_value);
            } catch (Exception $e) {
                $model->addError('image', $e->getMessage());
                $this->render('create', array(
                    'model' => $model,
                    'uploader' => $uploader,
                ));
                return;
            }
            //  ImageHelper::resize($model, 'image', $old_value);

            try {
                ImageHelper::resize($model, 'background', $old_value_background);
            } catch (Exception $e) {
                $model->addError('background', $e->getMessage());
                $this->render('create', array(
                    'model' => $model,
                    'uploader' => $uploader,
                ));
                return;
            }

            $baseUrl = Yii::app()->basePath;
            $model->attachment_url = CUploadedFile::getInstance($model, 'attachment_url');
            if ($model->attachment_url != null && $model->validate(['attachment_url'])) {
                $file = $model->attachment_url;
                $filename = uniqid('attachment') . '.pdf';
                $test = $baseUrl . '/../uploads/Article/files/' . $filename;
                $model->attachment_url = $test;
                $model->attachment_title = $filename;
                $file->saveAs($test);
            } else {
                $model->attachment_url = $old_pdf;
            }

            $model->flash_file = CUploadedFile::getInstance($model, 'flash_file');
            if ($model->flash_file != null && $model->validate(['flash_file'])) {
                $flash_file = $model->flash_file;
                $filename = uniqid('flash_file') . '.' . $flash_file->getExtensionName();
                $flash_path = $baseUrl . '/../uploads/Article/files/' . $filename;
                $model->flash_file = $filename;
                $flash_file->saveAs($flash_path);
            } else {
                $model->flash_file = $old_flash;
                // var_dump($old_flash);
                // die;
            }
            // var_dump($model->attributes);
            if ($model->validate()) {
                if ($model->image == null && $old_value != null)
                    $model->image = $old_value;

                if ($model->flash_file == null && $old_flash != null)
                    $model->flash_file = $old_flash;

                if ($model->save(false)) {
                    Yii::app()->user->setFlash('alert-success', Yii::t('admin', 'Item has been successfully updated.'));
                    //var_dump($model->attributes);
                    $this->redirect(array('admin'));
                }
            }
        }
        $this->render('update', array(
            'model' => $model,
            'uploader' => $uploader,
        ));
    }

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

        //        if ($model->productImages !== NULL) {
        //            foreach ($model->productImages as $image) {
        //                ImageHelper::remove($image, 'image');
        //            }
        //        }
        ImageHelper::remove($model, 'image');
        $model->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'));
        }
    }

    public function actionDelete_pdf($id)
    {
        $model = $this->loadModel($id);
        $model->scenario = 'deletepdf';
        $model->attachment_title = Null;
        if ($model->save()) {
            $this->redirect(array('admin'));
        } else {
            var_dump($model->getErrors());
        }
    }

    public function actionDeleteImage($id)
    {
        $model = $this->loadModel($id);
        ImageHelper::remove($model, 'image');
        $model->scenario = 'deletepdf';
        $model->image = Null;
        if ($model->save()) {
            $this->redirect(array('admin'));
        } else {
            var_dump($model->getErrors());
        }
    }

    public function actionDelete_flash($id)
    {
        $model = $this->loadModel($id);
        // $model->scenario='deletepdf';
        $model->flash_file = Null;
        if ($model->save()) {
            $this->redirect(array('admin'));
        } else {
            var_dump($model->getErrors());
        }
    }


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

    public function actionQuickUpdate()
    {
        $es = new EditableSaver('Article');
        $es->update();
    }

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

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