<?php

namespace App\Http\Controllers\Admin;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Models\BlogCategory;
use App\Models\BlogPost;

class BlogCategoryController extends Controller
{
    // -------------------------------------------------------------------------
    // LIST
    // -------------------------------------------------------------------------

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

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

    // -------------------------------------------------------------------------
    // CREATE
    // -------------------------------------------------------------------------

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

        $name        = trim($request->input('name', ''));
        $slug        = trim($request->input('slug', ''));
        $description = trim($request->input('description', ''));

        if (empty($name)) {
            set_flash('error', __('messages.field_required'));
            Response::redirect('/admin/blog/categories');
            return;
        }

        if (empty($slug)) {
            $slug = slugify($name);
        }

        $existing = BlogCategory::findBySlug($slug);
        if ($existing) {
            set_flash('error', __('messages.error.slug_taken'));
            Response::redirect('/admin/blog/categories');
            return;
        }

        BlogCategory::create([
            'name'        => $name,
            'slug'        => $slug,
            'description' => $description,
            'sort_order'  => 0,
        ]);

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

    // -------------------------------------------------------------------------
    // UPDATE
    // -------------------------------------------------------------------------

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

        $id       = (int) ($params['id'] ?? 0);
        $category = BlogCategory::find($id);

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

        $name        = trim($request->input('name', ''));
        $slug        = trim($request->input('slug', ''));
        $description = trim($request->input('description', ''));

        if (empty($name)) {
            set_flash('error', __('messages.field_required'));
            Response::redirect('/admin/blog/categories');
            return;
        }

        if (empty($slug)) {
            $slug = slugify($name);
        }

        // Check slug conflict with another category
        $existing = BlogCategory::findBySlug($slug);
        if ($existing && (int) $existing['id'] !== $id) {
            set_flash('error', __('messages.error.slug_taken'));
            Response::redirect('/admin/blog/categories');
            return;
        }

        BlogCategory::updateById($id, [
            'name'        => $name,
            'slug'        => $slug,
            'description' => $description,
        ]);

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

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

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

        $id = (int) ($params['id'] ?? 0);

        // Safe delete: refuse if posts are assigned
        $postCount = BlogPost::count(['category_id' => $id]);
        if ($postCount > 0) {
            set_flash('error', __('messages.error.category_has_posts', ['count' => $postCount]));
            Response::redirect('/admin/blog/categories');
            return;
        }

        $category = BlogCategory::find($id);
        if (!$category) {
            set_flash('error', __('messages.not_found', ['item' => 'Category']));
            Response::redirect('/admin/blog/categories');
            return;
        }

        BlogCategory::deleteById($id);
        set_flash('success', __('messages.category_deleted'));
        Response::redirect('/admin/blog/categories');
    }
}
