<?php

namespace App\Core\Users\Controllers;

use App\Controllers\BaseController;
use App\Core\Audit\Services\AuditService;
use App\Core\Auth\Models\RoleModel;
use App\Core\Auth\Models\UserModel;
use App\Core\License\Services\LicenseService;
use Config\Database;

class UserController extends BaseController
{
    public function index()
    {
        $users = (new UserModel())->orderBy('created_at', 'DESC')->findAll();
        $rolesByUser = [];

        if ($users !== []) {
            $rows = Database::connect()->table('core_user_roles ur')
                ->select('ur.user_id, r.label, r.name')
                ->join('core_roles r', 'r.id = ur.role_id')
                ->whereIn('ur.user_id', array_column($users, 'id'))
                ->orderBy('r.label', 'ASC')
                ->get()
                ->getResultArray();

            foreach ($rows as $row) {
                $rolesByUser[(int) $row['user_id']][] = $row;
            }
        }

        return view('core/users/index', [
            'title' => 'Utilisateurs',
            'users' => $users,
            'roles' => (new RoleModel())->orderBy('label')->findAll(),
            'rolesByUser' => $rolesByUser,
        ]);
    }

    public function store()
    {
        if (! (new LicenseService())->canCreateUser()) {
            return redirect()->back()->with('error', 'Limite utilisateurs atteinte pour le plan actuel.');
        }

        $rules = [
            'email' => 'required|valid_email|is_unique[core_users.email]',
            'password' => 'required|min_length[8]',
            'firstname' => 'permit_empty|max_length[120]',
            'lastname' => 'permit_empty|max_length[120]',
            'role_id' => 'required|is_not_unique[core_roles.id]',
        ];

        if (! $this->validate($rules)) {
            return redirect()->back()->withInput()->with('error', 'Impossible de créer cet utilisateur.');
        }

        $userId = (new UserModel())->insert([
            'email' => strtolower((string) $this->request->getPost('email')),
            'password_hash' => password_hash((string) $this->request->getPost('password'), PASSWORD_DEFAULT),
            'firstname' => (string) $this->request->getPost('firstname'),
            'lastname' => (string) $this->request->getPost('lastname'),
            'status' => 'active',
        ], true);

        Database::connect()->table('core_user_roles')->ignore(true)->insert([
            'user_id' => $userId,
            'role_id' => (int) $this->request->getPost('role_id'),
        ]);

        (new AuditService())->log('user.create', 'user', (string) $userId, 'Création utilisateur');

        return redirect()->back()->with('success', 'Utilisateur créé.');
    }
}
