<?php

namespace Core\App\Models;

use PDO;

class AdminPasswordReset
{
    protected PDO $db;

    public function __construct()
    {
        $this->db = \db();
    }

    public function cleanupExpired(): void
    {
        $stmt = $this->db->prepare("
            DELETE FROM admin_password_resets
            WHERE expires_at <= NOW()
        ");
        $stmt->execute();
    }

    public function createReset(
        string $email,
        string $tokenHash,
        string $expiresAt,
        ?string $ipAddress,
        ?string $userAgent
    ): void {
        $stmt = $this->db->prepare("
            DELETE FROM admin_password_resets
            WHERE email = :email
        ");
        $stmt->execute([':email' => $email]);

        $stmt = $this->db->prepare("
            INSERT INTO admin_password_resets
                (email, token_hash, expires_at, ip_address, user_agent)
            VALUES
                (:email, :token_hash, :expires_at, :ip_address, :user_agent)
        ");

        $stmt->execute([
            ':email'       => $email,
            ':token_hash'  => $tokenHash,
            ':expires_at'  => $expiresAt,
            ':ip_address'  => $ipAddress,
            ':user_agent'  => $userAgent,
        ]);
    }

public function findValidByToken(string $tokenHash): ?array
{
    $stmt = $this->db->prepare("
        SELECT *
        FROM admin_password_resets
        WHERE token_hash = :token_hash
        LIMIT 1
    ");
    $stmt->execute([':token_hash' => $tokenHash]);

    $row = $stmt->fetch(\PDO::FETCH_ASSOC);

    if (!$row) {
        return null;
    }

    // التحقق من الانتهاء باستخدام PHP (نفس timezone)
    if (strtotime($row['expires_at']) <= time()) {
        return null;
    }

    return $row;
}


    public function deleteById(int $id): void
    {
        $stmt = $this->db->prepare("
            DELETE FROM admin_password_resets
            WHERE id = :id
            LIMIT 1
        ");
        $stmt->execute([':id' => $id]);
    }
}
