<?php

namespace App\Http\Controllers\Admin;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Models\BlogTag;

class BlogTagController extends Controller
{
    // -------------------------------------------------------------------------
    // LIST
    // -------------------------------------------------------------------------

    public function index(Request $request, array $params = []): void
    {
        $tags = BlogTag::allWithPostCount();

        $this->renderAdmin('blog/tags', [
            'pageTitle' => 'Blog Tags',
            'tags'      => $tags,
            'auth'      => $this->auth(),
            'csrf'      => $this->csrf(),
        ]);
    }

    // -------------------------------------------------------------------------
    // UPDATE (rename)
    // -------------------------------------------------------------------------

    public function update(Request $request, array $params = []): void
    {
        $this->validateCsrf();

        $id  = (int) ($params['id'] ?? 0);
        $tag = BlogTag::find($id);

        if (!$tag) {
            set_flash('error', __('messages.not_found', ['item' => 'Tag']));
            Response::redirect('/admin/blog/tags');
            return;
        }

        $newName = trim($request->input('name', ''));
        if (empty($newName)) {
            set_flash('error', __('messages.field_required'));
            Response::redirect('/admin/blog/tags');
            return;
        }

        // Check for name collision with a different tag (case-insensitive)
        $nameConflict = $this->db()->fetch(
            "SELECT id FROM iw_blog_tags WHERE LOWER(name) = LOWER(:name) AND id != :id LIMIT 1",
            ['name' => $newName, 'id' => $id]
        );
        if ($nameConflict) {
            set_flash('error', __('messages.error.name_taken'));
            Response::redirect('/admin/blog/tags');
            return;
        }

        // Slug: use provided or regenerate from new name
        $newSlug = trim($request->input('slug', ''));
        if (empty($newSlug)) {
            $newSlug = slugify($newName);
        }

        // Ensure slug uniqueness (excluding current tag)
        $slugConflict = $this->db()->fetch(
            "SELECT id FROM iw_blog_tags WHERE slug = :slug AND id != :id LIMIT 1",
            ['slug' => $newSlug, 'id' => $id]
        );
        if ($slugConflict) {
            $newSlug = $newSlug . '-' . substr(md5($newName . $id), 0, 6);
        }

        BlogTag::updateById($id, [
            'name' => $newName,
            'slug' => $newSlug,
        ]);

        set_flash('success', __('messages.updated'));
        Response::redirect('/admin/blog/tags');
    }

    // -------------------------------------------------------------------------
    // DELETE
    // -------------------------------------------------------------------------

    public function delete(Request $request, array $params = []): void
    {
        $this->validateCsrf();

        $id  = (int) ($params['id'] ?? 0);
        $tag = BlogTag::find($id);

        if (!$tag) {
            set_flash('error', __('messages.not_found', ['item' => 'Tag']));
            Response::redirect('/admin/blog/tags');
            return;
        }

        // Safety: refuse to delete if tag is still assigned to posts
        $postCount = (int) $this->db()->fetchColumn(
            "SELECT COUNT(*) FROM iw_blog_post_tags WHERE tag_id = :id",
            ['id' => $id]
        );

        if ($postCount > 0) {
            set_flash('error', __('messages.error.tag_has_posts', ['count' => $postCount]));
            Response::redirect('/admin/blog/tags');
            return;
        }

        BlogTag::deleteById($id);
        set_flash('success', __('messages.tag_deleted'));
        Response::redirect('/admin/blog/tags');
    }
}
