<?php

declare(strict_types=1);

namespace App\Models;

use App\Core\Model;
use PDO;

/**
 * Faq Model
 *
 * Handles frequently asked questions data retrieval.
 */
class Faq extends Model
{
    /**
     * The database table associated with the model.
     */
    protected string $table = 'faqs';

    /**
     * Get FAQs for the home page.
     *
     * Tries to use show_on_home column if it exists,
     * otherwise falls back to just active FAQs.
     *
     * @param int $limit Maximum number of FAQs to return
     * @return array<int, array<string, mixed>>
     */
    public function getForHome(int $limit = 6): array
    {
        // Try with show_on_home column first
        try {
            $sql = sprintf(
                'SELECT * FROM `%s` WHERE `show_on_home` = :show_on_home AND `active` = :active ORDER BY `sort_order` ASC LIMIT :limit',
                $this->table
            );

            $stmt = $this->db->prepare($sql);
            $stmt->bindValue(':show_on_home', 1, PDO::PARAM_INT);
            $stmt->bindValue(':active', 1, PDO::PARAM_INT);
            $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
            $stmt->execute();

            $results = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];

            // If we got results, return them
            if (!empty($results)) {
                return $results;
            }
        } catch (\Throwable $e) {
            // show_on_home column may not exist yet — fall through
            error_log('Faq::getForHome (with show_on_home) error: ' . $e->getMessage());
        }

        // Fallback: get active FAQs without show_on_home filter
        try {
            $sql = sprintf(
                'SELECT * FROM `%s` WHERE `active` = :active ORDER BY `sort_order` ASC, `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) {
            error_log('Faq::getForHome (fallback) error: ' . $e->getMessage());
            return [];
        }
    }

    /**
     * Get FAQs filtered by category.
     *
     * @param string $category The FAQ category to filter by
     * @return array<int, array<string, mixed>>
     */
    public function getByCategory(string $category): array
    {
        $sql = sprintf(
            'SELECT * FROM `%s` WHERE `category` = :category AND `active` = :active ORDER BY `sort_order` ASC',
            $this->table
        );

        $stmt = $this->db->prepare($sql);
        $stmt->execute([':category' => $category, ':active' => 1]);

        return $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
    }
}
