<?php

namespace backend\controllers;

use Yii;
use common\models\User;
use backend\models\MailForm;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\helpers\Upload ;
use common\helpers\Password ;
use common\models\UserEtablissement ;
use common\models\Etablissement ;
use yii\base\UserException ;
use common\models\CreditHistorique; 
use common\models\Commande; 

/**
 * UserController implements the CRUD actions for User model.
 */
class UserController extends BackendController
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
            'access' => [
	            'class' => AccessControl::className(),
	            'rules' => [
		            [
		            	'allow' => true,
		            	'roles' => ['@'],
		            	'matchCallback' => function ($rule, $action) {
                                        if($action->actionMethod == 'actionIndex' ||
                                           $action->actionMethod == 'actionCreate' ||
                                           $action->actionMethod == 'actionUpdate' ||
                                           $action->actionMethod == 'actionCredit' ||
                                           $action->actionMethod == 'actionMail' ||
                                           $action->actionMethod == 'actionCommandes')
                                        {
                                            return Yii::$app->user->identity->status == USER::STATUS_ADMIN 
                                                || Yii::$app->user->identity->status == USER::STATUS_BOULANGER ;
                                        }
                                        else {
                                            return Yii::$app->user->identity->status == USER::STATUS_ADMIN ;
                                        }
		            	}
	            	]
	            ],
            ],
        ];
    }

    /**
     * Lists all User models.
     * @return mixed
     */
    public function actionIndex()
    {
        $params = Yii::$app->request->queryParams;
        
        $query = User::findBy($params) ;
            
        $dataProvider = new ActiveDataProvider([
            'query' => $query
        ]);
        
        $etablissement = Etablissement::find()
                ->where(['id' => Yii::$app->user->identity->id_etablissement])
                ->one() ;
        
        return $this->render('index', [
            'dataProvider' => $dataProvider,
            'etablissement' => $etablissement
        ]);
    }

    /**
     * Displays a single User model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

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

        if ($model->load(Yii::$app->request->post()) && $model->validate() && YII_ENV != 'demo') {
            
            // save use
            $password = Password::generate() ;
            $model->setPassword($password);
            $model->generateAuthKey();
            $model->username = $model->email ;
            $model->confiance = 1 ;
            if(!strlen($model->email))
                $model->username = 'inconnu@laboiteapain.net' ;
            
            $model->save() ;
            
            // liaison etablissement / user
            $user_etablissement = new UserEtablissement() ;
            $user_etablissement->id_user = $model->id ;
            $user_etablissement->id_etablissement = Yii::$app->user->identity->id_etablissement ;
            $user_etablissement->credit = 0 ;
            $user_etablissement->actif = 1 ;
            $user_etablissement->save() ;
            
            // send mail
            if(strlen($model->email))
            {
                $etablissement = Etablissement::findOne(Yii::$app->user->identity->id_etablissement) ;
                Yii::$app->mailer->compose() ;
                $mail = Yii::$app->mailer->compose(
                        ['html' => 'createUserAdmin-html', 'text' => 'createUserAdmin-text'],
                        ['user' => $model, 'etablissement' => $etablissement, 'password' => $password])
                    ->setTo($model->email)
                    ->setFrom(['contact@laboiteapain.net' => 'La boîte à pain'])
                    ->setSubject('[La boîte à pain] Inscription')
                    ->send() ;
            }

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

    /**
     * Updates an existing User model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        $user = User::find()->with('userEtablissement')->where(['id' => $model['id']])->one() ;
        $user_appartient_etablissement = UserEtablissement::findOne(['id_user' =>$id, 'id_etablissement' => Yii::$app->user->identity->id_etablissement]) ;
        if(($user_appartient_etablissement && count($user->userEtablissement) == 1) || Yii::$app->user->identity->status == USER::STATUS_ADMIN)
        {
            if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['index']);
            } else {
                return $this->render('update', [
                    'model' => $model,
                ]);
            }
        }
        else {
            throw new UserException("Vous ne pouvez pas modifier cet utilisateur, soit parce qu'il appartient à plusieurs boulangeries, soit parce qu'il n'est pas lié à la votre.");
        }
    }

    public function actionMail() {
        
        $users = (new \yii\db\Query())
                ->select('*')
                ->from('user, user_etablissement')
                ->where('user.id = user_etablissement.id_user')
                ->andWhere('user_etablissement.actif = 1')
                ->andWhere('user_etablissement.id_etablissement = '.Yii::$app->user->identity->id_etablissement)
                ->all() ;
        
        $arr_users = [] ;
        foreach($users as $u) {
            if(isset($u['email']))
                $arr_users[] = $u['email'] ;
        }
        
        return $this->render('liste_mails', [
                //'model' => $model,
                'users' => $arr_users
            ]);
        
    }
    
    public function actionCredit($id) 
    {
        $user = User::find()->with('userEtablissement')->where(['id' => $id])->one() ;
        $user_appartient_etablissement = UserEtablissement::findOne(['id_user' =>$id, 'id_etablissement' => Yii::$app->user->identity->id_etablissement]) ;
        if(($user_appartient_etablissement) || Yii::$app->user->identity->status == USER::STATUS_ADMIN)
        {
            $credit_historique = new CreditHistorique; 
            if ($credit_historique->load(Yii::$app->request->post()) && $credit_historique->validate()) 
            {
                $credit_historique->id_user = $user->id ;
                $credit_historique->id_etablissement = Yii::$app->user->identity->id_etablissement ;
                if($credit_historique->type == CreditHistorique::TYPE_DEBIT && $credit_historique->montant > 0)
                    $credit_historique->montant = - $credit_historique->montant ;
                
                $credit_historique->save() ;
                
                $this->redirect(['user/index']) ;
            }
            
            $historique = CreditHistorique::find()
                ->with('commande')
                ->where([
                    'id_user' => $user->id,
                    'id_etablissement' => Yii::$app->user->identity->id_etablissement,
                ])
                ->orderBy('date DESC')
                ->all() ;
            
            return $this->render('credit', [
                'user' => $user,
                'credit_historique' => $credit_historique,
                'historique' => $historique
            ]) ;
        }
        else {
            throw new UserException("Vous ne pouvez pas créditer un utilisateur qui n'est pas associé à votre boulangerie.");
        }
    }
    
    public function actionCommandes($id)
    {
        
        $user = User::findOne($id) ;
        
        $commandes = Commande::find()
                ->with('commandeProduits', 'pointVente', 'creditHistorique')
                ->joinWith('production','production.etablissement')
                ->where([
                    'id_user' => $id,
                    'production.id_etablissement' => Yii::$app->user->identity->id_etablissement 
                 ])
                ->orderBy('production.date DESC')
                ->all();
        
        foreach ($commandes as $c)
            $c->init();
        
        return $this->render('commandes', [
            'commandes' => $commandes,
            'user' => $user
        ]) ;
    }
    
    /**
     * Finds the User model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return User the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = User::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    
    
}