<?php

class CarouselController extends ModuleAdminController
{

    public $modelName = 'Carousel';
    public $defaultAction = 'admin';

    public function init()
    {
        parent::init();
        Yii::app()->user->setState('menu_active', 'slider.carousel');
    }

    public function getViewPath($checkTheme = true)
    {
        if ($checkTheme && ($theme = Yii::app()->getTheme()) !== null) {
            if (is_dir($theme->getViewPath() . DIRECTORY_SEPARATOR . 'modules' . DIRECTORY_SEPARATOR . $this->getModule($this->id)->getName() . DIRECTORY_SEPARATOR . 'views' . DIRECTORY_SEPARATOR . Yii::app()->controller->id))
                return $theme->getViewPath() . DIRECTORY_SEPARATOR . 'modules' . DIRECTORY_SEPARATOR . $this->getModule($this->id)->getName() . DIRECTORY_SEPARATOR . 'views' . DIRECTORY_SEPARATOR . Yii::app()->controller->id;
        }
        return Yii::getPathOfAlias('application.modules.' . $this->getModule($this->id)->getName() . '.views.' . Yii::app()->controller->id);
    }

    public function accessRules()
    {
        return array(
            array('allow',
                'expression' => "Yii::app()->user->checkAccess('all_modules_admin')",
            ),
            array('deny',
                'users' => array('*'),
            ),
        );
    }

    public function actionView($id)
    {
        $this->redirect(array('admin'));
    }

//    public function actionAdmin(){
//        $this->getMinSorter();
//        $this->getMaxSorter();
//        parent::actionAdmin();
//    }

