<?php
/**
 * Plugin Name: ShopCentral - Advanced Multi Store Management & Store Analytics
 * Plugin URI: https://dominopress.com/plugin/shopcentral
 * Description: Ultimate WooCommerce Multi-Store Manager & Analytics suite. Centralize orders, products, and customers across sites from one dashboard. Includes background order import & sync with Action Scheduler, Customer Sync by Email, and Custom Meta & ACF Repeater Sync for connected child stores.
 * Version: 2.7.0
 * Author: Dominopress
 * Author URI: https://dominopress.com/
 * Text Domain: shopcentral
 * Requires at least: 6.8
 * Requires PHP: 7.4
 * License: GPLv2 or later
 * License URI: http://www.gnu.org/licenses/gpl-2.0.html
 */

defined('ABSPATH') || exit;

// Define constants
define('SHOPCENTRAL_VERSION', '2.7.0');
define('SHOPCENTRAL_PATH', plugin_dir_path(__FILE__));
define('SHOPCENTRAL_URL', plugin_dir_url(__FILE__));

// Include requirement files
require_once SHOPCENTRAL_PATH . 'includes/class-shopcentral-db.php';
require_once SHOPCENTRAL_PATH . 'includes/class-shopcentral-remote-api.php';
require_once SHOPCENTRAL_PATH . 'includes/class-shopcentral-settings-api.php';
require_once SHOPCENTRAL_PATH . 'includes/class-shopcentral-api.php';
require_once SHOPCENTRAL_PATH . 'includes/class-shopcentral-store-api.php';
require_once SHOPCENTRAL_PATH . 'includes/class-shopcentral-advanced-analytics.php';
require_once SHOPCENTRAL_PATH . 'includes/class-shopcentral-customer-intelligence.php';
require_once SHOPCENTRAL_PATH . 'includes/class-shopcentral-marketing-controller.php';
require_once SHOPCENTRAL_PATH . 'includes/class-shopcentral-automation-engine.php';
require_once SHOPCENTRAL_PATH . 'includes/class-shopcentral-notification-system.php';
require_once SHOPCENTRAL_PATH . 'includes/class-shopcentral-export-tools.php';
require_once SHOPCENTRAL_PATH . 'includes/class-shopcentral-event-tracker.php';
require_once SHOPCENTRAL_PATH . 'includes/class-shopcentral-deactivation-survey.php';
require_once SHOPCENTRAL_PATH . 'includes/class-shopcentral-product-sync.php';
require_once SHOPCENTRAL_PATH . 'includes/class-shopcentral-product-meta.php';
require_once SHOPCENTRAL_PATH . 'includes/class-shopcentral-logger.php';

// Global Product Editor
require_once SHOPCENTRAL_PATH . 'includes/ProductEditor/class-product-editor.php';
require_once SHOPCENTRAL_PATH . 'includes/ProductEditor/class-editor-queue.php';

// Smart Product Creator
require_once SHOPCENTRAL_PATH . 'includes/SmartProductCreator/class-smart-product-creator.php';


