<?php

namespace App\Http\Controllers\Admin;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Models\DownloadCategory;
use App\Models\Download;

/**
 * ITSWEBER CMS – Admin Download Category Controller (Phase 8)
 */
class DownloadCategoryController extends Controller
{
    // -------------------------------------------------------------------------
    // LIST
    // -------------------------------------------------------------------------

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

        $this->renderAdmin('downloads/categories', [
            'pageTitle'  => __('admin.download_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_url('downloads/categories'));
            return;
        }

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

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

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

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

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

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

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

        if (!$category) {
            set_flash('error', __('messages.not_found', ['item' => __('admin.nav.categories')]));
            Response::redirect(admin_url('downloads/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_url('downloads/categories'));
            return;
        }

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

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

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

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

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

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

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

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

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

        DownloadCategory::deleteById($id);
        set_flash('success', 'Category deleted.');
        Response::redirect(admin_url('downloads/categories'));
    }
}
