<?php

namespace App\Http\Controllers\Admin;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Models\EventCategory;
use App\Models\Event;

/**
 * ITSWEBER CMS – Admin Event Category Controller (Phase 4b)
 */
class EventCategoryController extends Controller
{
    // -------------------------------------------------------------------------
    // LIST
    // -------------------------------------------------------------------------

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

        $this->renderAdmin('events/categories', [
            'pageTitle'  => __('admin.event_categories.title'),
            '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.error.category_name_required'));
            Response::redirect('/admin/events/categories');
            return;
        }

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

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

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

        set_flash('success', 'Category "' . $name . '" created.');
        Response::redirect('/admin/events/categories');
    }

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

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

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

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

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

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

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

        $existing = EventCategory::findBySlug($slug);
        if ($existing && (int) $existing['id'] !== $id) {
            set_flash('error', __('messages.error.slug_taken'));
            Response::redirect('/admin/events/categories');
            return;
        }

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

        set_flash('success', 'Category updated.');
        Response::redirect('/admin/events/categories');
    }

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

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

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

        // Safe delete: refuse if events are assigned
        $eventCount = Event::count(['category_id' => $id]);
        if ($eventCount > 0) {
            set_flash('error', __('messages.error.category_has_items', ['count' => $eventCount]));
            Response::redirect('/admin/events/categories');
            return;
        }

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

        EventCategory::deleteById($id);
        set_flash('success', 'Category deleted.');
        Response::redirect('/admin/events/categories');
    }
}
