<?php defined('MW_PATH') || exit('No direct script access allowed');

/**
 * ArticlesController
 * 
 * Handles the actions for articles related tasks
 * 
 * @package MailWizz EMA
 * @author Serban George Cristian <cristian.serban@mailwizz.com> 
 * @link http://www.mailwizz.com/
 * @copyright 2013-2014 MailWizz EMA (http://www.mailwizz.com)
 * @license http://www.mailwizz.com/license/
 * @since 1.0
 */
 
class ArticlesController extends Controller
{
    public function init()
    {
        $this->getData('pageScripts')->add(array('src' => AssetsUrl::js('articles.js')));
        parent::init();
    }
    
    /**
     * Define the filters for various controller actions
     * Merge the filters with the ones from parent implementation
     */
    public function filters()
    {
        $filters = array(
            'postOnly + delete, slug',
        );
        
        return CMap::mergeArray($filters, parent::filters());
    }
    
    /**
     * List all available articles
     */
    public function actionIndex($id=null)
    {
        $request = Yii::app()->request;$notify = Yii::app()->notify;
        $article = new Article('search');
          if($request->isPostRequest) {
                $sortOrderAll = $_POST['priority'];
				if(count($sortOrderAll)>0)
				{
					foreach($sortOrderAll as $menuId=>$sortOrder)
					{
						$article->isNewRecord =true; 
						$article->updateByPk($menuId,array('priority'=>$sortOrder)); 
					}
				}
				  $notify->addSuccess(Yii::t('app', 'Priority successfully updated!'));
				  $this->redirect(Yii::app()->request->urlReferrer) ;
        }
        
        $article->unsetAttributes();
        
        // for filters.
        $article->attributes = (array)$request->getQuery($article->modelName, array());
        if(empty($id) and !empty($article->category_id2)){
            $id = $article->category_id2; 
        }
        $article->category_id2 = $id;
        if(!defined('CATEGORY')){
            define('CATEGORY',$id);
        }
        $title = 'CMS Pages';
		if(!empty($id)){
		$categoryModel = $this->loadCategoryModel($id);
		$title = $categoryModel->name;
		$article->category_id = $categoryModel->category_id;
		}
		if(!empty($id)){
			$ar =  array(
                Yii::t('articles', 'CMS Pages') => $this->createUrl('articles/index/'),
                Yii::t('articles', $title) => $this->createUrl('articles/index/id/'.$id),
                Yii::t('app', 'Create new'),
            );
		}
		else{
			$ar =  array(
                Yii::t('articles', 'CMS Pages') => $this->createUrl('articles/index'),
                Yii::t('app', 'Create new'),
            );
		}
        $this->setData(array(
            'pageMetaTitle'     => $this->data->pageMetaTitle . ' | '. Yii::t('articles', 'View '.$title),
            'pageHeading'       => Yii::t('articles', 'View '.$title),
            'pageBreadcrumbs'   =>  $ar ,
        ));
        
        $this->render('list', compact('article','id'));
    }
    public function loadCategoryModel($id)
    {
        $model = ArticleCategory::model()->findByAttributes(array(
            'category_id'      => $id,
            
        ));
        
        if ($model === null) {
            throw new CHttpException(404, Yii::t('app', 'The requested page does not exist.'));
        }
        
        return $model;
    }
    /**
     * Create a new article
     */
   public function actionCreate($cid=null)
    {
        $request    = Yii::app()->request;
        $notify     = Yii::app()->notify;
        $image_array = array();
        $caption_array = array();
        $article    = new Article();
        $articleToCategory = new ArticleToCategory();
		$title = 'CMS Page';
		if(!empty($cid)){
		$categoryModel = $this->loadCategoryModel($cid);
		$title = $categoryModel->name;
		$article->category_id = $categoryModel->category_id;
		}
        if ($request->isPostRequest && ($attributes = (array)$request->getPost($article->modelName, array()))) {
            $article->attributes = $attributes;
            if (isset(Yii::app()->params['POST'][$article->modelName]['content'])) {
                $article->content = Yii::app()->ioFilter->purify(Yii::app()->params['POST'][$article->modelName]['content']);
            }
            if (!$article->save()) {
                  $notify->addError(Yii::t('app', 'Your form has a few errors, please fix them and try again!'));
            } else {
                if ($categories = (array)$request->getPost($articleToCategory->modelName, array())) {
                    foreach ($categories as $category_id) {
                        $articleToCategory = new ArticleToCategory();
                        $articleToCategory->article_id = $article->article_id;
                        $articleToCategory->category_id = (int)$category_id;
                        $articleToCategory->save();
                    }
                }
                $notify->addSuccess(Yii::t('app', 'Your form has been successfully saved!'));
            }

            Yii::app()->hooks->doAction('controller_action_save_data', $collection = new CAttributeCollection(array(
                'controller'=> $this,
                'success'   => $notify->hasSuccess,
                'article'   => $article,
            )));

            if ($collection->success) {
                $this->redirect(array('articles/index/id/'.$cid));
            }
        }
		if(!empty($cid)){
			$ar =  array(
                Yii::t('articles', 'CMS Pages') => $this->createUrl('articles/index/'),
                Yii::t('articles', $title) => $this->createUrl('articles/index/id/'.$cid),
                Yii::t('app', 'Create new'),
            );
		}
		else{
			$ar =  array(
                Yii::t('articles', 'CMS Pages') => $this->createUrl('articles/index'),
                Yii::t('app', 'Create new'),
            );
		}
		      $this->getData('pageStyles')->add(array('src' => Yii::app()->apps->getBaseUrl('assets/css/select2.min.css')));
       $this->getData('pageScripts')->add(array('src' => Yii::app()->apps->getBaseUrl('assets/js/select2.min.js')));
		$this->getData('pageScripts')->add(array('src' =>'https://code.jquery.com/ui/1.11.2/jquery-ui.min.js'));
		 $this->getData('pageScripts')->add(array('src' =>Yii::app()->apps->getBaseUrl('assets/js/dropzone.min.js')));
		$this->getData('pageStyles')->add(array('src' =>Yii::app()->apps->getBaseUrl('assets/css/dropzone.css')));
	    $this->setData(array(
            'pageMetaTitle'     => $this->data->pageMetaTitle . ' | '. Yii::t('articles', 'Create new '.$title),
            'pageHeading'       => Yii::t('articles', 'Create new '.$title),
            'pageBreadcrumbs'   => $ar,
        ));

        $this->render('form', compact('article', 'articleToCategory','image_array','caption_array'));
    }

