<?php

namespace App\Models;

use App\Core\Model;

class User extends Model
{
    protected static string $table = 'iw_users';

    /**
     * All users for admin listing, ordered by role then username.
     * Excludes password_hash from the result set.
     */
    public static function allForAdmin(): array
    {
        return static::db()->fetchAll(
            "SELECT id, username, email, role, is_active, created_at, updated_at
             FROM iw_users
             ORDER BY role ASC, username ASC"
        );
    }

    /**
     * Count active admin users.
     * Used for safety checks (prevent deleting or demoting the last admin).
     */
    public static function countAdmins(): int
    {
        return (int) static::db()->fetchColumn(
            "SELECT COUNT(*) FROM iw_users WHERE role = 'admin' AND is_active = 1"
        );
    }

    // ─────────────────────────────────────────────────────────────────────
    // TOTP 2FA helpers
    // ─────────────────────────────────────────────────────────────────────

    /**
     * Check if a user has TOTP 2FA enabled.
     */
    public static function hasTotpEnabled(int $userId): bool
    {
        return (bool) static::db()->fetchColumn(
            "SELECT totp_enabled FROM iw_users WHERE id = :id LIMIT 1",
            ['id' => $userId]
        );
    }

    /**
     * Get the TOTP secret for a user.
     */
    public static function getTotpSecret(int $userId): ?string
    {
        $val = static::db()->fetchColumn(
            "SELECT totp_secret FROM iw_users WHERE id = :id LIMIT 1",
            ['id' => $userId]
        );
        return $val ?: null;
    }

    /**
     * Get stored recovery codes for a user.
     *
     * @return string[]
     */
    public static function getRecoveryCodes(int $userId): array
    {
        $json = static::db()->fetchColumn(
            "SELECT totp_recovery_codes FROM iw_users WHERE id = :id LIMIT 1",
            ['id' => $userId]
        );
        if (!$json) {
            return [];
        }
        return json_decode($json, true) ?: [];
    }

    /**
     * Enable TOTP 2FA for a user.
     */
    public static function enableTotp(int $userId, string $secret, array $recoveryCodes): void
    {
        static::updateById($userId, [
            'totp_secret'         => $secret,
            'totp_enabled'        => 1,
            'totp_recovery_codes' => json_encode($recoveryCodes),
        ]);
    }

    /**
     * Disable TOTP 2FA for a user.
     */
    public static function disableTotp(int $userId): void
    {
        static::updateById($userId, [
            'totp_secret'         => null,
            'totp_enabled'        => 0,
            'totp_recovery_codes' => null,
        ]);
    }

    /**
     * Update recovery codes (e.g. after using one).
     */
    public static function updateRecoveryCodes(int $userId, array $codes): void
    {
        static::updateById($userId, [
            'totp_recovery_codes' => json_encode($codes),
        ]);
    }
}
