<?php

namespace App\Models;

use App\Core\Model;

class BlogTag extends Model
{
    protected static string $table = 'iw_blog_tags';

    /**
     * Find a tag by name (case-insensitive), or create it if it doesn't exist.
     * Returns the tag row.
     */
    public static function findOrCreateByName(string $name): array
    {
        $name = trim($name);
        if ($name === '') {
            return [];
        }

        $existing = static::db()->fetch(
            "SELECT * FROM iw_blog_tags WHERE LOWER(name) = LOWER(:name) LIMIT 1",
            ['name' => $name]
        );

        if ($existing) {
            return $existing;
        }

        $slug = slugify($name);

        // Ensure slug uniqueness
        $slugCheck = static::findBySlug($slug);
        if ($slugCheck) {
            $slug = $slug . '-' . bin2hex(random_bytes(4));
        }

        $id = static::create([
            'name' => $name,
            'slug' => $slug,
        ]);

        return static::find($id) ?? ['id' => $id, 'name' => $name, 'slug' => $slug];
    }

    /**
     * Return all tags with their post count (for admin tag management).
     *
     * @return array[]
     */
    public static function allWithPostCount(): array
    {
        return static::db()->fetchAll(
            "SELECT t.*, COUNT(pt.post_id) AS post_count
             FROM iw_blog_tags t
             LEFT JOIN iw_blog_post_tags pt ON pt.tag_id = t.id
             GROUP BY t.id
             ORDER BY t.name ASC"
        );
    }

    /**
     * Return all tags assigned to a given post.
     *
     * @return array[]
     */
    public static function findByPost(int $postId): array
    {
        return static::db()->fetchAll(
            "SELECT t.*
             FROM iw_blog_tags t
             JOIN iw_blog_post_tags pt ON pt.tag_id = t.id
             WHERE pt.post_id = :post_id
             ORDER BY t.name ASC",
            ['post_id' => $postId]
        );
    }
}

