<?php

defined("ABSPATH") || exit();

class Chit_Plugin
{
    private static $instance = null;

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

    private function __construct() {}

    public function init()
    {
        require_once CHIT_PATH . "includes/class-chit-codes.php";
        require_once CHIT_PATH . "includes/class-chit-batches.php";
        require_once CHIT_PATH . "includes/class-chit-import.php";
        Chit_Import::init();

        register_activation_hook(CHIT_FILE, function () {
            require_once CHIT_PATH . "includes/class-chit-activator.php";
            Chit_Activator::activate();
        });

        // Plugin updates don't re-fire the activation hook, so catch schema
        // changes on the next admin request.
        add_action("admin_init", function () {
            require_once CHIT_PATH . "includes/class-chit-activator.php";
            Chit_Activator::maybe_upgrade();
        });

        // Freemius owns uninstall.php (for its own telemetry/cleanup), so
        // plugin uninstall logic must register through Freemius's hook.
        if (function_exists("chit_fs")) {
            chit_fs()->add_action("after_uninstall", function () {
                require_once CHIT_PATH .
                    "includes/class-chit-uninstaller.php";
                Chit_Uninstaller::uninstall();
            });
        }

        add_action("before_woocommerce_init", [
            $this,
            "declare_wc_compatibility",
        ]);

        require_once CHIT_PATH . "includes/frontend/class-chit-redeem.php";
        new Chit_Redeem();

        if (is_admin()) {
            require_once CHIT_PATH . "includes/admin/class-chit-admin.php";
            new Chit_Admin();
        }
    }

    public function declare_wc_compatibility(): void
    {
        if (
            !class_exists(
                \Automattic\WooCommerce\Utilities\FeaturesUtil::class
            )
        ) {
            return;
        }
        \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility(
            "custom_order_tables",
            CHIT_FILE,
            true
        );
        \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility(
            "cart_checkout_blocks",
            CHIT_FILE,
            true
        );
    }
}
