<?php

/**
 * Plugin Name: Kns Dynamic Discounts for WooCommerce
 * Plugin URI: https://knsapp.com/kns-dynamic-discounts/
 * Description: Advanced discount system with BOGO campaigns, quantity-based pricing, customer segmentation, and usage limits for WooCommerce.
 * Version:     1.0.0
 * Author:      KNS App
 * Author URI:  https://knsapp.com/
 * Text Domain: kns-dynamic-discounts-for-woocommerce
 * Domain Path: /includes/languages
 * Requires at least: 5.8
 * Requires PHP: 7.4
 * Requires Plugins: woocommerce
 * WC requires at least: 5.0
 * WC tested up to: 9.5
 * License:     GPL-2.0+
 * License URI: http://www.gnu.org/licenses/gpl-2.0.txt
 *
 * @package KNS_Dynamic_Discounts
 */
if (!defined('ABSPATH')) {
    exit;
    // Exit if accessed directly.
}

if (!defined('KNSDD_DISABLE_FS_PLUGIN_UPDATER')) {
    define('KNSDD_DISABLE_FS_PLUGIN_UPDATER', true);
}

// ========================================
// Freemius SDK Integration (upgrade/license recognition)
// ========================================
if (!function_exists('knsdd_fs')) {
    function knsdd_fs()
    {
        global $knsdd_fs;
        if (!isset($knsdd_fs)) {
            require_once dirname(__FILE__) . '/freemius/start.php';
            $knsdd_fs = fs_dynamic_init(array(
                'id' => '22171',
                'slug' => 'kns-dynamic-discounts-for-woocommerce',
                'premium_slug' => 'kns-dynamic-discounts-for-woocommerce-premium',
                'type' => 'plugin',
                'public_key' => 'pk_87e754526f94b95d4d49c9f7abbd2',
                'is_premium' => false,
                'premium_suffix' => 'Pro',
                'has_addons' => false,
                'has_paid_plans' => true,
                'is_org_compliant' => true,
                'menu' => array(
                    'slug' => 'knsdd-groups',
                    'first-path' => 'admin.php?page=knsdd-groups',
                    'account' => false,
                    'contact' => false,
                    'support' => false,
                ),
                'is_live' => true,
            ));
        }
        return $knsdd_fs;
    }

    knsdd_fs();
    do_action('knsdd_fs_loaded');
    knsdd_fs()->add_action('after_uninstall', 'knsdd_uninstall_cleanup');
}
/**
 * Cleanup function called on uninstall.
 * Deletes options, rules, and database tables.
 */
function knsdd_uninstall_cleanup()
{
    global $wpdb;
    // 1. Get groups before deleting options
    $groups = get_option('knsdd_groups', array());
    // 2. Delete the main options
    $options_to_delete = array(
        'knsdd_groups',
        'knsdd_group_dates',
        'knsdd_global_settings',
        'knsdd_group_flags',
        'knsdd_usage_tracker',
        'knsdd_db_version'
    );
    foreach ($options_to_delete as $option_name) {
        delete_option($option_name);
    }
    // 3. Delete the rules for each group
    if (!empty($groups) && is_array($groups)) {
        foreach ($groups as $group) {
            if (is_string($group) && !empty($group)) {
                delete_option('knsdd_rules_' . sanitize_key($group));
            }
        }
    }
    // 4. Drop the custom database table
    $table_name = $wpdb->prefix . 'knsdd_usage_log';
    $wpdb->query("DROP TABLE IF EXISTS {$table_name}");
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery
}

