<?php

declare(strict_types=1);

namespace App\Models;

use App\Core\Model;
use PDO;

/**
 * Announcement Model
 *
 * Handles site-wide announcements data retrieval with fallback queries.
 */
class Announcement extends Model
{
    protected string $table = 'announcements';

    /**
     * Get all active announcements ordered by created_at DESC.
     */
    public function getActive(): array
    {
        try {
            $sql = sprintf('SELECT * FROM `%s` WHERE `active` = :active ORDER BY `created_at` DESC', $this->table);
            $stmt = $this->db->prepare($sql);
            $stmt->execute([':active' => 1]);
            return $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
        } catch (\Throwable $e) {
            // Fallback: without active/created_at columns
            try {
                $sql = sprintf('SELECT * FROM `%s` ORDER BY `id` DESC', $this->table);
                $stmt = $this->db->prepare($sql);
                $stmt->execute();
                return $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
            } catch (\Throwable $e2) {
                return [];
            }
        }
    }

    /**
     * Get the latest active announcements with a limit.
     */
    public function getLatest(int $limit = 5): array
    {
        try {
            $sql = sprintf('SELECT * FROM `%s` WHERE `active` = :active ORDER BY `created_at` DESC LIMIT :limit', $this->table);
            $stmt = $this->db->prepare($sql);
            $stmt->bindValue(':active', 1, PDO::PARAM_INT);
            $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
            $stmt->execute();
            return $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
        } catch (\Throwable $e) {
            try {
                $sql = sprintf('SELECT * FROM `%s` ORDER BY `id` DESC LIMIT :limit', $this->table);
                $stmt = $this->db->prepare($sql);
                $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
                $stmt->execute();
                return $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
            } catch (\Throwable $e2) {
                return [];
            }
        }
    }
}
