<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Services\AuthService;

class AdminUserController extends Controller
{
    private AuthService $auth;

    public function __construct()
    {
        $this->auth = new AuthService();
    }

    public function index(Request $request): string
    {
        require_role('admin');

        $filters = [
            'role' => (string) $request->input('role', ''),
            'status' => (string) $request->input('status', ''),
            'search' => (string) $request->input('search', ''),
        ];

        return $this->view('admin/users/index', [
            'title' => 'Gestao de utilizadores',
            'users' => $this->auth->users($filters),
            'stats' => $this->auth->stats(),
            'filters' => $filters,
        ]);
    }

    public function show(Request $request): string
    {
        require_role('admin');

        $user = $this->auth->findById((int) $request->input('id'));

        if (!$user) {
            flash('error', 'Utilizador nao encontrado.');
            app()->response()->redirect('/admin/users');
        }

        unset($user['password'], $user['password_reset_token']);

        return $this->view('admin/users/show', [
            'title' => 'Perfil do utilizador',
            'managedUser' => $user,
        ]);
    }

    public function approve(Request $request): void
    {
        $this->changeStatus($request, 'active', 'Conta aprovada.');
    }

    public function reject(Request $request): void
    {
        $this->changeStatus($request, 'rejected', 'Conta rejeitada.');
    }

    public function suspend(Request $request): void
    {
        $this->changeStatus($request, 'suspended', 'Conta suspensa.');
    }

    public function activate(Request $request): void
    {
        $this->changeStatus($request, 'active', 'Conta activada.');
    }

    private function changeStatus(Request $request, string $status, string $message): void
    {
        require_role('admin');

        if (!verify_csrf((string) $request->post('_csrf_token', ''))) {
            flash('error', 'Sessao expirada. Tente novamente.');
            app()->response()->back();
        }

        $result = $this->auth->changeStatus(
            (int) $request->post('user_id'),
            $status,
            (int) current_user()['id']
        );

        if (!$result['ok']) {
            flash('error', $result['error']);
            app()->response()->back();
        }

        flash('success', $message);
        app()->response()->back();
    }
}