class ShopCentral_Plugin
{
    public function __construct()
    {
        // Activation hooks
        register_activation_hook(__FILE__, ['ShopCentral_DB', 'init']);
        register_activation_hook(__FILE__, [$this, 'plugin_activation_redirect']);
        register_activation_hook(__FILE__, function () {
            ShopCentral_Event_Tracker::track_install();
            ShopCentral_Event_Tracker::track_activation();
        });

        // Deactivation hook
        register_deactivation_hook(__FILE__, ['ShopCentral_Event_Tracker', 'track_deactivation']);

        // Initialize event tracker and deactivation survey
        ShopCentral_Event_Tracker::init();
        ShopCentral_Deactivation_Survey::init();

        // Also check tables on admin init
        add_action('admin_init', [$this, 'check_tables']);
        add_action('admin_init', [$this, 'handle_activation_redirect']);

        // Plugin action links
        add_filter('plugin_action_links_' . plugin_basename(__FILE__), [$this, 'add_plugin_action_links']);

        // Get feature settings
        $features = ShopCentral_Settings_API::get_feature_settings();

        // Initialize core API (always needed)
        new ShopCentral_API();
        new ShopCentral_Settings_API('shopcentral/v1');



        if (isset($features['store_manager']) && $features['store_manager']) {
            new ShopCentral_Store_API('shopcentral/v1');
            new ShopCentral_Advanced_Analytics('shopcentral/v1');
            new ShopCentral_Customer_Intelligence('shopcentral/v1');
            new ShopCentral_Marketing_Controller('shopcentral/v1');
            new ShopCentral_Automation_Engine('shopcentral/v1');
            new ShopCentral_Notification_System('shopcentral/v1');
            new ShopCentral_Export_Tools('shopcentral/v1');
            new ShopCentral_Product_Sync_Manager();
        }

        add_action('admin_menu', [$this, 'register_menu']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_scripts']);
        add_filter('submenu_file', [$this, 'filter_submenu_active_item'], 10, 2);



        // Nonce Refresh
        add_action('wp_ajax_shopcentral_get_nonce', [$this, 'ajax_get_nonce']);
        add_action('wp_ajax_nopriv_shopcentral_get_nonce', [$this, 'ajax_get_nonce']);

        // Auto-cleanup old logs (daily)
        add_action('shopcentral_cleanup_logs_cron', [$this, 'cleanup_old_logs']);
        if (!wp_next_scheduled('shopcentral_cleanup_logs_cron')) {
            wp_schedule_event(time(), 'daily', 'shopcentral_cleanup_logs_cron');
        }
    }

    public function cleanup_old_logs()
    {
        ShopCentral_Logger::delete_old_logs(30);
    }

    public function check_tables()
    {
        ShopCentral_DB::init();
    }

    public function plugin_activation_redirect()
    {
        // Set a transient to trigger redirect after activation
        set_transient('shopcentral_activation_redirect', true, 30);
    }

    public function handle_activation_redirect()
    {
        // Check if we should redirect
        if (get_transient('shopcentral_activation_redirect')) {
            delete_transient('shopcentral_activation_redirect');

            // Only redirect if not doing bulk activation
            if (!isset($_GET['activate-multi'])) {
                wp_safe_redirect(admin_url('admin.php?page=shopcentral'));
                exit;
            }
        }
    }

    public function add_plugin_action_links($links)
    {
        $manage_link = '<a href="' . admin_url('admin.php?page=shopcentral') . '">' . __('Manage Stores', 'shopcentral') . '</a>';
        array_unshift($links, $manage_link);
        return $links;
    }

    public function register_menu()
    {
        // Main Menu
        add_menu_page(
            'ShopCentral',
            'ShopCentral',
            'manage_options',
            'shopcentral',
            [$this, 'render_admin_page'],
            'dashicons-store',
            6
        );

        add_submenu_page(
            'shopcentral',
            'Dashboard',
            'Dashboard',
            'manage_options',
            'shopcentral',
            [$this, 'render_admin_page']
        );

        add_submenu_page(
            'shopcentral',
            __('Stores', 'shopcentral'),
            __('Stores', 'shopcentral'),
            'manage_options',
            'shopcentral&route=/store-manager/stores',
            [$this, 'render_admin_page']
        );

        add_submenu_page(
            'shopcentral',
            __('Products', 'shopcentral'),
            __('Products', 'shopcentral'),
            'manage_options',
            'shopcentral&route=/store-manager/products',
            [$this, 'render_admin_page']
        );

        add_submenu_page(
            'shopcentral',
            __('Orders', 'shopcentral'),
            __('Orders', 'shopcentral'),
            'manage_options',
            'shopcentral&route=/store-manager/orders',
            [$this, 'render_admin_page']
        );

        add_submenu_page(
            'shopcentral',
            __('Discounts', 'shopcentral'),
            __('Discounts', 'shopcentral'),
            'manage_options',
            'shopcentral&route=/store-manager/coupons',
            [$this, 'render_admin_page']
        );

        add_submenu_page(
            'shopcentral',
            __('Customers', 'shopcentral'),
            __('Customers', 'shopcentral'),
            'manage_options',
            'shopcentral&route=/store-manager/customers',
            [$this, 'render_admin_page']
        );

        add_submenu_page(
            'shopcentral',
            __('Global Coupon', 'shopcentral'),
            __('Global Coupon', 'shopcentral'),
            'manage_options',
            'shopcentral&route=/store-manager/marketing/global-coupon',
            [$this, 'render_admin_page']
        );

        add_submenu_page(
            'shopcentral',
            __('Customer Insight', 'shopcentral'),
            __('Customer Insight', 'shopcentral'),
            'manage_options',
            'shopcentral&route=/store-manager/customer-intelligence',
            [$this, 'render_admin_page']
        );

        add_submenu_page(
            'shopcentral',
            __('Automation', 'shopcentral'),
            __('Automation', 'shopcentral'),
            'manage_options',
            'shopcentral&route=/store-manager/automation',
            [$this, 'render_admin_page']
        );

        add_submenu_page(
            'shopcentral',
            __('Store Analytics', 'shopcentral'),
            __('Store Analytics', 'shopcentral'),
            'manage_options',
            'shopcentral&route=/store-manager/analytics/advanced',
            [$this, 'render_admin_page']
        );

        add_submenu_page(
            'shopcentral',
            __('Product Analytics', 'shopcentral'),
            __('Product Analytics', 'shopcentral'),
            'manage_options',
            'shopcentral&route=/store-manager/analytics/products',
            [$this, 'render_admin_page']
        );

        add_submenu_page(
            'shopcentral',
            __('Export Tools', 'shopcentral'),
            __('Export Tools', 'shopcentral'),
            'manage_options',
            'shopcentral&route=/store-manager/export',
            [$this, 'render_admin_page']
        );

        add_submenu_page(
            'shopcentral',
            __('Global Product Editor', 'shopcentral'),
            __('Product Editor', 'shopcentral'),
            'manage_options',
            'shopcentral&route=/store-manager/product-editor',
            [$this, 'render_admin_page']
        );

        add_submenu_page(
            'shopcentral',
            __('ShopCentral Logs', 'shopcentral'),
            __('ShopCentral Logs', 'shopcentral'),
            'manage_options',
            'shopcentral&route=/store-manager/logs',
            [$this, 'render_admin_page']
        );

    }

    public function enqueue_scripts($hook)
    {
        $page = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';

        if ( empty( $page ) || strpos( $page, 'shopcentral' ) !== 0 ) {
            return;
        }

        $script_path = SHOPCENTRAL_PATH . 'assets/admin.js';
        $script_url = SHOPCENTRAL_URL . 'assets/admin.js';
        $vendors_path = SHOPCENTRAL_PATH . 'assets/vendors.js';
        $vendors_url = SHOPCENTRAL_URL . 'assets/vendors.js';

        if (file_exists($vendors_path)) {
            wp_enqueue_script(
                'shopcentral-vendors',
                $vendors_url,
                [],
                filemtime($vendors_path),
                true
            );
        }

        if (file_exists($script_path)) {
            global $wpdb;
            wp_enqueue_script(
                'shopcentral-admin',
                $script_url,
                ['shopcentral-vendors', 'wp-element'],
                filemtime($script_path),
                true
            );

            $currentPage = 'store-manager';
            $store_api = new ShopCentral_Store_API('shopcentral/v1');

            wp_localize_script('shopcentral-admin', 'shopCentralData', [
                'rootUrl' => home_url(),
                'apiUrl' => rest_url('shopcentral/v1/'),
                'nonce' => wp_create_nonce('wp_rest'),
                'currentPage' => $currentPage,
                'isPro' => function_exists('shopcentral_pro_fs') && shopcentral_pro_fs()->can_use_premium_code(),
                'storeLimit' => $store_api->get_store_limit(),
                'currentStoreCount' => $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}shopcentral_stores")
            ]);

            // Hide standard WordPress footer and notices on all ShopCentral pages to maintain a clean layout
            echo '<style>
                #wpfooter { display: none !important; }
                #wpbody-content { padding-bottom: 0 !important; }
                .update-nag, .notice, .error, .updated, .is-dismissible { display: none !important; }
                #wpbody-content > *:not(#shopcentral-root) {
                    display: none !important;
                }
            </style>';
        }
    }

    public function render_admin_page()
    {
        echo '<div id="shopcentral-root"></div>';
    }

    public function ajax_get_nonce()
    {
        wp_send_json_success(['nonce' => wp_create_nonce('wp_rest')]);
    }

    public function filter_submenu_active_item($submenu_file, $parent_file)
    {
        if ($parent_file === 'shopcentral') {
            $route = isset($_GET['route']) ? sanitize_text_field(wp_unslash($_GET['route'])) : '';
            if ($route) {
                return 'shopcentral&route=' . $route;
            }
        }
        return $submenu_file;
    }


}

new ShopCentral_Plugin();
