<?php
namespace App\Controllers;
use App\Models\UserModel;
use App\Models\PostsModel;
use App\Views\View;
use App\Classes\FormValidator;
class AdminController
{
private UserModel $userModel;
private PostsModel $postModel;
private View $view;
private FormValidator $formValidator;
private array $fillable = ['email', 'password'];
public function __construct(UserModel $userModel, PostsModel $postModel, View $view, FormValidator $formValidator)
{
$this->userModel = $userModel;
$this->postModel = $postModel;
$this->view = $view;
$this->formValidator = $formValidator;
}
public function index()
{
if (isset($_SESSION['user_id']) && $_SESSION['user_role'] === '4') {
return $this->dashboard();
} else {
redirect('/admin/login');
}
}
public function login()
{
if (isset($_SESSION['user_id']) && $_SESSION['user_role'] === '4') {
redirect('/admin');
}
$errors = [];
$old = [];
$errors['flash'] = $_SESSION['errors']['flash'] ?? '';
foreach ($this->fillable as $field) {
$errors[$field] = $_SESSION['errors'][$field] ?? '';;
$old[$field] = $_POST[$field] ?? $_SESSION['old'][$field] ?? '';
}
$this->view->render('admin/login', [
'title' => "Вход в панель администратора",
'errors' => $errors,
'old' => $old
], 'admin');
}
public function loginStore()
{
$data = loadData($this->fillable);
$rules = [
'email' => [
'required' => true,
'min' => 5,
'max' => 20,
'email' => $data['email']
],
'password' => [
'required' => true,
'min' => 5,
'max' => 20
]
];
$validation = $this->formValidator->validate($data, $rules);
if ($validation->hasErrors()) {
$_SESSION['errors'] = [];
$_SESSION['old'] = [];
$errorFields = array_keys($validation->getErrors());
foreach ($this->fillable as $field) {
if (in_array($field, $errorFields)) {
$_SESSION['errors'][$field] = $validation->listErrors($field);
}
$_SESSION['old'][$field] = $_POST[$field];
}
redirect('/admin/login');
}
$result = $this->userModel->auth($data['email'], $data['password']);
if ($result) {
if ($result->role === '4') {
$_SESSION['user_id'] = $result->id;
$_SESSION['user_name'] = $result->name;
$_SESSION['user_role'] = $result->role;
$_SESSION['errors']['flash'] = 'Вы успешно вошли в админку';
redirect('/admin');
} else {
$_SESSION['errors']['flash'] = 'У вас нет прав доступа';
redirect('/admin/login');
}
} else {
$_SESSION['errors']['flash'] = 'Неверный email или пароль';
redirect('/admin/login');
}
}
public function logout()
{
unset($_SESSION['user_role']);
redirect('/admin/login');
}
private function dashboard()
{
$users = $this->userModel->findAll();
$posts = $this->postModel->findAll();
return $this->view->render('admin/index', [
'title' => "Добро пожаловать в админ-панель",
'users' => $users,
'posts' => $posts
], 'admin');
}
}