<?php

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Controller;
use App\Models\Site;
use App\Models\Topic;
use App\Services\WordPressService;

class CategoryController extends Controller
{
    public function index(string $id): void
    {
        Auth::requireLogin();

        $site = Site::find((int) $id);
        if (!$site) {
            $this->flash('danger', 'Strona nie znaleziona.');
            $this->redirect('/sites');
            return;
        }

        $wp = new WordPressService();
        $categories = $wp->getCategories($site);

        $topics = Topic::findBySiteWithGlobal((int) $id);
        $hasTopicsWithoutCategory = false;
        foreach ($topics as $t) {
            if (!empty($t['global_topic_id']) && empty($t['wp_category_id'])) {
                $hasTopicsWithoutCategory = true;
                break;
            }
        }

        $this->view('categories/index', [
            'site' => $site,
            'categories' => $categories,
            'hasTopicsWithoutCategory' => $hasTopicsWithoutCategory,
        ]);
    }

    public function sync(string $id): void
    {
        Auth::requireLogin();

        $site = Site::find((int) $id);
        if (!$site) {
            $this->flash('danger', 'Strona nie znaleziona.');
            $this->redirect('/sites');
            return;
        }

        $wp = new WordPressService();
        $categories = $wp->getCategories($site);

        if ($categories === false) {
            $this->flash('danger', 'Nie udało się pobrać kategorii z WordPress.');
        } else {
            $this->flash('success', 'Pobrano ' . count($categories) . ' kategorii z WordPress.');
        }

        $this->redirect("/sites/{$id}/categories");
    }

    public function create(string $id): void
    {
        Auth::requireLogin();

        $site = Site::find((int) $id);
        if (!$site) {
            $this->json(['success' => false, 'message' => 'Strona nie znaleziona.']);
            return;
        }

        $name = trim($this->input('name', ''));
        if ($name === '') {
            $this->json(['success' => false, 'message' => 'Nazwa kategorii jest wymagana.']);
            return;
        }

        $parent = (int) $this->input('parent', 0);

        $wp = new WordPressService();
        $result = $wp->createCategory($site, $name, $parent);

        if (!$result || !isset($result['id'])) {
            $this->json(['success' => false, 'message' => 'Nie udało się utworzyć kategorii w WordPress.']);
            return;
        }

        $this->json([
            'success' => true,
            'message' => "Utworzono kategorię \"{$result['name']}\" (ID: {$result['id']})",
            'category' => [
                'id' => $result['id'],
                'name' => $result['name'],
                'slug' => $result['slug'],
                'parent' => $result['parent'],
            ],
        ]);
    }

    public function createFromTopics(string $id): void
    {
        Auth::requireLogin();

        $site = Site::find((int) $id);
        if (!$site) {
            $this->json(['success' => false, 'message' => 'Strona nie znaleziona.']);
            return;
        }

        $wp = new WordPressService();

        // Get existing WP categories
        $existingCategories = $wp->getCategories($site);
        if ($existingCategories === false) {
            $this->json(['success' => false, 'message' => 'Nie udało się pobrać kategorii z WordPress.']);
            return;
        }

        // Index existing by name (lowercase) for duplicate detection
        $existingByName = [];
        foreach ($existingCategories as $cat) {
            $existingByName[mb_strtolower($cat['name'])] = $cat;
        }

        // Get site topics with global topic info
        $topics = Topic::findBySiteWithGlobal((int) $id);

        // Group topics by parent category
        $groups = [];
        foreach ($topics as $topic) {
            if (empty($topic['global_topic_id'])) {
                continue; // skip custom topics without global link
            }
            $parentName = $topic['global_category_name'] ?? null;
            $childName = $topic['global_topic_name'] ?? $topic['name'];

            if (!$parentName) {
                // Topic is linked to a top-level global topic (it IS a category, not a child)
                // Create as standalone category
                $parentName = $childName;
                $childName = null;
            }

            if (!isset($groups[$parentName])) {
                $groups[$parentName] = [];
            }
            if ($childName) {
                $groups[$parentName][] = [
                    'topic_id' => $topic['id'],
                    'name' => $childName,
                ];
            }
        }

        $created = 0;
        $skipped = 0;
        $assigned = 0;
        $errors = [];

        foreach ($groups as $parentName => $children) {
            // Find or create parent category in WP
            $parentKey = mb_strtolower($parentName);
            if (isset($existingByName[$parentKey])) {
                $parentWpId = $existingByName[$parentKey]['id'];
                $skipped++;
            } else {
                $parentResult = $wp->createCategory($site, $parentName, 0);
                if (!$parentResult || !isset($parentResult['id'])) {
                    $errors[] = "Nie udało się utworzyć kategorii \"{$parentName}\"";
                    continue;
                }
                $parentWpId = $parentResult['id'];
                $existingByName[$parentKey] = $parentResult;
                $created++;
            }

            // Create child categories
            foreach ($children as $child) {
                $childKey = mb_strtolower($child['name']);
                if (isset($existingByName[$childKey])) {
                    $childWpId = $existingByName[$childKey]['id'];
                    $skipped++;
                } else {
                    $childResult = $wp->createCategory($site, $child['name'], $parentWpId);
                    if (!$childResult || !isset($childResult['id'])) {
                        $errors[] = "Nie udało się utworzyć podkategorii \"{$child['name']}\"";
                        continue;
                    }
                    $childWpId = $childResult['id'];
                    $existingByName[$childKey] = $childResult;
                    $created++;
                }

                // Assign wp_category_id to the topic
                Topic::update($child['topic_id'], ['wp_category_id' => $childWpId]);
                $assigned++;
            }
        }

        $message = "Utworzono {$created} kategorii, pominięto {$skipped} istniejących, przypisano {$assigned} tematów.";
        if (!empty($errors)) {
            $message .= ' Błędy: ' . implode('; ', $errors);
        }

        $this->json([
            'success' => true,
            'message' => $message,
            'created' => $created,
            'skipped' => $skipped,
            'assigned' => $assigned,
            'errors' => $errors,
        ]);
    }
}
