<?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'  => 'Download 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/downloads/categories');
            return;
        }

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

        $existing = DownloadCategory::findBySlug($slug);
        if ($existing) {
            set_flash('error', 'A category with this slug already exists.');
            Response::redirect('/admin/downloads/categories');
            return;
        }

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

        set_flash('success', 'Category "' . $name . '" created.');
        Response::redirect('/admin/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', 'Category not found.');
            Response::redirect('/admin/downloads/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/downloads/categories');
            return;
        }

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

        $existing = DownloadCategory::findBySlug($slug);
        if ($existing && (int) $existing['id'] !== $id) {
            set_flash('error', 'Another category with this slug already exists.');
            Response::redirect('/admin/downloads/categories');
            return;
        }

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

        set_flash('success', 'Category updated.');
        Response::redirect('/admin/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', 'Cannot delete: ' . $count . ' download(s) are assigned to this category. Reassign or delete them first.');
            Response::redirect('/admin/downloads/categories');
            return;
        }

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

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