    /**
     * Update existing article
     */
    public function actionUpdate($id,$cid=null)
    {
        $article = Article::model()->findByPk((int)$id);

        if (empty($article)) {
            throw new CHttpException(404, Yii::t('app', 'The requested page does not exist.'));
        }

        $request = Yii::app()->request;
        $notify = Yii::app()->notify;
        $image_array = array();
        $caption_array = array();
        $articleToCategory = new ArticleToCategory();
		$title = 'CMS Page';
		if(!empty($cid)){
		$categoryModel = $this->loadCategoryModel($cid);
		$title = $categoryModel->name;
		$article->category_id = $categoryModel->category_id;
		}
        if ($request->isPostRequest && ($attributes = (array)$request->getPost($article->modelName, array()))) {
            $article->attributes = $attributes;
            if (isset(Yii::app()->params['POST'][$article->modelName]['content'])) {
                $article->content = Yii::app()->ioFilter->purify(Yii::app()->params['POST'][$article->modelName]['content']);
            }
            if (!$article->save()) {
                  $notify->addError(Yii::t('app', 'Your form has a few errors, please fix them and try again!'));
            } else {
                ArticleToCategory::model()->deleteAllByAttributes(array('article_id' => $article->article_id));
                if ($categories = (array)$request->getPost($articleToCategory->modelName, array())) {
                    foreach ($categories as $category_id) {
                        $articleToCategory = new ArticleToCategory();
                        $articleToCategory->article_id = $article->article_id;
                        $articleToCategory->category_id = (int)$category_id;
                        $articleToCategory->save();
                    }
                }
                $notify->addSuccess(Yii::t('app', 'Your form has been successfully saved!'));
            }

            Yii::app()->hooks->doAction('controller_action_save_data', $collection = new CAttributeCollection(array(
                'controller'=> $this,
                'success'   => $notify->hasSuccess,
                'article'   => $article,
            )));

            if ($collection->success) {
                $this->refresh();//(array('articles/index/id/'.$cid));
                $this->redirect(array('articles/index/id/'.$cid));
            }
        }
	 
	 	if(!empty($cid)){
			$ar =  array(
                Yii::t('articles', 'CMS Pages') => $this->createUrl('articles/index/'),
                Yii::t('articles', $title) => $this->createUrl('articles/index/id/'.$cid),
                Yii::t('app', 'Update'),
            );
		}
		else{
			$ar =  array(
                Yii::t('articles', 'CMS Pages') => $this->createUrl('articles/index'),
                Yii::t('app', 'Update'),
            );
		}
		      $this->getData('pageStyles')->add(array('src' => Yii::app()->apps->getBaseUrl('assets/css/select2.min.css')));
       $this->getData('pageScripts')->add(array('src' => Yii::app()->apps->getBaseUrl('assets/js/select2.min.js')));
        $this->getData('pageScripts')->add(array('src' =>Yii::app()->apps->getBaseUrl('assets/js/dropzone.min.js')));
		$this->getData('pageStyles')->add(array('src' =>Yii::app()->apps->getBaseUrl('assets/css/dropzone.css')));
	    $this->setData(array(
            'pageMetaTitle'     => $this->data->pageMetaTitle . ' | '. Yii::t('articles', 'Update '.$title),
            'pageHeading'       => Yii::t('articles', 'Update '.$title),
            'pageBreadcrumbs'   => $ar , 
        ));

        $this->render('form', compact('article', 'articleToCategory','image_array','caption_array'));
    }
    public function actionupdate_language($parent_id = null, $lan=null)
    {
       
       $parent_article = Article::model()->findByPk($parent_id);

        if (empty($parent_article)) {
            throw new CHttpException(404, Yii::t('app', 'The requested page does not exist.'));
        }

        $article = Article::model()->findByAttributes(['parent_article' => $parent_id, 'language' => $lan]);
        if(empty($article)){
            $article =  new Article();
            $article->attributes = $parent_article->attributes; 
            $article->parent_article = $parent_id;
            $article->language = $lan;

        }

        $request = Yii::app()->request;
        $notify = Yii::app()->notify;
        $image_array = array();
        $caption_array = array();
        $articleToCategory = new ArticleToCategory();
		$title = 'CMS Page';
		if(!empty($cid)){
		$categoryModel = $this->loadCategoryModel($cid);
		$title = $categoryModel->name;
		$article->category_id = $categoryModel->category_id;
		}
        if ($request->isPostRequest && ($attributes = (array)$request->getPost($article->modelName, array()))) {
            $article->attributes = $attributes;
            if (isset(Yii::app()->params['POST'][$article->modelName]['content'])) {
                $article->content = Yii::app()->ioFilter->purify(Yii::app()->params['POST'][$article->modelName]['content']);
            }
            if (!$article->save()) {
                  $notify->addError(Yii::t('app', 'Your form has a few errors, please fix them and try again!'));
            } else {
                ArticleToCategory::model()->deleteAllByAttributes(array('article_id' => $article->article_id));
                if ($categories = (array)$request->getPost($articleToCategory->modelName, array())) {
                    foreach ($categories as $category_id) {
                        $articleToCategory = new ArticleToCategory();
                        $articleToCategory->article_id = $article->article_id;
                        $articleToCategory->category_id = (int)$category_id;
                        $articleToCategory->save();
                    }
                }
                $notify->addSuccess(Yii::t('app', 'Your form has been successfully saved!'));
            }

            Yii::app()->hooks->doAction('controller_action_save_data', $collection = new CAttributeCollection(array(
                'controller'=> $this,
                'success'   => $notify->hasSuccess,
                'article'   => $article,
            )));

            if ($collection->success) {
                $this->redirect(Yii::app()->createUrl('articles/update',['id'=> $parent_article->primaryKey]));
           
            }
        }
	 
	 	if(!empty($cid)){
			$ar =  array(
                Yii::t('articles', 'CMS Pages') => $this->createUrl('articles/index/'),
                Yii::t('articles', $title) => $this->createUrl('articles/index/id/'.$cid),
                Yii::t('app', 'Update'),
            );
		}
		else{
			$ar =  array(
                Yii::t('articles', 'CMS Pages') => $this->createUrl('articles/index'),
                Yii::t('app', 'Update'),
            );
		}
		      $this->getData('pageStyles')->add(array('src' => Yii::app()->apps->getBaseUrl('assets/css/select2.min.css')));
       $this->getData('pageScripts')->add(array('src' => Yii::app()->apps->getBaseUrl('assets/js/select2.min.js')));
        $this->getData('pageScripts')->add(array('src' =>Yii::app()->apps->getBaseUrl('assets/js/dropzone.min.js')));
		$this->getData('pageStyles')->add(array('src' =>Yii::app()->apps->getBaseUrl('assets/css/dropzone.css')));
	    $this->setData(array(
            'pageMetaTitle'     => $this->data->pageMetaTitle . ' | '. Yii::t('articles', 'Update '.$title),
            'pageHeading'       => Yii::t('articles', 'Update '.$title),
            'pageBreadcrumbs'   => $ar , 
        ));

        $this->render('form', compact('article', 'articleToCategory','image_array','caption_array', 'parent_article'));
    }
    /**
     * Delete an existing article
     */
    public function actionDelete($id)
    {
        $article = Article::model()->findByPk((int)$id);
        
        if (empty($article)) {
            throw new CHttpException(404, Yii::t('app', 'The requested page does not exist.'));
        }
        
        $article->delete();
        
        $request    = Yii::app()->request;
        $notify     = Yii::app()->notify;
        
        if (!$request->getQuery('ajax')) {
            $notify->addSuccess(Yii::t('app', 'The item has been successfully deleted!'));
            $this->redirect($request->getPost('returnUrl', array('articles/index')));
        }
    }
    
