<?php

declare(strict_types=1);

$basePath = dirname(__DIR__);

try {
    require_once $basePath . '/vendor/autoload.php';

    \App\Core\Config::load($basePath);
    \App\Helpers\Logger::setBasePath($basePath);

    $sites = \App\Models\Site::findAll('id ASC');
    if (empty($sites)) {
        echo "Brak stron do aktualizacji.\n";
        exit(0);
    }

    $wordpress = new \App\Services\WordPressService();
    $success = 0;
    $failed = 0;

    foreach ($sites as $site) {
        $siteId = (int) ($site['id'] ?? 0);
        $siteName = (string) ($site['name'] ?? 'bez-nazwy');
        $siteUrl = (string) ($site['url'] ?? '');

        $result = $wordpress->enableSearchEngineIndexing($site);
        $isSuccess = !empty($result['success']);
        $message = (string) ($result['message'] ?? 'brak komunikatu');

        if ($isSuccess) {
            $success++;
        } else {
            $failed++;
        }

        echo sprintf(
            "[%s] site_id=%d, status=%s, site=%s, url=%s, message=%s\n",
            date('Y-m-d H:i:s'),
            $siteId,
            $isSuccess ? 'ok' : 'error',
            $siteName,
            $siteUrl,
            $message
        );
    }

    $summary = "Indexing fix summary: success={$success}, failed={$failed}";
    \App\Helpers\Logger::info($summary, 'installer');
    echo $summary . "\n";
} catch (\Throwable $e) {
    $message = 'Enable indexing cron error: ' . $e->getMessage();
    echo $message . "\n";

    if (class_exists(\App\Helpers\Logger::class)) {
        \App\Helpers\Logger::error($message, 'installer');
    }
    exit(1);
}
