<?php
namespace WebshoptigerCatalogSync;

defined( 'ABSPATH' ) || exit;

class Plugin {

    private static ?Plugin $instance = null;

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

    private function __construct() {
        $this->load_dependencies();
        $this->init_hooks();
    }

    private function load_dependencies(): void {
        require_once WEBSHOPTIGERCATALOGSYNC_PATH . 'includes/Installer.php';
        require_once WEBSHOPTIGERCATALOGSYNC_PATH . 'includes/Settings.php';

        // Always load — needed on both the source and destination site
        require_once WEBSHOPTIGERCATALOGSYNC_PATH . 'includes/DestinationGuard.php';
        require_once WEBSHOPTIGERCATALOGSYNC_PATH . 'includes/BrandSync.php';
        require_once WEBSHOPTIGERCATALOGSYNC_PATH . 'includes/RestAPI.php';

        // Only load on the source site
        if ( Settings::is_source_site() ) {
            require_once WEBSHOPTIGERCATALOGSYNC_PATH . 'includes/SiteManager.php';
            require_once WEBSHOPTIGERCATALOGSYNC_PATH . 'includes/CategorySync.php';
            require_once WEBSHOPTIGERCATALOGSYNC_PATH . 'includes/Queue.php';
            require_once WEBSHOPTIGERCATALOGSYNC_PATH . 'includes/Sync.php';
            require_once WEBSHOPTIGERCATALOGSYNC_PATH . 'includes/Scheduler.php';
        }

        if ( is_admin() ) {
            require_once WEBSHOPTIGERCATALOGSYNC_PATH . 'admin/AdminPage.php';
        }
    }

    private function init_hooks(): void {
        Settings::init();
        RestAPI::init();

        add_action( 'woocommerce_loaded', [ 'WebshoptigerCatalogSync\\DestinationGuard', 'init' ] );

        add_action( 'init', [ 'WebshoptigerCatalogSync\\BrandSync', 'maybe_register_taxonomy' ], 5 );

        if ( Settings::is_source_site() ) {
            Queue::init();
            add_action( 'init', function() {
                Scheduler::init();
                Scheduler::schedule();
            } );
        }

        if ( is_admin() ) {
            Admin\AdminPage::init();
            add_action( 'admin_notices', [ __CLASS__, 'maybe_show_disclaimer_notice' ] );
            add_action( 'wp_ajax_webshoptigercatalogsync_dismiss_disclaimer', [ __CLASS__, 'ajax_dismiss_disclaimer' ] );
            // Upgrade banner on every plugin admin page (Lite only)
            add_action( 'admin_notices', [ __CLASS__, 'maybe_show_upgrade_banner' ] );
        }
    }

    /**
     * Show an upgrade-to-Pro banner on every plugin admin page when the user
     * is on the Lite (free) version.
     */
    public static function maybe_show_upgrade_banner(): void {
        if ( Settings::is_pro() ) return;

        $page = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        if ( strpos( $page, 'webshoptigercatalogsync-sync' ) === false ) return;

        $upgrade_url = function_exists( 'webshoptigercatalogsync_fs' ) ? webshoptigercatalogsync_fs()->get_upgrade_url() : 'https://shop-sync.nl/pro';
        ?>
        <div class="notice wcs-upgrade-banner" style="border-left-color:#9d05ea;background:#faf5ff;padding:12px 16px;display:flex;align-items:center;gap:16px;flex-wrap:wrap;">
            <strong style="color:#9d05ea;font-size:14px;">⚡ Webshoptiger Catalog Sync Pro</strong>
            <span style="color:#444;">
                Unlock <strong>AI description rewriting</strong>, <strong>price adjustments per site</strong>,
                <strong>selective field sync</strong>, <strong>per-site schedules</strong>,
                <strong>statistics dashboard</strong> and <strong>email reports</strong>.
            </span>
            <a href="<?php echo esc_url( $upgrade_url ); ?>" target="_blank"
               style="background:#9d05ea;color:#fff;padding:6px 16px;border-radius:4px;text-decoration:none;font-weight:600;white-space:nowrap;">
                Upgrade to Pro &rarr;
            </a>
        </div>
        <?php
    }

    /**
     * Show a one-time disclaimer notice in the WordPress admin after activation.
     * Dismissed by the user via a close button; stored in user meta so each
     * admin user sees it once and can dismiss it independently.
     */
    public static function maybe_show_disclaimer_notice(): void {
        $user_id = get_current_user_id();
        if ( get_user_meta( $user_id, 'webshoptigercatalogsync_disclaimer_dismissed', true ) ) return;
        $nonce = wp_create_nonce( 'webshoptigercatalogsync_dismiss_disclaimer' );
        ?>
        <div class="notice notice-warning sc-sync-disclaimer" style="border-left-color:#9d05ea;padding:16px 16px 14px;">
            <h3 style="margin:0 0 8px;font-size:15px;">
                ⚠️ Webshoptiger Catalog Sync for WooCommerce — Important Notice
            </h3>
            <p style="margin:0 0 8px;">
                <strong>Webshoptiger B.V. is not liable for any bugs, errors, or damage caused by the use of this plugin.</strong>
                This includes, but is not limited to, incorrect product data, price errors, stock changes, or data loss
                on your source or destination WooCommerce stores.
            </p>
            <p style="margin:0 0 8px;">
                <strong>Before running any synchronisation, always make a complete backup of both your source site and every destination site</strong>
                (database + files). Test on a staging environment first. By using this plugin you accept the
                <a href="https://shop-sync.nl/terms" target="_blank">Terms of Service</a>.
            </p>
            <p style="margin:0;">
                <button type="button" class="button button-secondary"
                        onclick="(function(btn){
                            btn.disabled=true;
                            fetch(ajaxurl,{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},
                            body:'action=webshoptigercatalogsync_dismiss_disclaimer&nonce=<?php echo esc_js( $nonce ); ?>'})
                            .then(function(){btn.closest('.sc-sync-disclaimer').remove();});
                        })(this);">
                    I understand — do not show this again
                </button>
            </p>
        </div>
        <?php
    }

    public static function ajax_dismiss_disclaimer(): void {
        check_ajax_referer( 'webshoptigercatalogsync_dismiss_disclaimer', 'nonce' );
        update_user_meta( get_current_user_id(), 'webshoptigercatalogsync_disclaimer_dismissed', 1 );
        wp_send_json_success();
    }
}
