<?php

namespace app\controllers;

use Yii;
use app\models\Messages;
use yii\data\SqlDataProvider;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\Controller;

class MessagesController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    //'delete' => ['post'],
                ],
            ],
        ];
    }

    public function init(){
        if(Yii::$app->user->isGuest)
        {
            return $this->redirect('/user/login');
        }
        if(@!Yii::$app->user->identity->confirmed_at && (@Yii::$app->user->identity->role == 1)){
            return $this->redirect('/registration/organizer');
        }
        $this->layout = '@app/views/layouts/backend/user';
        parent::init();
    }

    public function actionIndex()
    {
        //$dataProvider = new ActiveDataProvider([
        //    'query' => Messages::find()->where(['user_id' => Yii::$app->user->identity->id]),
        //]);
        // Obnylator Messages
        Yii::$app->db->createCommand("UPDATE messages SET status=1 WHERE user_id=:user_id")->bindValue(":user_id",Yii::$app->user->identity->id)->execute();

        // Pagination
        $totalCount = Yii::$app->db->createCommand('SELECT COUNT(*) FROM messages WHERE user_id=:user_id', [':user_id' => Yii::$app->user->identity->id])->queryScalar();
        $query = 'SELECT * FROM messages  WHERE user_id=:user_id ORDER by DATE DESC';

        $dataProvider = new SqlDataProvider([
            'sql' => $query,
            'params' => [':user_id' => Yii::$app->user->identity->id],
            'totalCount' => (int)$totalCount,
            'pagination' => [
                'pageSize' => 30,
            ]
        ]);
        //$userRole = Yii::$app->authManager->getRole('org');
        //Yii::$app->authManager->assign($userRole, Yii::$app->user->identity->id);

        return $this->render('index', [
            'dataProvider' => $dataProvider,
        ]);
    }

    public function actionView($id)
    {
        $model = $this->findModel($id);

        return $this->render('view', [
            'model' => $model,
        ]);
    }

    public function actionDelete($id)
    {
            if(Yii::$app->user->can('member'))
            {
                return $this->redirect(['index']);
            }
            else
            {
                $this->findModel($id)->delete();

                return $this->redirect(['index']);
            }
    }

    protected function findModel($id)
    {
        if (($model = Messages::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

}
