<?php

// phpcs:ignore WordPress.Files.FileName.InvalidClassFileName
/**
 * Plugin Name:       Smart Product Sort
 * Description:       Advanced product sorting rules for WooCommerce — per-category, priority-based, toggle on/off instantly.
 * Version:           1.1.0
 * Author:            plgnplay
 * License:           GPL-2.0-or-later
 * License URI:       https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain:       smart-product-sort
 * Domain Path:       /languages
 * Requires at least: 6.5
 * Tested up to:      6.9
 * Requires PHP:      7.4
 * Requires Plugins:  woocommerce
 * WC requires at least: 7.1
 * WC tested up to:      10.5.3
 *
 * @package Smart_Product_Sort
 */
// phpcs:disable Universal.Files.SeparateFunctionsFromOO.Mixed -- Main plugin bootstrap file.
// phpcs:disable WordPress.Files.FileName.InvalidClassFileName -- Main plugin bootstrap file.
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
// Load Composer autoloader.
if ( file_exists( __DIR__ . '/vendor/autoload.php' ) ) {
    require_once __DIR__ . '/vendor/autoload.php';
}
/**
 * Freemius free/premium switching mechanism.
 * DO NOT REMOVE — essential for the function_exists check to work properly.
 */
if ( function_exists( 'spsort_fs' ) ) {
    spsort_fs()->set_basename( false, __FILE__ );
} else {
    if ( !function_exists( 'spsort_fs' ) ) {
        /**
         * Create a helper function for easy Freemius SDK access.
         *
         * @return Freemius
         */
        function spsort_fs() {
            global $spsort_fs;
            if ( !isset( $spsort_fs ) ) {
                $spsort_fs = fs_dynamic_init( array(
                    'id'               => '26961',
                    'slug'             => 'smart-product-sort',
                    'premium_slug'     => 'smart-product-sort-pro',
                    'type'             => 'plugin',
                    'public_key'       => 'pk_94dcf7d7f350dbeed55c39f0acd0f',
                    'is_premium'       => false,
                    'premium_suffix'   => '(Pro)',
                    'has_addons'       => false,
                    'has_paid_plans'   => true,
                    'is_org_compliant' => true,
                    'menu'             => array(
                        'slug'       => 'smart-product-sort',
                        'first-path' => 'admin.php?page=smart-product-sort',
                        'parent'     => array(
                            'slug' => 'woocommerce',
                        ),
                    ),
                    'is_live'          => true,
                ) );
            }
            return $spsort_fs;
        }

        // Init Freemius.
        spsort_fs();
        // Signal that SDK was initiated.
        do_action( 'spsort_fs_loaded' );
        /**
         * Freemius uninstall cleanup — runs after Freemius tracks the uninstall event.
         *
         * @return void
         */
        function spsort_fs_uninstall_cleanup() {
            global $wpdb;
            $table = $wpdb->prefix . 'spsort_sort_rules';
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange
            $wpdb->query( $wpdb->prepare( 'DROP TABLE IF EXISTS %i', $table ) );
            delete_option( 'spsort_version' );
        }

        spsort_fs()->add_action( 'after_uninstall', 'spsort_fs_uninstall_cleanup' );
    }
    // ── Plugin constants ──────────────────────────────────────────────────
    define( 'SPSORT_VERSION', '1.1.0' );
    define( 'SPSORT_PLUGIN_FILE', __FILE__ );
    define( 'SPSORT_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
    define( 'SPSORT_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
    define( 'SPSORT_PLUGIN_BASENAME', plugin_basename( __FILE__ ) );
    /**
     * Main plugin class — singleton.
     */
    final class Smart_Product_Sort {
        /**
         * Single instance.
         *
         * @var Smart_Product_Sort|null
         */
        private static $instance = null;

        /**
         * Get or create the single instance.
         *
         * @return Smart_Product_Sort
         */
        public static function instance() {
            if ( null === self::$instance ) {
                self::$instance = new self();
            }
            return self::$instance;
        }

        /**
         * Constructor — private to enforce singleton.
         */
        private function __construct() {
            $this->includes();
            $this->init_hooks();
        }

        /**
         * Load required files.
         *
         * @return void
         */
        private function includes() {
            require_once SPSORT_PLUGIN_DIR . 'includes/class-spsort-install.php';
            require_once SPSORT_PLUGIN_DIR . 'includes/class-spsort-sort-rules.php';
            require_once SPSORT_PLUGIN_DIR . 'includes/class-spsort-query.php';
            require_once SPSORT_PLUGIN_DIR . 'admin/class-spsort-admin.php';
            // Load Pro features if licensed.
            if ( file_exists( SPSORT_PLUGIN_DIR . 'pro/class-spsort-pro.php' ) ) {
                require_once SPSORT_PLUGIN_DIR . 'pro/class-spsort-pro.php';
            }
        }

        /**
         * Register hooks.
         *
         * @return void
         */
        private function init_hooks() {
            register_activation_hook( SPSORT_PLUGIN_FILE, array('SPSORT_Install', 'activate') );
            register_deactivation_hook( SPSORT_PLUGIN_FILE, array('SPSORT_Install', 'deactivate') );
            add_action( 'plugins_loaded', array($this, 'on_plugins_loaded') );
            add_action( 'before_woocommerce_init', array($this, 'declare_hpos_compatibility') );
        }

        /**
         * Run after all plugins are loaded — verify WooCommerce is active.
         *
         * @return void
         */
        public function on_plugins_loaded() {
            if ( !$this->is_woocommerce_active() ) {
                add_action( 'admin_notices', array($this, 'notice_woocommerce_missing') );
                return;
            }
            SPSORT_Query::instance();
            SPSORT_Admin::instance();
            // Initialize Pro features if available.
            if ( class_exists( 'SPSORT_Pro' ) ) {
                SPSORT_Pro::instance();
            }
        }

        /**
         * Declare compatibility with WooCommerce High-Performance Order Storage.
         *
         * @return void
         */
        public function declare_hpos_compatibility() {
            if ( class_exists( '\\Automattic\\WooCommerce\\Utilities\\FeaturesUtil' ) ) {
                \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'custom_order_tables', SPSORT_PLUGIN_FILE, true );
            }
        }

        /**
         * Check WooCommerce is active.
         *
         * @return bool
         */
        private function is_woocommerce_active() {
            return class_exists( 'WooCommerce' );
        }

        /**
         * Admin notice when WooCommerce is missing.
         *
         * @return void
         */
        public function notice_woocommerce_missing() {
            echo '<div class="notice notice-error"><p>';
            echo esc_html__( 'Smart Product Sort requires WooCommerce to be installed and active.', 'smart-product-sort' );
            echo '</p></div>';
        }

    }

    /**
     * Returns the main plugin instance.
     *
     * @return Smart_Product_Sort
     */
    function smart_product_sort() {
        return Smart_Product_Sort::instance();
    }

    // Kick off.
    smart_product_sort();
}