<?php

declare(strict_types=1);

namespace App\Repositories;

use App\Core\Database;

final class UserRepository
{
    /** @var string */
    private $hospitalCode;

    public function __construct(string $hospitalCode = 'njch')
    {
        $this->hospitalCode = $hospitalCode;
    }

    /**
     * انتقال آمن تدريجي: نستخدم نفس جدول المستخدمين الحالي مع bind parameters.
     * المرحلة التالية: نقل كلمات المرور إلى password_hash في جدول مستقل.
     *
     * @return array<string, mixed>|null
     */
    public function findDashboardUserByLegacyPassword(string $username, string $password): ?array
    {
        $sql = "
            SELECT
                name,
                NVL(dashboard_role, 0) AS dashboard_role,
                NVL(dashboard_role_fin, 0) AS dashboard_role_fin,
                NVL(dashboard_role_revenue, NVL(dashboard_role, 0)) AS dashboard_role_revenue
            FROM SECURITY_USERS
            WHERE UPPER(name) = UPPER(:username)
              AND decrypt_password(user_password) = :password
              AND NVL(dashboard_role, 0) = 1
              AND ROWNUM <= 1
        ";

        return Database::fetchOne($this->hospitalCode, $sql, [
            'username' => $username,
            'password' => $password,
        ]);
    }
}