    /**
     * generate the slug for an article based on the article title
     */
    public function actionSlug()
    {
        $request = Yii::app()->request;
        
        if (!$request->isAjaxRequest) {
            $this->redirect(array('articles/index'));    
        }

        $article = new Article();
        $article->article_id = (int)$request->getPost('article_id');
        $article->slug = $request->getPost('string');
        
        $category = new ArticleCategory();
        $category->slug = $article->slug;
        
        $article->slug = $category->generateSlug();
        $article->slug = $article->generateSlug();
        
        return $this->renderJson(array('result' => 'success', 'slug' => $article->slug));
    }
    public function actionUpload($width=null,$height=null)
    {
	  ini_set('memory_limit', '-1'); $this->fileUploadDropzone();exit;    
	}
	public function fileUploadDropzone(){
		
			$path_file =  Yii::getPathOfAlias('root.uploads.files');
			$file_format = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
			$file_title = pathinfo($_FILES['file']['name'], PATHINFO_FILENAME);
			$img = date('Y-m-d-h-i-s').'-'.rand(0,9999).'-'.time().".".$file_format;
			$year_folder = $path_file .'/'. date("Y");
			$month_folder = $year_folder . '/' . date("m");
			$month_folder2 = date("Y"). '/' . date("m");
			!file_exists($year_folder) && mkdir($year_folder , 0777);
			!file_exists($month_folder) && mkdir($month_folder, 0777);
			 $path_file = $month_folder ;
			 move_uploaded_file($_FILES['file']['tmp_name'], $path_file."/{$img}");
			if(isset($_POST['rand'])){
				echo json_encode(array('img'=> $month_folder2. '/' .$img,'rand'=>$_POST['rand'],'file_title'=>Yii::t('app',$file_title,array('_'=>'','-'=>''))));exit;
			} 
			echo  $month_folder2. '/' .$img; exit; 
		 
	}
	function actionDelete_image()
	{
		 
	
		$str="";
		if(isset($_POST['inp']))
		{
		 
			 
			$ar = explode(',',$_POST['inp']);
			 
			 
			if($ar)
			{
				foreach($ar as $k=>$val)
				{
					 
					if($val!=$_POST['file'] and $val!="")
					{
						 
						$str .= ",".$val;
						 
					}
				}
			}
			 
		}
		echo $str; 
		 
    
   }
}
