<?php
namespace PortalPeopleStatis\modules\SatisfyManager\controllers;

// No Yii2 Controller inheritance
use PortalPeopleStatis\modules\SatisfyManager\forms\UserForm;
use Yiisoft\Validator\Validator;

use Yiisoft\Yii\View\Renderer\ViewRenderer;

class UserController
{
    public $validator;
    private $viewRenderer;

    function __construct(ViewRenderer $viewRenderer)
    {
        $this->validator = new Validator();
        $this->viewRenderer = $viewRenderer;
    }

    function actionIndex()
    {
        $userRepository = new \PortalPeopleStatis\modules\SatisfyManager\repositories\UserRepository(
            new \Yiisoft\Db\Connection(/* DB config here */)
        );
        $users = $userRepository->findAll();
        return $this->viewRenderer->render('user/index', ['users' => $users]);
    }

    function actionCreate()
    {
        $form = new UserForm();
        $message = '';
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $form->setEmail($_POST['email'] ?? '');
            $result = $this->validator->validate($form);
            if ($result->isValid()) {
                $userRepository = new \PortalPeopleStatis\modules\SatisfyManager\repositories\UserRepository(
                    new \Yiisoft\Db\Connection(/* DB config here */)
                );
                $user = new \PortalPeopleStatis\modules\SatisfyManager\models\User([
                    'email' => $form->getEmail(),
                ]);
                $userRepository->save($user);
                $message = 'User created!';
            } else {
                $message = implode(' ', $result->getErrorMessages());
            }
        }
        return $this->viewRenderer->render('user/create', ['form' => $form, 'message' => $message]);
    }

    function actionUpdate($id)
    {
        // TODO: Update user
        return $this->viewRenderer->render('user/update', ['id' => $id]);
    }
}
