<?php
declare(strict_types=1);

namespace App\Controllers\Web;

use App\Middleware\AuthSession;
use App\Middleware\TenantScope;
use App\Models\Role;
use App\Models\User;
use Core\Controller;
use Core\Session;
use Core\Tool;

final class UsersController extends Controller
{
    public function middleware(): array
    {
        return [AuthSession::class, TenantScope::class];
    }

    private function tenantId(): int
    {
        return (int) ($_SESSION['tenant_id'] ?? 0);
    }

    private function guardAdmin(): void
    {
        $role = Session::user()['role_code'] ?? '';
        if (!in_array($role, [Role::ADMIN, Role::EXECUTIVE, Role::PROJECT_MANAGER], true)) {
            Session::flash('users_msg', 'You do not have permission to manage users.');
            redirect('/Home');
        }
    }

    public function index(): void
    {
        $this->guardAdmin();
        $this->render('users/index', [
            'users' => User::listForTenant($this->tenantId()),
            'flash' => Session::flash('users_msg'),
        ]);
    }

    public function create(): void
    {
        $this->guardAdmin();
        $this->render('users/form', [
            'target' => null,
            'roles'  => Role::listAll(),
            'csrf'   => Tool::generateCsrf(),
        ]);
    }

    public function edit(int $id): void
    {
        $this->guardAdmin();
        $target = User::findByIdInTenant($this->tenantId(), $id);
        if (!$target) { Session::flash('users_msg', 'User not found.'); redirect('/Users'); }
        $this->render('users/form', [
            'target' => $target,
            'roles'  => Role::listAll(),
            'csrf'   => Tool::generateCsrf(),
        ]);
    }

    public function save(): void
    {
        $this->guardAdmin();
        if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') redirect('/Users');
        if (!Tool::checkCsrf($_POST['_csrf'] ?? null)) {
            Session::flash('users_msg', 'Session expired.'); redirect('/Users');
        }
        $tenantId = $this->tenantId();
        $id       = (int) ($_POST['user_id'] ?? 0);

        if (trim((string) ($_POST['username'] ?? '')) === '') {
            Session::flash('users_msg', 'Username is required.');
            redirect($id > 0 ? "/Users/edit/{$id}" : '/Users/create');
        }
        if ($id === 0 && empty($_POST['password'])) {
            Session::flash('users_msg', 'Password is required for a new user.');
            redirect('/Users/create');
        }

        try {
            if ($id > 0) {
                User::update($tenantId, $id, $_POST);
                Session::flash('users_msg', 'User updated.');
            } else {
                $id = User::create($tenantId, $_POST);
                Session::flash('users_msg', 'User created.');
            }
        } catch (\PDOException $e) {
            Session::flash('users_msg', 'Save failed: ' . $e->getMessage());
            redirect($id > 0 ? "/Users/edit/{$id}" : '/Users/create');
        }
        redirect('/Users');
    }

    public function delete(int $id): void
    {
        $this->guardAdmin();
        $me = (int) (Session::user()['user_id'] ?? 0);
        if ($me === $id) {
            Session::flash('users_msg', "You can't delete yourself.");
            redirect('/Users');
        }
        User::softDelete($this->tenantId(), $id);
        Session::flash('users_msg', 'User deleted.');
        redirect('/Users');
    }
}
