<?php

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Controller;
use App\Helpers\Validator;
use App\Models\Site;
use App\Models\Topic;
use App\Models\GlobalTopic;

class TopicController 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;
        }

        $topics = Topic::findBySiteWithGlobal((int) $id);
        $globalTopics = GlobalTopic::findAllGrouped();
        $assignedGlobalIds = array_values(array_unique(array_map(
            static fn($v) => (int) $v,
            array_filter(array_column($topics, 'global_topic_id'))
        )));
        $assignedTopicNames = array_values(array_unique(array_filter(array_map(
            static fn($name) => mb_strtolower(trim((string) $name)),
            array_column($topics, 'name')
        ))));

        $this->view('topics/index', [
            'site' => $site,
            'topics' => $topics,
            'globalTopics' => $globalTopics,
            'assignedGlobalIds' => $assignedGlobalIds,
            'assignedTopicNames' => $assignedTopicNames,
        ]);
    }

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

        $validator = new Validator();
        $validator->required('name', $this->input('name'), 'Nazwa tematu');

        if (!$validator->isValid()) {
            $this->flash('danger', $validator->getFirstError());
            $this->redirect("/sites/{$id}/topics");
            return;
        }

        Topic::create([
            'site_id' => (int) $id,
            'global_topic_id' => $this->input('global_topic_id') ? (int) $this->input('global_topic_id') : null,
            'name' => $this->input('name'),
            'description' => $this->input('description', ''),
            'wp_category_id' => $this->input('wp_category_id') ? (int) $this->input('wp_category_id') : null,
            'is_active' => $this->input('is_active') ? 1 : 0,
        ]);

        $this->flash('success', 'Temat został dodany.');
        $this->redirect("/sites/{$id}/topics?topic_added=1");
    }

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

        $topic = Topic::find((int) $id);
        if (!$topic) {
            $this->flash('danger', 'Temat nie znaleziony.');
            $this->redirect('/sites');
            return;
        }

        Topic::update((int) $id, [
            'global_topic_id' => $this->input('global_topic_id') ? (int) $this->input('global_topic_id') : null,
            'name' => $this->input('name'),
            'description' => $this->input('description', ''),
            'wp_category_id' => $this->input('wp_category_id') ? (int) $this->input('wp_category_id') : null,
            'is_active' => $this->input('is_active') ? 1 : 0,
        ]);

        $this->flash('success', 'Temat został zaktualizowany.');
        $this->redirect("/sites/{$topic['site_id']}/topics");
    }

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

        $isAjax = !empty($_SERVER['HTTP_X_REQUESTED_WITH'])
            && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';

        $topic = Topic::find((int) $id);
        if (!$topic) {
            if ($isAjax) {
                $this->json(['success' => false, 'message' => 'Temat nie znaleziony.']);
                return;
            }
            $this->flash('danger', 'Temat nie znaleziony.');
            $this->redirect('/sites');
            return;
        }

        $siteId = $topic['site_id'];
        Topic::delete((int) $id);

        if ($isAjax) {
            $this->json(['success' => true, 'message' => 'Temat został usunięty.']);
            return;
        }

        $this->flash('success', 'Temat został usunięty.');
        $this->redirect("/sites/{$siteId}/topics");
    }
}
