<?php
require_once __DIR__ . '/../Core.php';

class PasswordReset extends Model
{
    public function createToken(int $userId, string $email): string
    {
        $token = random_token(24);
        $hash = hash('sha256', $token);
        $this->db->prepare('UPDATE password_resets SET used_at = NOW() WHERE user_id = ? AND used_at IS NULL')->execute([$userId]);
        $stmt = $this->db->prepare('INSERT INTO password_resets (user_id, email, token_hash, expires_at) VALUES (?, ?, ?, DATE_ADD(NOW(), INTERVAL 60 MINUTE))');
        $stmt->execute([$userId, $email, $hash]);
        return $token;
    }

    public function findValid(string $token): ?array
    {
        $hash = hash('sha256', $token);
        $stmt = $this->db->prepare('SELECT * FROM password_resets WHERE token_hash = ? AND used_at IS NULL AND expires_at >= NOW() ORDER BY id DESC LIMIT 1');
        $stmt->execute([$hash]);
        return $stmt->fetch() ?: null;
    }

    public function markUsed(int $id): bool
    {
        $stmt = $this->db->prepare('UPDATE password_resets SET used_at = NOW() WHERE id = ?');
        return $stmt->execute([$id]);
    }
}
