<?php

declare(strict_types=1);

namespace App\Models;

use App\Core\Model;
use PDO;

/**
 * Slider Model
 *
 * Handles homepage carousel/slider data retrieval with fallback queries.
 */
class Slider extends Model
{
    protected string $table = 'sliders';

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

    /**
     * Get featured (active) sliders with a limit.
     */
    public function getFeatured(int $limit = 5): array
    {
        try {
            $sql = sprintf('SELECT * FROM `%s` WHERE `active` = :active ORDER BY `sort_order` ASC 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` ASC 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 [];
            }
        }
    }
}
