<?php

namespace app\controllers;

use Yii;
use app\models\HasilVoting;
use app\models\HasilVotingSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use app\models\MVoting;
use app\models\TKandidat;
use yii\helpers\ArrayHelper;
use yii\data\ActiveDataProvider;
use app\models\User;
use app\models\TUser;
use yii\web\Response;


/**
 * HasilVotingController implements the CRUD actions for HasilVoting model.
 */
class HasilVotingController extends Controller
{
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all HasilVoting models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new HasilVotingSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

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

    /**
     * Displays a single HasilVoting model.
     * @param integer $id_voting
     * @param integer $id_user
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id_voting, $id_user)
    {
        return $this->render('view', [
            'model' => $this->findModel($id_voting, $id_user),
        ]);
    }

    /**
     * Creates a new HasilVoting model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new HasilVoting();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id_voting' => $model->id_voting, 'id_user' => $model->id_user]);
        }

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

    /**
     * Updates an existing HasilVoting model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id_voting
     * @param integer $id_user
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id_voting, $id_user)
    {
        $model = $this->findModel($id_voting, $id_user);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id_voting' => $model->id_voting, 'id_user' => $model->id_user]);
        }

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

    /**
     * Deletes an existing HasilVoting model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id_voting
     * @param integer $id_user
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id_voting, $id_user)
    {
        $this->findModel($id_voting, $id_user)->delete();

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

    /**
     * Finds the HasilVoting model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id_voting
     * @param integer $id_user
     * @return HasilVoting the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id_voting, $id_user)
    {
        if (($model = HasilVoting::findOne(['id_voting' => $id_voting, 'id_user' => $id_user])) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }

    public function actionOnlineVoting(){

        

        $user = Yii::$app->user->identity;
        $voting = MVoting::find()->where(['status_aktif'=>1])->one();
        $hasil_voting = HasilVoting::find()->where(['id_voting' => $voting->id_voting])->andWhere(['id_user' =>$user->id])->one();
        $arrayPilihan = ArrayHelper::map(TKandidat::find()->where(['id_voting'=>$voting->id_voting])->orderBy(['id_kandidat' => SORT_ASC])->all(),'id_kandidat','nama_kandidat');

        $model = new HasilVoting();

        if ($model->load(Yii::$app->request->post())) {
            $model->id_voting = $voting->id_voting;
            $model->id_user = $user->id;
            $model->status_voting = 1;
            $model->save();
            if($model->save()){
                $email = \Yii::$app->mailer->compose()
                ->setTo($user->email)
                ->setFrom(['gtconlinesystem@gmail.com' => 'Online Voting System'])
                ->setSubject('Informasi Pemberitahuan Voting')
                ->setHtmlBody('
                    <b>Terima Kasih Buat Partisipasi Anda Telah Melakukan Voting</b>
                    <br><br>
                    <b>Hasil Voting Akan Ditunjukkan Jika Periode Voting Telah Berakhir</b>')
                ->send();

                if($email){
                    Yii::$app->session->setFlash('success', "Voting Berhasil Dilakukan, Informasi bahwa anda telah berhasil melakukan Voting dikirim ke Email Anda");
                }
                else{
                    Yii::$app->session->setFlash('success', "Terima Kasih, Voting Berhasil Dilakukan");
                }

                
            }else{
                Yii::$app->getSession()->setFlash('danger','Maaf, Pilihan Anda Belum Berhasil Disimpan pada Online Voting');
            }

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

        return $this->render('online_voting', [
            'model' => $model,
            'arrayPilihan' => $arrayPilihan,
            'hasil_voting' => $hasil_voting,
            'voting' => $voting,
        ]);
    }

    public function actionHasilVoting($id_voting){

        $query_hasil_voting = HasilVoting::find()->select(['id_voting','id_user','pilihan','COUNT(pilihan) AS Jumlah_Voting '])->where(['id_voting'=>$id_voting])->groupBy(['pilihan']);
        $hasil_voting = $query_hasil_voting->asArray()->all();

        $dataGrafik=[];
        
        foreach ($hasil_voting as $key => $value) {
            $kandidat =  TKandidat::find()->where(['id_kandidat' => $value['pilihan']])->one();
            $dataGrafik[] = [
                'name' => $kandidat->nama_kandidat,
                'y' => floatval($value['Jumlah_Voting']),
            ];
        }

       
        $voting = MVoting::find()->where(['id_voting'=>$id_voting])->one();

        $dataProvider = new ActiveDataProvider([
            'query' => $query_hasil_voting,
            'pagination' => [
                'pageSize' => 30,
            ],
            'sort' => [
                'defaultOrder' => [
                    'pilihan' => SORT_ASC,
                    
                ]
            ],
        ]);

        $arrayVoting = ArrayHelper::map(MVoting::find()->all(),'id_voting','nama_voting');

        return $this->render('hasil_voting', [
            'hasil_voting' => $hasil_voting,
            'voting' => $voting,
            'dataProvider' => $dataProvider,
            'dataGrafik' => $dataGrafik,
            'arrayVoting' => $arrayVoting,
            
            
        ]);

    }

    public function actionFilterHasilVoting($id_voting){

        $query_hasil_voting = HasilVoting::find()->select(['id_voting','id_user','pilihan','COUNT(pilihan) AS Jumlah_Voting '])->where(['id_voting'=>$id_voting])->groupBy(['pilihan']);
        $hasil_voting = $query_hasil_voting->asArray()->all();

        $dataGrafik=[];
        
        foreach ($hasil_voting as $key => $value) {
            $kandidat =  TKandidat::find()->where(['id_kandidat' => $value['pilihan']])->one();
            $dataGrafik[] = [
                'name' => $kandidat->nama_kandidat,
                'y' => floatval($value['Jumlah_Voting']),
            ];
        }

       
        $voting = MVoting::find()->where(['id_voting'=>$id_voting])->one();
        $arrayVoting = ArrayHelper::map(MVoting::find()->all(),'id_voting','nama_voting');

        return $this->renderAjax('_renderHasilVoting', [
            'hasil_voting' => $hasil_voting,
            'voting' => $voting,
            'dataGrafik' => $dataGrafik,
            'arrayVoting' => $arrayVoting,
            
            
        ]);

    }

    public function actionResultVoting($id_voting){

        $query_hasil_voting = HasilVoting::find()->select(['id_voting','id_user','pilihan','COUNT(pilihan) AS Jumlah_Voting '])->where(['id_voting'=>$id_voting])->groupBy(['pilihan']);
        $hasil_voting = $query_hasil_voting->asArray()->all();

        $dataGrafik=[];
        
        foreach ($hasil_voting as $key => $value) {
            $kandidat =  TKandidat::find()->where(['id_kandidat' => $value['pilihan']])->one();
            $dataGrafik[] = [
                'name' => $kandidat->nama_kandidat,
                'y' => floatval($value['Jumlah_Voting']),
            ];
        }

        Yii::$app->response->format = Response::FORMAT_JSON;
        return $dataGrafik;
    }

    public function actionRekapitulasiPenggunaVoting($id_voting){

        $query_pengguna_voting = HasilVoting::find()->where(['id_voting'=>$id_voting]);
        //$hasil_voting = $query->asArray()->all();
       
        $voting = MVoting::find()->where(['id_voting'=>$id_voting])->one();

        /*$dataProvider = new ActiveDataProvider([
            'query' => $query_pengguna_voting,
            'pagination' => [
                'pageSize' => 20,
            ],
            'sort' => [
                'defaultOrder' => [
                    'id_user' => SORT_ASC,
                    
                ]
            ],
        ]);*/


