<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Auth;
use App\Csrf;
use App\Repositories\Container;

class AdminStaffController
{
    public function index(): void
    {
        $staff   = array_values(array_filter(Container::users()->all(), fn($u) => in_array($u['role'] ?? '', ['STAFF', 'ADMIN', 'ARTIST'], true)));
        $artists = Container::artists()->all(false);
        render('admin', 'admin.staff', compact('staff', 'artists'), t('admin.staff.title'));
    }

    public function create(): void
    {
        Csrf::requireValid();
        $username = trim((string)($_POST['username'] ?? ''));
        $email    = trim((string)($_POST['email'] ?? ''));
        $first    = trim((string)($_POST['first_name'] ?? ''));
        $last     = trim((string)($_POST['last_name'] ?? ''));
        $password = (string)($_POST['password'] ?? '');
        $role     = in_array($_POST['role'] ?? 'STAFF', ['STAFF','ADMIN','ARTIST'], true) ? $_POST['role'] : 'STAFF';
        $artistProfileId = trim((string)($_POST['artist_profile_id'] ?? '')) ?: null;

        if (!$username || !$first || strlen($password) < 8) {
            $_SESSION['_flash']['error'] = t('admin.staff.invalid');
            redirect('/admin/staff');
        }
        if (Container::users()->findByUsername($username)) {
            $_SESSION['_flash']['error'] = t('admin.staff.duplicate_username');
            redirect('/admin/staff');
        }
        $user = Container::users()->save([
            'username'              => strtolower($username),
            'email'                 => $email ?: null,
            'first_name'            => $first,
            'last_name'             => $last,
            'role'                  => $role,
            'password_hash'         => password_hash($password, PASSWORD_DEFAULT),
            'pin_hash'              => null,
            'is_active'             => true,
            'artist_profile_id'     => $artistProfileId,
            'must_change_password'  => true,
        ]);
        Container::audit()->log(Auth::user()['id'] ?? '', 'CREATE_STAFF', 'user', $user['id']);
        $_SESSION['_flash']['success'] = t('admin.staff.created');
        redirect('/admin/staff');
    }

    public function resetPin(array $params): void
    {
        Csrf::requireValid();
        $user = Container::users()->find($params['id'] ?? '');
        if (!$user) redirect('/admin/staff');
        Container::users()->save(array_merge($user, ['pin_hash' => null, 'pin_set_at' => null]));
        Container::audit()->log(Auth::user()['id'] ?? '', 'RESET_PIN', 'user', $user['id']);
        $_SESSION['_flash']['success'] = t('admin.staff.pin_reset');
        redirect('/admin/staff');
    }

    /**
     * Admin resets a staff member's password without knowing the old one.
     */
    public function resetPassword(array $params): void
    {
        Csrf::requireValid();
        $user = Container::users()->find($params['id'] ?? '');
        if (!$user) redirect('/admin/staff');
        $newPassword = (string)($_POST['new_password'] ?? '');
        if (strlen($newPassword) < 8) {
            $_SESSION['_flash']['error'] = t('admin.staff.password_too_short');
            redirect('/admin/staff');
        }
        Container::users()->save(array_merge($user, [
            'password_hash'        => password_hash($newPassword, PASSWORD_DEFAULT),
            'must_change_password' => true,
        ]));
        Container::audit()->log(Auth::user()['id'] ?? '', 'RESET_PASSWORD', 'user', $user['id']);
        $_SESSION['_flash']['success'] = t('admin.staff.password_reset');
        redirect('/admin/staff');
    }

    public function disable(array $params): void
    {
        Csrf::requireValid();
        $user = Container::users()->find($params['id'] ?? '');
        if (!$user) redirect('/admin/staff');
        Container::users()->save(array_merge($user, ['is_active' => false]));
        Container::audit()->log(Auth::user()['id'] ?? '', 'DISABLE_STAFF', 'user', $user['id']);
        redirect('/admin/staff');
    }

    public function enable(array $params): void
    {
        Csrf::requireValid();
        $user = Container::users()->find($params['id'] ?? '');
        if (!$user) redirect('/admin/staff');
        Container::users()->save(array_merge($user, ['is_active' => true]));
        Container::audit()->log(Auth::user()['id'] ?? '', 'ENABLE_STAFF', 'user', $user['id']);
        redirect('/admin/staff');
    }
}
