<?php

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Config;
use App\Core\Controller;
use App\Core\Database;
use App\Helpers\Logger;
use App\Services\StatLinkService;

class StatLinkController extends Controller
{
    public function index(): void
    {
        Auth::requireLogin();

        $db = Database::getInstance();
        $page = max(1, (int) $this->input('page', 1));
        $perPage = 20;
        $offset = ($page - 1) * $perPage;

        // Stats
        $stats = [];
        $statsStmt = $db->query(
            "SELECT status, COUNT(*) as cnt FROM statlink_links GROUP BY status"
        );
        foreach ($statsStmt->fetchAll() as $row) {
            $stats[$row['status']] = (int) $row['cnt'];
        }

        $totalLinks = array_sum($stats);
        $totalPages = max(1, (int) ceil($totalLinks / $perPage));

        // Links with article and site info
        $stmt = $db->prepare(
            "SELECT sl.*, a.title as article_title, s.name as site_name
             FROM statlink_links sl
             LEFT JOIN articles a ON sl.article_id = a.id
             LEFT JOIN sites s ON sl.site_id = s.id
             ORDER BY sl.added_at DESC
             LIMIT :limit OFFSET :offset"
        );
        $stmt->bindValue('limit', $perPage, \PDO::PARAM_INT);
        $stmt->bindValue('offset', $offset, \PDO::PARAM_INT);
        $stmt->execute();
        $links = $stmt->fetchAll();

        $this->view('statlink/index', [
            'links' => $links,
            'stats' => $stats,
            'page' => $page,
            'totalPages' => $totalPages,
            'totalLinks' => $totalLinks,
        ]);
    }

    public function runByToken(): void
    {
        $configuredToken = (string) Config::get('SEO_TRIGGER_TOKEN', '');
        $providedToken = (string) $this->input('token', '');

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

        if ($configuredToken === '') {
            $this->json(['success' => false, 'message' => 'Token trigger is disabled.'], 503);
            return;
        }

        if ($providedToken === '' || !hash_equals($configuredToken, $providedToken)) {
            $this->json(['success' => false, 'message' => 'Forbidden'], 403);
            return;
        }

        @set_time_limit(300);

        $service = new StatLinkService();

        // One action per run: prioritize removing expired, then retry failed, then add new
        $removeResult = $service->removeExpiredLinks();

        if ($removeResult['removed'] > 0 || $removeResult['errors'] > 0) {
            $this->json([
                'success' => true,
                'action' => 'remove',
                'removed' => $removeResult['removed'],
                'remove_errors' => $removeResult['errors'],
            ]);
            return;
        }

        // Retry failed links before adding new ones
        $retryResult = $service->retryFailedLinks();
        if ($retryResult['retried'] > 0 || $retryResult['errors'] > 0) {
            $this->json([
                'success' => true,
                'action' => 'retry',
                'retried' => $retryResult['retried'],
                'still_failed' => $retryResult['still_failed'],
                'retry_errors' => $retryResult['errors'],
                'diagnostics' => $service->getLastDiagnostics(),
            ]);
            return;
        }

        $addResult = $service->processNewArticles();
        $this->json([
            'success' => true,
            'action' => 'add',
            'added' => $addResult['added'],
            'skipped' => $addResult['skipped'],
            'add_errors' => $addResult['errors'],
            'diagnostics' => $service->getLastDiagnostics(),
        ]);
    }
}
