<?php

/**
 * Pro access (via Freemius) + free-tier quota enforcement.
 *
 * @package BulkAltText
 */

declare(strict_types=1);

namespace BulkAltText\Licensing;

use WP_Error;

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

class LicenseManager
{
    private static ?LicenseManager $instance = null;

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

        return self::$instance;
    }

    /**
     * Is the site allowed to use Pro features?
     *
     * Pro is granted exclusively by Freemius — a paying customer or an active
     * trial. There is no bypass in code.
     */
    public function is_pro(): bool
    {
        if (!function_exists('bata_fs')) {
            return false;
        }

        $fs = \bata_fs();

        if (method_exists($fs, 'can_use_premium_code') && $fs->can_use_premium_code()) {
            return true;
        }
        if (method_exists($fs, 'is_paying') && $fs->is_paying()) {
            return true;
        }
        if (method_exists($fs, 'is_trial') && $fs->is_trial()) {
            return true;
        }

        return false;
    }

    /**
     * URL of the Freemius upgrade/pricing screen, shown to free users.
     */
    public function upgrade_url(): string
    {
        if (function_exists('bata_fs')) {
            $fs = \bata_fs();
            if (method_exists($fs, 'get_upgrade_url')) {
                return (string) $fs->get_upgrade_url();
            }
        }

        return admin_url('upload.php?page=bulk-alt-text-ai');
    }

    /* ------------------------------------------------------------------ */
    /* Feature gating                                                      */
    /* ------------------------------------------------------------------ */

    /**
     * May the site run an AI generation? AI is a Pro-only feature; the free
     * plan can audit images and apply alt text manually, but not use the AI.
     *
     * @return true|WP_Error  true if allowed, WP_Error('batai_pro_only') if not.
     */
    public function can_generate()
    {
        if ($this->is_pro()) {
            return true;
        }

        return new WP_Error(
            'batai_pro_only',
            __('AI alt text is a Pro feature. Upgrade to let the AI write your image alt text automatically.', 'bulk-alt-text-ai'),
            ['upgrade_url' => $this->upgrade_url()]
        );
    }
}
