<?php
/**
 * Plugin Name: DZQCOD — Quick Order & COD Management for WooCommerce
 * Plugin URI:  https://dzqcod.nibra.cloud
 * Description: Complete COD e-commerce solution — quick order forms, call center, smart shipping, printing, campaigns, fraud detection, quantity pricing, offers, WhatsApp, SMS, Meta/TikTok CAPI. Built for MENA & African markets.
 * Version:     3.1.0
 * Author:      NIBRA Technology
 * Author URI:  https://nibra.cloud
 * License:     GPL-2.0-or-later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: dzqcod
 * Domain Path: /languages
 * Requires at least: 6.0
 * Requires PHP: 7.4
 * WC requires at least: 7.0
 * WC tested up to: 9.6
 */
defined('ABSPATH') || exit;
if (!function_exists('add_action')) { header('Status: 403 Forbidden'); exit; }

define('DZQCOD_VER', '3.1.0');
define('DZQCOD_FILE', __FILE__);
define('DZQCOD_PATH', plugin_dir_path(__FILE__));
define('DZQCOD_URL', plugin_dir_url(__FILE__));
define('DZQCOD_DB', 'dz_');

// Security: rate limit AJAX
add_action('init', function(){
    if (defined('DOING_AJAX') && DOING_AJAX && strpos($_REQUEST['action'] ?? '', 'dzqcod_') === 0) {
        $key = 'dzqcod_rl_' . md5(($_SERVER['REMOTE_ADDR'] ?? '') . gmdate('Y-m-d-H-i'));
        $c = (int)get_transient($key);
        if ($c > 60) { wp_send_json_error(['message' => 'Rate limit'], 429); exit; }
        set_transient($key, $c + 1, 120);
    }
});

// Security headers
add_action('admin_init', function(){
    if (isset($_GET['page']) && strpos($_GET['page'], 'dzqcod') !== false) {
        header('X-Content-Type-Options: nosniff');
        header('X-Frame-Options: SAMEORIGIN');
    }
});

// WooCommerce HPOS compatibility
add_action('before_woocommerce_init', function(){
    if (class_exists(\Automattic\WooCommerce\Utilities\FeaturesUtil::class)) {
        \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility('custom_order_tables', __FILE__);
        \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility('cart_checkout_blocks', __FILE__);
    }
});

// Bootstrap
add_action('plugins_loaded', function(){
    if (!class_exists('WooCommerce')) {
        add_action('admin_notices', function(){
            echo '<div class="notice notice-error"><p><strong>DZQCOD</strong> يحتاج WooCommerce. <a href="' . admin_url('plugin-install.php?s=woocommerce&tab=search') . '">تثبيت</a></p></div>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- safe static HTML
        });
        return;
    }
    require_once DZQCOD_PATH . 'includes/Core.php';
    require_once DZQCOD_PATH . 'includes/Modules.php';
    require_once DZQCOD_PATH . 'includes/TelegramBot.php';
    require_once DZQCOD_PATH . 'includes/ProductEnhanced.php';
    require_once DZQCOD_PATH . 'includes/CustomerAccount.php';
    \DZQCOD\Core::boot();
    new \DZQCOD\Modules();
    new \DZQCOD\ProductEnhanced();
    new \DZQCOD\CustomerAccount();
    foreach (['SalesBoost', 'SmartOps', 'CustomProducts', 'Integrations', 'Shipping'] as $mod) {
        $f = DZQCOD_PATH . "includes/{$mod}.php";
        if (file_exists($f)) {
            try {
                require_once $f;
                $cls = "\\DZQCOD\\{$mod}";
                if (class_exists($cls)) new $cls();
            } catch (\Throwable $e) {
                if ( defined( "WP_DEBUG" ) && WP_DEBUG ) { error_log("DZQCOD: {$mod} load error: " . $e->getMessage()); } // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log }
            }
        }
    }

    // ═══ LOAD DOWNLOADED ADDONS FROM addons/ DIRECTORY ═══
    $addons_dir = DZQCOD_PATH . 'addons/';
    if (is_dir($addons_dir)) {
        // Single PHP files: addons/slug.php
        foreach (glob($addons_dir . '*.php') as $af) {
            try { require_once $af; } catch (\Throwable $e) {
                if ( defined( "WP_DEBUG" ) && WP_DEBUG ) { error_log("DZQCOD Addon: " . basename($af) . " error: " . $e->getMessage()); } // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log }
            }
        }
        // Directory addons: addons/slug/slug.php or addons/slug/init.php
        foreach (glob($addons_dir . '*/') as $ad) {
            $slug = basename($ad);
            $entry = $ad . $slug . '.php';
            if (!file_exists($entry)) $entry = $ad . 'init.php';
            if (file_exists($entry)) {
                try { require_once $entry; } catch (\Throwable $e) {
                    if ( defined( "WP_DEBUG" ) && WP_DEBUG ) { error_log("DZQCOD Addon {$slug}: " . $e->getMessage()); } // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log }
                }
            }
        }
    }
    // Static module inits
    if (class_exists('\DZQCOD\SmartOps')) {
        \DZQCOD\SmartOps::workflows_init();
        \DZQCOD\SmartOps::multistore_init();
        \DZQCOD\SmartOps::instagram_init();
    }
});

register_activation_hook(__FILE__, function(){
    if (!current_user_can('activate_plugins')) return;
    require_once DZQCOD_PATH . 'includes/Installer.php';
    \DZQCOD\Installer::activate();
});

register_deactivation_hook(__FILE__, function(){
    if (!current_user_can('activate_plugins')) return;
    wp_clear_scheduled_hook('dzqcod_daily_cleanup');
    wp_clear_scheduled_hook('dzqcod_telemetry');
    wp_clear_scheduled_hook('dzqcod_license_check');
});
