<?php

namespace App\Models;

use App\Core\Model;

/**
 * ITSWEBER CMS – PasswordReset Model
 *
 * Manages password-reset tokens stored in iw_password_resets.
 * Tokens are single-use, expire after 1 hour, and are deleted on use.
 */
class PasswordReset extends Model
{
    protected static string $table = 'iw_password_resets';

    /** Token lifetime in seconds (1 hour). */
    const TOKEN_TTL = 3600;

    /**
     * Create a new reset token for an e-mail address.
     *
     * Any previous tokens for the same address are deleted first so that
     * only the latest token is ever valid (prevents token accumulation).
     *
     * @return string The generated token (64 hex chars).
     */
    public static function createFor(string $email): string
    {
        // Remove any previous tokens for this address
        static::deleteForEmail($email);

        $token     = bin2hex(random_bytes(32));
        $expiresAt = date('Y-m-d H:i:s', time() + self::TOKEN_TTL);

        static::create([
            'email'      => $email,
            'token'      => $token,
            'expires_at' => $expiresAt,
            'created_at' => date('Y-m-d H:i:s'),
        ]);

        return $token;
    }

    /**
     * Find a valid (non-expired) reset record by token.
     *
     * @return array|null The reset row, or null if not found / expired.
     */
    public static function findValid(string $token): ?array
    {
        return static::db()->fetch(
            "SELECT * FROM iw_password_resets
              WHERE token = :token
                AND expires_at > :now
              LIMIT 1",
            [
                'token' => $token,
                'now'   => date('Y-m-d H:i:s'),
            ]
        );
    }

    /**
     * Delete all reset tokens for the given e-mail address.
     */
    public static function deleteForEmail(string $email): void
    {
        static::db()->delete('iw_password_resets', ['email' => $email]);
    }

    /**
     * Delete a specific token (called after successful password change).
     */
    public static function deleteToken(string $token): void
    {
        static::db()->delete('iw_password_resets', ['token' => $token]);
    }

    /**
     * Remove all expired tokens (housekeeping, called opportunistically).
     */
    public static function purgeExpired(): void
    {
        static::db()->query(
            "DELETE FROM iw_password_resets WHERE expires_at <= :now",
            ['now' => date('Y-m-d H:i:s')]
        );
    }
}
