<?php
namespace frontend\controllers;

use Yii;
use yii\base\InvalidArgumentException;
use yii\web\BadRequestHttpException;
use yii\web\NotFoundHttpException;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use backend\models\News;
use backend\models\Blog;
use backend\models\NewsCategory;
use yii\helpers\Url;
use frontend\models\NewsComments;

class NewsController extends Controller {

    /**
     * @inheritdoc
     */
    public function behaviors() {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['index', 'view'],
                        'allow' => true,
                        'roles' => ['?', '@']
                    ],
                ]
            ],
        ];
    }
	
	public function actionIndex() {
     	$caQuery = News::find()->where(['status' => 1]);
		$catDataProvider = new ActiveDataProvider([

            'query' => $caQuery,
            'sort' => [
                'defaultOrder' => [
                    'id' => SORT_DESC,
                ]
            ],
            'pagination' => [
                'pageSize' => 10,
        ]]);
		return $this->render('index', [
					'catDataProvider' => $catDataProvider,
		]);
    }

      public function actionView($slug) {
	    $this->layout = 'newsview';
		$modelcomment = new NewsComments();
		$postQueryy = News::find()->where(['slug' => $slug, 'status' => 1])->one();
		if(isset($postQueryy)) {
		$totalview = ($postQueryy->news_view + 1);
$connection = Yii::$app->db;
			$command = $connection->createCommand()->update('news', ['news_view' => $totalview], ['status' => 1, 'id' => $postQueryy->id])->execute();
			$connection->close();
		$postQuery = News::find()->where(['slug' => $slug, 'status' => 1])->one();
		 $relatedBlog = News::find()->where(['cat_id' => $postQuery->cat_id, 'status' => 1])->AndWhere(['!=', 'id', $postQuery->id])->orderBy(['id' => SORT_DESC])->limit(15)->all();
		 $recentBlog = News::find()->where(['status' => 1])->AndWhere(['!=', 'id', $postQuery->id])->orderBy(['id' => SORT_DESC])->limit(5)->all();
		 $popularBlog = Blog::find()->where(['status' => 1])->orderBy(['blog_view' => SORT_DESC])->limit(10)->all();
		 $count_all = NewsComments::find()->where(['status' => 1])->andwhere(['news_id' => $postQuery->id])->all();
		 $comments_all = NewsComments::find()->where(['status' => 1])->andwhere(['parent_id' => 0])->andwhere(['news_id' => $postQuery->id])->orderBy(['id' => SORT_DESC])->all();
		 if ($modelcomment->load(Yii::$app->request->post())) {
	             Yii::$app->getSession()->destroy();
			if (Yii::$app->request->isAjax) {
				Yii::$app->response->format = Response::FORMAT_JSON;
				return ActiveForm::validate($modelcomment);
			}
			
			$modelcomment->news_id = $postQuery->id;
		  if($modelcomment->save(false)) {
            \Yii::$app->getSession()->setFlash('copmssg', 'Your Comment will only be visible after moderation!');
			return $this->redirect(Yii::$app->request->referrer);
		  } else {
             \Yii::$app->getSession()->setFlash('copmssgerror', 'Unable to add your Comment.');
			 return $this->redirect(Yii::$app->request->referrer); 
		  }
		} else {
		 return $this->render('view', [
                    'postQuery' => $postQuery,
					'relatedBlog' => $relatedBlog,
					'recentBlog' => $recentBlog,
					'popularBlog' => $popularBlog,
					'modelcomment' => $modelcomment,
					'count_all' => $count_all,
					'commentalls' => $comments_all,
             ]);
		}	
        } else {
			throw new NotFoundHttpException('The requested page does not exist.');
		 }		
	}	
}
