<?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'  => 'Event 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', 'Category name is required.');
            Response::redirect('/admin/events/categories');
            return;
        }

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

        $existing = EventCategory::findBySlug($slug);
        if ($existing) {
            set_flash('error', 'A category with this slug already exists.');
            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', 'Category not found.');
            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', 'Category name is 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', 'Another category with this slug already exists.');
            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', 'Cannot delete: ' . $eventCount . ' event(s) are assigned to this category. Reassign or delete them first.');
            Response::redirect('/admin/events/categories');
            return;
        }

        $category = EventCategory::find($id);
        if (!$category) {
            set_flash('error', 'Category not found.');
            Response::redirect('/admin/events/categories');
            return;
        }

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