<?php

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Config;
use App\Core\Controller;
use App\Helpers\Logger;
use App\Models\Site;
use App\Services\PublisherService;

class PublishController extends Controller
{
    public function runByToken(): void
    {
        $configuredToken = (string) Config::get('PUBLISH_TRIGGER_TOKEN', '');
        $providedToken = (string) $this->input('token', '');

        if ($providedToken === '') {
            $providedToken = (string) ($_SERVER['HTTP_X_PUBLISH_TOKEN'] ?? '');
        }

        if ($configuredToken === '') {
            Logger::warning('Token publish trigger called, but PUBLISH_TRIGGER_TOKEN is not configured.', 'publish');
            $this->json(['success' => false, 'message' => 'Token trigger is disabled.'], 503);
            return;
        }

        if ($providedToken === '' || !hash_equals($configuredToken, $providedToken)) {
            $ip = (string) ($_SERVER['REMOTE_ADDR'] ?? 'unknown');
            Logger::warning("Invalid publish token attempt from {$ip}", 'publish');
            $this->json(['success' => false, 'message' => 'Forbidden'], 403);
            return;
        }

        $publisher = new PublisherService();
        $result = $publisher->publishNext();

        $this->json($result, 200);
    }

    public function run(): void
    {
        Auth::requireLogin();

        $publisher = new PublisherService();
        $result = $publisher->publishNext();

        if ($result['success']) {
            $this->flash('success', $result['message']);
        } else {
            $this->flash('danger', $result['message']);
        }

        $this->redirect('/');
    }

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

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

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

        $publisher = new PublisherService();
        $result = $publisher->publishForSite($site);

        if ($isAjax) {
            $this->json($result);
            return;
        }

        if ($result['success']) {
            $this->flash('success', $result['message']);
        } else {
            $this->flash('danger', $result['message']);
        }

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