<?php

namespace App\Validation;

use Exception;
use App\Models\UsersModel;

class UserRules
{
    public function emailExists(string $str, string $fields, array $data): bool
    {
        try {
            $model = new UsersModel();
            $user = $model->findUserByEmailAddress($data['email']);
            if (!empty($user)) {
                return true;
            }
            return false;
        } catch (Exception $e) {
            return false;
        }
    }

    public function validateUser(string $str, string $fields, array $data): bool
    {
        try {
            $model = new UsersModel();
            $user = $model->findUserByEmailAddress($data['email']);
            if (!empty($user) && $this->verifyHashedPassword($user['PasswordHash'], ($data['password']))) {
                return true;
            }
            return false;
        } catch (Exception $e) {
            return false;
        }
    }


    private function verifyHashedPassword($hashedPassword, $password)
    {
        if ($hashedPassword === null) {
            return false;
        }
        if ($password === null) {
            throw new Exception("Password cannot be null");
        }
        $src = base64_decode($hashedPassword);

        $dst = substr($src, 1, 16);

        $buffer3 = substr($src, 17, 32);
        $buffer4 = hash_pbkdf2("sha1", $password, $dst, 1000, 32, true);
        return $this->areHashesEqual($buffer3, $buffer4);
    }

    private function areHashesEqual($firstHash, $secondHash)
    {
        $minHashLength = min(strlen($firstHash), strlen($secondHash));
        $xor = strlen($firstHash) ^ strlen($secondHash);
        for ($i = 0; $i < $minHashLength; $i++) {
            $xor |= ord($firstHash[$i]) ^ ord($secondHash[$i]);
        }
        return $xor === 0;
    }


    public function userExists(string $str, string $fields, array $data): bool
    {
        try {
            $model = new UsersModel();
            $user = $model->findUserById($data['user_id']);
            if (!empty($user)) {
                return true;
            }
            return false;
        } catch (Exception $e) {
            return false;
        }
    }
}
