<?php

namespace backend\controllers;

use Yii;
use common\models\User;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * UserController implements the CRUD actions for User model.
 */
class UserController extends Controller {

    /**
     * @inheritdoc
     */
    public function behaviors() {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all User models.
     * @return mixed
     */
    public function actionIndex() {
        $dataProvider = new ActiveDataProvider([
            'query' => User::find(),
        ]);

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

    /**
     * Displays a single User model.
     * @param string $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 \backend\models\SignupForm();
        if ($model->load(Yii::$app->request->post())) {
            if ($user = $model->signup()) {
                return $this->redirect(['index']);
            } else {
                return $this->render('create', [
                            'model' => $model,
                ]);
            }
        }
//        $model = new User();
//        $requested = Yii::$app->request->post();
//        if ($model->load($requested)) {
////            $model->setPassword($requested['User']['password']);
////            $model->generateAuthKey();
////            $model->nombre = $requested['User']['nombre'];
////            $model->apellidos = $requested['User']['apellidos'];
////            $model->cuota = $requested['User']['cuota'];
////            $model->email = $requested['User']['email'];
////            $model->agente = $model->username = $requested['User']['username'];
////            $model->pdv_id = $requested['User']['pdv_id'];
////            $model->rolSeleccionado = $requested['User']['rolSeleccionado'];
//            //echo var_dump($model);
//            if ($model->save()) {
//                $auth = \Yii::$app->authManager;
//                $authorRole = $auth->getRole($model->rolSeleccionado);
//                $auth->assign($authorRole, $model->id);
//                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 string $id
     * @return mixed
     */
    public function actionUpdate($id) {
        $model = $this->findModel($id);
        $requested = Yii::$app->request->post();
        if ($model->load($requested)) {
            $model->generateAuthKey();
            $model->nombre = $requested['User']['nombre'];
            $model->apellidos = $requested['User']['apellidos'];
            $model->cuota = $requested['User']['cuota'];
            $model->email = $requested['User']['email'];
            $model->agente = $model->username = $requested['User']['username'];
            $model->pdv_id = $requested['User']['pdv_id'];
            if ($model->isNewRecord) {
                $model->rolSeleccionado = $requested['User']['rolSeleccionado'];
                $model->setPassword($requested['User']['password']);
            } else {
                if ($requested['User']['password'] != '') {
                    $model->setPassword($requested['User']['password']);
                }
            }
            //echo var_dump($model);
            if ($model->save()) {
                if ($model->isNewRecord) {
                    $auth = \Yii::$app->authManager;
                    $authorRole = $auth->getRole($model->rolSeleccionado);
                    $auth->assign($authorRole, $model->id);
                    \Yii::$app->getSession()->setFlash('Usuario nuevo registrado correctamente.');
                } else {
                    if ($requested['User']['password'] != '') {
                        \Yii::$app->getSession()->setFlash('Usuario ID: ' . $model->id . ' Username: ' . $model->username . ' modificado correctamente.', ' Con modificacion en Password');
                    } else {
                        \Yii::$app->getSession()->setFlash('Usuario ID: ' . $model->id . ' Username: ' . $model->username . '  modificado correctamente.', ' Sin modificacion en Password');
                    }
                }
                return $this->redirect(['index']);
            } else {
                return $this->render('update', [
                            'model' => $model,
                ]);
            }
        } else {
            return $this->render('update', [
                        'model' => $model,
            ]);
        }
    }

    /**
     * Assign items
     * @param string $id
     * @return array
     */
    public function actionAssign($id) {
        $items = Yii::$app->getRequest()->post('items', []);
        $model = new \mdm\admin\models\Assignment($id);
        $success = $model->assign($items);
        Yii::$app->getResponse()->format = 'json';
        return array_merge($model->getItems(), ['success' => $success]);
    }

    /**
     * Assign items
     * @param string $id
     * @return array
     */
    public function actionRevoke($id) {
        $items = Yii::$app->getRequest()->post('items', []);
        $model = new \mdm\admin\models\Assignment($id);
        $success = $model->revoke($items);
        Yii::$app->getResponse()->format = 'json';
        return array_merge($model->getItems(), ['success' => $success]);
    }

    /**
     * Deletes an existing User model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id) {
        $model = $this->findModel($id);
        $model->status = 0;
        $model->save();
        return $this->redirect(['index']);
    }

    public function actionReactivar($id) {
        $model = $this->findModel($id);
        $model->status = 10;
        $model->save();
        return $this->redirect(['index']);
    }

    /**
     * Finds the User model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $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.');
        }
    }

}
