<?php

namespace App\Models;

use Core\Model;

/**
 * Email Queue Model
 *
 * This model represents the 'email_queue' table. By extending Core\Model,
 * it automatically inherits all standard data operations (find, create, etc.).
 */
class EmailQueue extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected static string $table = "email_queue";

    /**
     * Update the status of an email in the queue.
     *
     * @param int $id The email record ID.
     * @param string $status New status ('pending', 'sent', 'failed', etc.).
     * @param string|null $sentAt Optional timestamp when the email was sent.
     * @return int Rows affected
     */
    public static function updateStatus(int $id, string $status, ?string $sentAt = null): int
    {
        $data = ['status' => $status];
        if ($sentAt !== null) {
            $data['sent_at'] = $sentAt;
        }

        return self::update($id, $data);
    }

    /**
     * Fetch pending emails from the queue.
     *
     * @param int $limit Number of emails to fetch
     * @return array
     */
    public static function getPendingEmails(int $limit = 10): array
    {
        $sql = "SELECT * FROM `" . self::$table . "` WHERE `status` = 'pending' ORDER BY `created_at` ASC LIMIT ?";
        return self::fetchAll($sql, [$limit]);
    }
}
