<?php

require_once __DIR__ . '/CryptoHelper.php';

class PasswordHelper
{
    public static function verify($plainText, $storedHash)
    {
        $storedHash = (string) $storedHash;

        if (password_get_info($storedHash)['algo'] !== null) {
            return password_verify((string) $plainText, $storedHash);
        }

        try {
            $legacyEncrypted = CryptoHelper::encrypt((string) $plainText);
            if (hash_equals($storedHash, $legacyEncrypted)) {
                return true;
            }
        } catch (Throwable $exception) {
            error_log('Legacy password check failed: ' . $exception->getMessage());
        }

        return hash_equals($storedHash, sha1(md5((string) $plainText)));
    }

    public static function needsRehash($storedHash)
    {
        return password_get_info((string) $storedHash)['algo'] === null
            || password_needs_rehash((string) $storedHash, PASSWORD_DEFAULT);
    }

    public static function hash($plainText)
    {
        return password_hash((string) $plainText, PASSWORD_DEFAULT);
    }

    public static function upgrade(mysqli $connection, $userId, $plainText, $storedHash)
    {
        if (!self::needsRehash($storedHash)) {
            return;
        }

        $newHash = self::hash($plainText);
        $statement = mysqli_prepare($connection, 'UPDATE user SET password = ? WHERE id = ?');
        if ($statement === false) {
            error_log('No fue posible preparar la actualizacion de credenciales: ' . mysqli_error($connection));
            return;
        }

        mysqli_stmt_bind_param($statement, 'si', $newHash, $userId);
        if (!mysqli_stmt_execute($statement)) {
            error_log('No fue posible actualizar la credencial: ' . mysqli_error($connection));
        }
        mysqli_stmt_close($statement);
    }
}