<?php

/**
 * Main plugin orchestrator.
 *
 * @package BulkAltText
 */

declare(strict_types=1);

namespace BulkAltText;

use BulkAltText\Admin\SettingsPage;
use BulkAltText\Media\MediaIntegration;
use BulkAltText\Licensing\LicenseManager;
use BulkAltText\Rest\RestController;

if (!defined('ABSPATH')) {
    exit;
}

/**
 * Wires together every moving part of the plugin.
 */
final class Plugin
{
    private static ?Plugin $instance = null;

    private bool $booted = false;

    public static function instance(): Plugin
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }

        return self::$instance;
    }

    /**
     * Register all hooks. Idempotent.
     */
    public function init(): void
    {
        if ($this->booted) {
            return;
        }
        $this->booted = true;

        // Translations for plugins hosted on WordPress.org load automatically
        // since WP 4.6, so no load_plugin_textdomain() call is needed.

        ( new RestController() )->register();

        // Media library button + auto-generate-on-upload run everywhere.
        ( new MediaIntegration() )->register();

        if (is_admin()) {
            ( new SettingsPage() )->register();
        }

        add_filter('plugin_action_links_' . BATAI_BASENAME, [$this, 'action_links']);
    }

    /**
     * @param array<int, string> $links
     * @return array<int, string>
     */
    public function action_links(array $links): array
    {
        $settings = sprintf(
            '<a href="%s">%s</a>',
            esc_url(admin_url('upload.php?page=bulk-alt-text-ai')),
            esc_html__('Bulk generate', 'bulk-alt-text-ai')
        );

        $license = LicenseManager::instance();
        if (!$license->is_pro()) {
            $upgrade = sprintf(
                '<a href="%s" style="color:#16a34a;font-weight:600;">%s</a>',
                esc_url($license->upgrade_url()),
                esc_html__('Go Pro', 'bulk-alt-text-ai')
            );
            array_unshift($links, $settings, $upgrade);
        } else {
            array_unshift($links, $settings);
        }

        return $links;
    }

    public static function on_activate(): void
    {
        $defaults = [
            'language'       => 'site',
            'max_length'     => 125,
            'auto_on_upload' => false,
            'overwrite'      => false,
        ];
        if (get_option('batai_settings') === false) {
            add_option('batai_settings', $defaults);
        }

        if (get_option('batai_usage') === false) {
            add_option('batai_usage', ['period' => gmdate('Y-m'), 'count' => 0]);
        }
    }

    public static function on_deactivate(): void
    {
        // Nothing persistent to tear down; uninstall.php handles full cleanup.
    }
}
