<?php

namespace app\controllers;

use Yii;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use app\models\User;
use app\models\MasUserGroup;

class UsersController extends Controller
{
    public $layout = 'main';

    public function behaviors(): array
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                        'matchCallback' => function () {
                            return !Yii::$app->user->isGuest
                                && Yii::$app->user->identity->isAdmin();
                        },
                    ],
                ],
            ],
            'verbs' => [
                'class'   => VerbFilter::class,
                'actions' => ['delete' => ['post']],
            ],
        ];
    }

    public function actionIndex(): string
    {
        $users = User::find()->orderBy(['id' => SORT_ASC])->all();
        return $this->render('index', ['users' => $users]);
    }

    public function actionCreate()
    {
        $model = new User();
        $groups = MasUserGroup::find()->where(['is_active' => 'Y'])->all();

        if ($model->load(Yii::$app->request->post())) {
            $model->password = User::hashPassword(Yii::$app->request->post('User')['password_raw'] ?? '');
            $model->created_at = date('Y-m-d H:i:s');
            $model->updated_at = date('Y-m-d H:i:s');
            if ($model->save()) {
                Yii::$app->session->setFlash('success', 'User created successfully.');
                return $this->redirect(['users/index']);
            }
        }

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

    public function actionUpdate(int $id)
    {
        $model  = $this->findModel($id);
        $groups = MasUserGroup::find()->where(['is_active' => 'Y'])->all();

        if ($model->load(Yii::$app->request->post())) {
            $rawPwd = Yii::$app->request->post('User')['password_raw'] ?? '';
            if (!empty($rawPwd)) {
                $model->password = User::hashPassword($rawPwd);
            }
            $model->updated_at = date('Y-m-d H:i:s');
            if ($model->save(false)) {
                Yii::$app->session->setFlash('success', 'User updated successfully.');
                return $this->redirect(['users/index']);
            }
        }

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

    public function actionDelete(int $id)
    {
        $this->findModel($id)->delete();
        Yii::$app->session->setFlash('success', 'User deleted.');
        return $this->redirect(['users/index']);
    }

    protected function findModel(int $id): User
    {
        $model = User::findOne($id);
        if ($model === null) {
            throw new NotFoundHttpException('User not found.');
        }
        return $model;
    }
}
