<?php

declare(strict_types=1);

namespace App\Models;

use App\Core\Model;
use PDO;

/**
 * Affiliation Model
 *
 * Handles affiliations and partners data retrieval with fallback queries.
 */
class Affiliation extends Model
{
    protected string $table = 'affiliations';

    /**
     * Get affiliations/partners filtered by type.
     */
    public function getByType(string $type): array
    {
        try {
            $sql = sprintf('SELECT * FROM `%s` WHERE `type` = :type AND `active` = :active ORDER BY `sort_order` ASC', $this->table);
            $stmt = $this->db->prepare($sql);
            $stmt->execute([':type' => $type, ':active' => 1]);
            return $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
        } catch (\Throwable $e) {
            // Fallback: try without active/sort_order
            try {
                $sql = sprintf('SELECT * FROM `%s` WHERE `type` = :type ORDER BY `id` ASC', $this->table);
                $stmt = $this->db->prepare($sql);
                $stmt->execute([':type' => $type]);
                return $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
            } catch (\Throwable $e2) {
                return [];
            }
        }
    }

    /**
     * Get all active affiliations and partners.
     */
    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) {
            try {
                return $this->all();
            } catch (\Throwable $e2) {
                return [];
            }
        }
    }
}