        $dataSudahVoting = HasilVoting::find()->where(['id_voting'=>$id_voting])->asArray()->all();
        $arraySudahVoting = ArrayHelper::getColumn($dataSudahVoting,'id_user');

        $query_pengguna_belum_voting = TUser::find()->join('JOIN','auth_assignment','t_user.id = auth_assignment.user_id')->where(['auth_assignment.item_name'=>'PESERTA_VOTING'])->andWhere(['NOT IN','t_user.id',$arraySudahVoting]);
        //print_r($arraySudahVoting);die;
        //print_r($query_pengguna_voting->asArray()->all());die;

        $count_total_pengguna = TUser::find()->join('JOIN','auth_assignment','t_user.id = auth_assignment.user_id')->where(['auth_assignment.item_name'=>'PESERTA_VOTING'])->count();
        $count_sudah_voting = HasilVoting::find()->where(['id_voting'=>$id_voting])->count();
        $count_belum_voting = $count_total_pengguna - $count_sudah_voting;

        $searchModel = new HasilVotingSearch();
        $dataProvider = $searchModel->searchData($query_pengguna_voting,Yii::$app->request->queryParams);

        $searchModel2 = new HasilVotingSearch();
        $dataProvider2 = $searchModel2->searchData($query_pengguna_belum_voting,Yii::$app->request->queryParams);


        return $this->render('rekapitulasi_pengguna_voting', [
            //'hasil_voting' => $hasil_voting,
            'voting' => $voting,
            'dataProvider' => $dataProvider,
            'dataProvider2' => $dataProvider2,
            'count_total_pengguna' => $count_total_pengguna,
            'count_sudah_voting' => $count_sudah_voting,
            'count_belum_voting' => $count_belum_voting,
            
        ]);

    }
}
