<?php
declare(strict_types=1);
namespace Repositories;

final class AuthRepository extends BaseRepository
{
    public function findByEmail(string $email): ?array
    {
        return $this->fetchOne('SELECT * FROM users WHERE email=:email LIMIT 1', ['email' => $email]);
    }

    public function createUser(array $data): int
    {
        $this->execute('INSERT INTO users(name,email,phone,password_hash,role,status) VALUES(:name,:email,:phone,:password_hash,:role,"active")', $data);
        return (int)$this->db->lastInsertId();
    }

    public function createToken(int $userId, string $token, int $days = 30): void
    {
        $this->execute('INSERT INTO auth_tokens(user_id, token_hash, expires_at) VALUES(:user_id,:token_hash, DATE_ADD(NOW(), INTERVAL 30 DAY))', [
            'user_id' => $userId,
            'token_hash' => hash('sha256', $token)
        ]);
    }

    public function deleteToken(string $token): void
    {
        $this->execute('DELETE FROM auth_tokens WHERE token_hash=:hash', ['hash' => hash('sha256', $token)]);
    }
}