    public function actionCreate()
    {
        $model = Carousel::model()->findByAttributes(array('status' => Carousel::STATUS_DRAFT));

        if (!$model) {
            $model = new Carousel();
            $model->status = Carousel::STATUS_DRAFT;
            $model->save(false);
        }

        if (isset($_POST["{$this->modelName}"])) {
            $model->attributes = $_POST["{$this->modelName}"];

            if ($model->validate()) {
                $model->status = Carousel::STATUS_ACTIVE;

                if ($model->save()) {
                    Yii::app()->user->setFlash(
                        'success', tc('Success')
                    );
                    $model->unsetAttributes();

                    $this->redirect(array('admin'));
                }
            }
        }

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

    public function actionUploadImages($id)
    {

        $carousel = Carousel::model()->findByPk($id);
        if (!$carousel) {
            $result['error'] = 'not carousel model';
        }

        // check maximum file upload for ad
        $maxImgs = Carousel::getMaxPhotos();

        $currImgCount = 0;

        $uploadPath = Carousel::getUploadPath() . DIRECTORY_SEPARATOR . $id;

        if ($carousel->images) {
            $currImgCount = count($carousel->images);
        }

        if ($currImgCount >= $maxImgs) {
            $result['error'] = Yii::t("module_images", "You are trying to download more than {num} pictures", array("{num}" => $maxImgs));
        } elseif (!isset($result['error'])) {
            Yii::import("ext.EAjaxUpload.qqFileUploader");

            $allowedExtensions = param('allowedImgExtensions', array('jpg', 'jpeg', 'gif', 'png'));

            //$sizeLimit = param('maxImgFileSize', 8 * 1024 * 1024);
            $sizeLimit = Images::getMaxSizeLimit();

            $uploader = new qqFileUploader($allowedExtensions, $sizeLimit);


            $oldUMask = umask(0);
            if (!is_dir($uploadPath)) {
                @mkdir($uploadPath, 0777, true);
            }
            umask($oldUMask);

            if (is_writable($uploadPath)) {
                touch($uploadPath . DIRECTORY_SEPARATOR . 'index.htm');

                $existsFiles = getFilesNameArrayInPathWithoutHtml($uploadPath);
                if (count($existsFiles)) {
                    $maxNumber = 0;
                    foreach ($existsFiles as $file) {
                        $fileExp = explode('__', $file);
                        $p = (int)$fileExp[0];
                        if ($p >= $maxNumber)
                            $maxNumber = $p + 1;
                    }
                    $number = $maxNumber;
                } else {
                    $number = $currImgCount + 1;
                }

                $result = $uploader->handleUpload($uploadPath . DIRECTORY_SEPARATOR, false, $number . '__' . uniqid());

                if (isset($result['success']) && $result['success']) {
                    $resultMemoryCheck = HSite::allowUploadAndResizeImage($uploadPath . DIRECTORY_SEPARATOR . $result['filename']);

                    if ($resultMemoryCheck['result'] === true) {
                        $resize = new CImageHandler();
                        if ($resize->load($uploadPath . DIRECTORY_SEPARATOR . $result['filename'])) {
                            $resize->thumb(param('maxImageWidth', 1024), param('maxImageHeight', 768), Images::KEEP_PHOTO_PROPORTIONAL)
                                ->save();

                            $model = new CarouselImages();
                            $maxSorter = Yii::app()->db->createCommand()
                                ->select('MAX(sorter) as maxSorter')
                                ->from($model->tableName())
                                ->where('carousel_id = :carousel_id', array(':carousel_id' => $id))
                                ->queryScalar();

                            $model->image = $result['filename'];
                            $model->carousel_id = $id;
                            $model->sorter = $maxSorter + 1;
                            $model->save();
                        } else {
                            $result['error'] = 'Wrong image type.';
                            @unlink($uploadPath . DIRECTORY_SEPARATOR . $result['filename']);
                        }
                    } else {
                        @unlink($uploadPath . DIRECTORY_SEPARATOR . $result['filename']);
                        $result['error'] = tc('Upload failed. To upload image please increase the amount of RAM in your hosting.') . '(Minimum: ' . $resultMemoryCheck['memoryImageNeededInMB'] . 'MB)';
                    }
                }
            } else {
                $result['error'] = 'Access denied.';
            }
        }

        // to pass data through iframe you will need to encode all html tags
        $result = htmlspecialchars(json_encode($result), ENT_NOQUOTES);
        echo $result;
    }

    public function actionGetImages($id)
    {
        $carousel = $this->loadModel($id);

        $this->widget('application.modules.slider.components.CarouselAdminWidget', array(
            'images' => $carousel->images,
            'afterRefresh' => true,
        ));
        Yii::app()->end();
    }

    public function actionDeleteImage($id)
    {
        $carouselImage = CarouselImages::model()->findByPk($id);

        $carouselImage->delete();
    }

    public function actionSort($id)
    {
        $model = $this->loadModel($id);

        $ids = Yii::app()->request->getPost('image');

        if ($ids) {
            $sorter = 0;
            foreach ($ids as $id) {
                $sql = 'UPDATE {{carousel_images}} SET sorter=:sorter WHERE id=:id AND carousel_id=:carousel_id';
                Yii::app()->db->createCommand($sql)->execute(array(
                    ':sorter' => $sorter,
                    ':id' => $id,
                    ':carousel_id' => $model->id,
                ));
                $sorter++;
            }
        }
    }

    public function actionAjaxSave()
    {
        if (isset($_POST['CarouselImages'])) {
            $model = CarouselImages::model()->findByPk($_POST['CarouselImages']['id']);

            $model->attributes = $_POST['CarouselImages'];

            if ($model->save()) {
                echo CJSON::encode(array(
                    'status' => 'ok',
                    'html' => $this->renderPartial('widgets/_carousel_image_form', array('image' => $model, 'afterRefresh' => true), true)
                ));
                Yii::app()->end();
            } else {
                echo CJSON::encode(array(
                    'status' => 'err',
                    'html' => $this->renderPartial('widgets/_carousel_image_form', array('image' => $model, 'afterRefresh' => true), true)
                ));
                Yii::app()->end();
            }
        }
        throw404();
    }
}