// ========================================
// Read version from plugin header to keep constant in sync
if (!defined('KNSDD_VERSION')) {
    if (function_exists('get_file_data')) {
        $data = get_file_data(__FILE__, array(
            'Version' => 'Version',
        ));
        $ver = (isset($data['Version']) && $data['Version'] ? $data['Version'] : '1.0.0');
        define('KNSDD_VERSION', $ver);
    } else {
        define('KNSDD_VERSION', '1.0.0');
    }
}
define('KNSDD_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('KNSDD_PLUGIN_URL', plugin_dir_url(__FILE__));
if (!defined('KNSDD_PRO_UPGRADE_URL')) {
    define('KNSDD_PRO_UPGRADE_URL', 'https://knsapp.com/kns-dynamic-discounts/');
}
register_uninstall_hook(__FILE__, 'knsdd_uninstall_cleanup');
final class KNS_Dynamic_Discounts
{
    private static $_instance = null;

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

    private function __construct()
    {
        $this->includes();
        $this->init_hooks();
        // HPOS uyumluluğu bildir
        add_action('before_woocommerce_init', function () {
            if (class_exists(\Automattic\WooCommerce\Utilities\FeaturesUtil::class)) {
                \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility('custom_order_tables', __FILE__, true);
            }
        });
    }

    private function includes()
    {
        require_once KNSDD_PLUGIN_DIR . 'includes/class-knsdd-data.php';
        require_once KNSDD_PLUGIN_DIR . 'includes/helpers/class-knsdd-database.php';
        require_once KNSDD_PLUGIN_DIR . 'includes/helpers/class-knsdd-discount-engine.php';
        require_once KNSDD_PLUGIN_DIR . 'includes/helpers/class-knsdd-utils.php';
        require_once KNSDD_PLUGIN_DIR . 'includes/helpers/class-knsdd-conflicts.php';
        require_once KNSDD_PLUGIN_DIR . 'includes/helpers/class-knsdd-rules-validator.php';
        require_once KNSDD_PLUGIN_DIR . 'includes/helpers/class-knsdd-validator-registry.php';
        require_once KNSDD_PLUGIN_DIR . 'includes/helpers/class-knsdd-alias.php';
        require_once KNSDD_PLUGIN_DIR . 'includes/helpers/class-knsdd-performance-optimizer.php';
        // License helper (ücretsiz sürüm limit ve yönlendirme için)
        require_once KNSDD_PLUGIN_DIR . 'includes/helpers/class-knsdd-license.php';
        require_once KNSDD_PLUGIN_DIR . 'includes/class-knsdd-i18n.php';
        require_once KNSDD_PLUGIN_DIR . 'includes/class-knsdd-vendor-i18n.php';
        // WP-CLI: Backfill ve diğer operasyonel komutlar
        if (defined('WP_CLI') && WP_CLI) {
            require_once KNSDD_PLUGIN_DIR . 'includes/cli/class-knsdd-cli.php';
        }
        if (is_admin()) {
            require_once KNSDD_PLUGIN_DIR . 'includes/admin/class-knsdd-admin-menu.php';
            require_once KNSDD_PLUGIN_DIR . 'includes/class-knsdd-ajax.php';
        }
        // Frontend'de de çalışması gereken promos AJAX handler'ı (cache-bypass için)
        require_once KNSDD_PLUGIN_DIR . 'includes/ajax/class-knsdd-ajax-promos.php';
        require_once KNSDD_PLUGIN_DIR . 'includes/class-knsdd-cart.php';
        require_once KNSDD_PLUGIN_DIR . 'includes/class-knsdd-frontend.php';
        require_once KNSDD_PLUGIN_DIR . 'includes/class-knsdd-tracker.php';
        require_once KNSDD_PLUGIN_DIR . 'includes/class-knsdd-campaigns.php';
        // Frontend modular classes (skeletons; logic will be moved gradually)
        require_once KNSDD_PLUGIN_DIR . 'includes/frontend/class-knsdd-frontend-assets.php';
        require_once KNSDD_PLUGIN_DIR . 'includes/frontend/renderers/class-knsdd-icon-renderer.php';
        require_once KNSDD_PLUGIN_DIR . 'includes/frontend/renderers/class-knsdd-message-renderer.php';
        require_once KNSDD_PLUGIN_DIR . 'includes/frontend/renderers/class-knsdd-tier-table-renderer.php';
        require_once KNSDD_PLUGIN_DIR . 'includes/frontend/services/class-knsdd-campaign-validator.php';
        require_once KNSDD_PLUGIN_DIR . 'includes/frontend/services/class-knsdd-smart-message-service.php';
        require_once KNSDD_PLUGIN_DIR . 'includes/frontend/services/class-knsdd-message-service.php';
        require_once KNSDD_PLUGIN_DIR . 'includes/frontend/services/class-knsdd-checkout-protection.php';
        require_once KNSDD_PLUGIN_DIR . 'includes/frontend/services/class-knsdd-tier-service.php';
        require_once KNSDD_PLUGIN_DIR . 'includes/frontend/presenters/class-knsdd-wc-notice-presenter.php';
        require_once KNSDD_PLUGIN_DIR . 'includes/frontend/presenters/class-knsdd-checkout-notices-controller.php';
        require_once KNSDD_PLUGIN_DIR . 'includes/frontend/presenters/class-knsdd-cart-presenter.php';
        require_once KNSDD_PLUGIN_DIR . 'includes/frontend/shortcodes/class-knsdd-shortcode-product-promo.php';
        // Frontend'de de kullanılacak Tiers AJAX handler'ı (cache-bypass için)
        require_once KNSDD_PLUGIN_DIR . 'includes/ajax/class-knsdd-ajax-tiers.php';
        // Notification system
        if (is_admin()) {
            require_once KNSDD_PLUGIN_DIR . 'includes/notifications/interface-notification-type.php';
            require_once KNSDD_PLUGIN_DIR . 'includes/notifications/class-knsdd-notifications.php';
            require_once KNSDD_PLUGIN_DIR . 'includes/notifications/class-knsdd-notification-renderer.php';
        }
    }

    private function init_hooks()
    {
        register_activation_hook(__FILE__, array('KNSDD_Database', 'activate'));
        register_deactivation_hook(__FILE__, array('KNSDD_Utils', 'deactivate'));
        // Database migration: order_total sütunu kontrolü
        add_action('admin_init', array('KNSDD_Database', 'maybe_add_order_total_column'));
        // Çok dilli yapı: yalnızca bu eklenti için textdomain locale'ini ayarla ve dil dosyalarını yükle
        KNSDD_I18n::init();
        // Initialize validator registry
        KNSDD_Validator_Registry::init();
        if (is_admin()) {
            new KNSDD_Admin_Menu();
            new KNSDD_Ajax();
        }
        new KNSDD_Cart();
        new KNSDD_Frontend();
        // Checkout koruması (idempotency + frontend guard)
        if (class_exists('KNSDD_Checkout_Protection')) {
            KNSDD_Checkout_Protection::init();
        }
        // Promos AJAX: frontend'de de hook'ları kaydet
        if (class_exists('KNSDD_Ajax_Promos')) {
            new KNSDD_Ajax_Promos();
        }
        // Tiers AJAX: frontend'de de hook'ları kaydet
        if (class_exists('KNSDD_Ajax_Tiers')) {
            new KNSDD_Ajax_Tiers();
        }
        new KNSDD_Tracker();
        // Initialize notification system
        if (is_admin() && class_exists('KNSDD_Notifications')) {
            KNSDD_Notifications::instance();
        }
        // Ensure DB schema exists even if activation didn't fire (e.g., manual upload)
        add_action('plugins_loaded', array($this, 'check_database_version'), 20);
    }

    /**
     * Check DB version and run installer if needed.
     * This check runs on plugins_loaded and ensures the database is up to date.
     */
    public function check_database_version()
    {
        $current_db_version = get_option('knsdd_db_version', '1.0.0');
        if (version_compare($current_db_version, KNSDD_VERSION, '<')) {
            // If the db version is older than the plugin version, run the installer.
            // The installer (activate) will update the db version option on success.
            KNSDD_Database::maybe_create_usage_log_table();
            KNSDD_Database::maybe_add_rule_type_column();
        }
    }

}

function knsdd_run_plugin()
{
    if (!class_exists('WooCommerce')) {
        add_action('admin_notices', function () {
            echo '<div class="error"><p><strong>Kns Dynamic Discounts:</strong> ' . esc_html__('Bu eklentinin çalışması için WooCommerce eklentisinin aktif olması gerekmektedir.', 'kns-dynamic-discounts-for-woocommerce') . '</p></div>';
        });
        return;
    }
    return KNS_Dynamic_Discounts::instance();
}

add_action('plugins_loaded', 'knsdd_run_plugin');
