<?php

declare(strict_types=1);

namespace App\Models;

use App\Core\Model;
use PDO;

/**
 * BranchNews Model
 *
 * Handles branch news articles data retrieval with JOIN on branches
 * for the branch name.
 */
class BranchNews extends Model
{
    /**
     * The database table associated with the model.
     */
    protected string $table = 'branch_news';

    /**
     * Get the latest branch news with JOIN on branches for branch name.
     *
     * @param int $limit Maximum number of news articles to return
     * @return array<int, array<string, mixed>>
     */
    public function getLatest(int $limit = 6): array
    {
        $sql = sprintf(
            'SELECT bn.*, b.name AS branch_name
             FROM `%s` bn
             LEFT JOIN `branches` b ON bn.branch_id = b.id
             WHERE bn.active = :active
             ORDER BY bn.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) ?: [];
    }

    /**
     * Get a single news article by its slug with JOIN on branches for branch name.
     *
     * @param string $slug The URL-friendly slug to look up
     * @return array<string, mixed>|null The news article or null if not found
     */
    public function getBySlug(string $slug): ?array
    {
        $sql = sprintf(
            'SELECT bn.*, b.name AS branch_name
             FROM `%s` bn
             LEFT JOIN `branches` b ON bn.branch_id = b.id
             WHERE bn.slug = :slug AND bn.active = :active
             LIMIT 1',
            $this->table
        );

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

        $result = $stmt->fetch(PDO::FETCH_ASSOC);

        return $result !== false ? $result : null;
    }
}
