<?php
/**
 * Plugin Name: FlowDino
 * Plugin URI: https://www.flowdino.com
 * Description: Automatically synchronize your WooCommerce catalog with the FlowDino platform for centralized product management.
 * Version: 1.1.17
 * Author: Jeremy DUMONT
 * License: GPL v2 or later
 * Text Domain: flowdino
 * Domain Path: /languages
 * Requires at least: 5.0
 * Tested up to: 6.9
 * WC requires at least: 4.0
 * WC tested up to: 8.5
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

// Define plugin constants
if (!defined('FLOWDINO_PLUGIN_URL')) {
    define('FLOWDINO_PLUGIN_URL', plugin_dir_url(__FILE__));
}
if (!defined('FLOWDINO_PLUGIN_PATH')) {
    define('FLOWDINO_PLUGIN_PATH', plugin_dir_path(__FILE__));
}
if (!defined('FLOWDINO_VERSION')) {
    define('FLOWDINO_VERSION', '1.1.16');
}

// Declare compatibility with WooCommerce High Performance Order Storage (HPOS).
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);
    }
});

/**
 * Check if WooCommerce is active and show admin notice if not
 */
function flowdino_check_woocommerce() {
    if (!class_exists('WooCommerce')) {
        add_action('admin_notices', 'flowdino_woocommerce_missing_notice');
        return false;
    }
    return true;
}

/**
 * Admin notice for missing WooCommerce
 */
function flowdino_woocommerce_missing_notice() {
    ?>
    <div class="notice notice-error">
        <p><?php esc_html_e('FlowDino requires WooCommerce to be installed and active.', 'flowdino'); ?></p>
    </div>
    <?php
}

/**
 * Main FlowDino class
 */
class FlowDino {
    
    /**
     * Single instance of the class
     */
    private static $instance = null;
    
    /**
     * API handler instance
     */
    public $api;
    
    /**
     * Admin handler instance
     */
    public $admin;
    
    /**
     * Get single instance
     */
    public static function get_instance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    /**
     * Constructor
     */
    private function __construct() {
        add_action('init', array($this, 'init'));
    }
    
    /**
     * Initialize the plugin
     */
    public function init() {
        // Check if WooCommerce is available
        if (!flowdino_check_woocommerce()) {
            return;
        }
        
        // Load plugin text domain
        $this->load_textdomain();
        
        // Include required files
        $this->includes();
        
        // Initialize classes
        $this->init_classes();
        
        // Initialize hooks
        $this->init_hooks();
    }
    
    /**
     * Initialize classes
     */
    private function init_classes() {
        if (class_exists('FlowDino_WC_API')) {
            $this->api = new FlowDino_WC_API();
        }
        
        if (class_exists('FlowDino_WC_Admin')) {
            $this->admin = new FlowDino_WC_Admin();
        }
    }
    
    /**
     * Initialize hooks
     */
    private function init_hooks() {
        if (!$this->api || !$this->admin) {
            return;
        }

        // Product hooks
        add_action('woocommerce_update_product', array($this, 'on_product_update'));
        add_action('woocommerce_new_product', array($this, 'on_product_create'));
        add_action('woocommerce_delete_product', array($this, 'on_product_delete'));
        // Variation saved from admin edit screen (stock, status, price, etc.)
        // woocommerce_update_product_variation : fires from WC_Data::save() for variation objects
        add_action('woocommerce_update_product_variation', array($this, 'on_variation_update'));
        // woocommerce_save_product_variation : fires from the WooCommerce AJAX handler when
        // the user clicks "Enregistrer les modifications" on the product edit screen
        add_action('woocommerce_save_product_variation', array($this, 'on_variation_update'), 10, 1);

        // Stock auto-sync for already-synced products
        // woocommerce_product_set_stock_status : changement de statut (instock / outofstock)
        add_action('woocommerce_product_set_stock_status', array($this, 'on_stock_update'), 10, 3);
        // woocommerce_product_set_stock : changement de quantité
        add_action('woocommerce_product_set_stock', array($this, 'on_stock_quantity_update'));
        // Variation-specific hooks
        add_action('woocommerce_variation_set_stock_status', array($this, 'on_variation_stock_status_update'), 10, 3);
        add_action('woocommerce_variation_set_stock',        array($this, 'on_variation_stock_quantity_update'));
        
        // Admin hooks
        add_action('admin_menu', array($this->admin, 'add_admin_menu'));
        add_action('admin_enqueue_scripts', array($this->admin, 'enqueue_scripts'), 20);
        add_action('admin_enqueue_scripts', array($this, 'enqueue_label_scripts'), 20);

        // FlowDino shipping label on WC order admin page
        add_action('add_meta_boxes', array($this, 'add_shipping_label_meta_box'));

        // AJAX hooks
        add_action('wp_ajax_flowdino_sync_product', array($this, 'ajax_sync_product'));
        add_action('wp_ajax_flowdino_test_connection', array($this, 'ajax_test_connection'));
        add_action('wp_ajax_flowdino_proxy_label', array($this, 'ajax_proxy_label'));
    }

    /**
     * Enqueue pdf.js and pdf-utils.js on WC order edit screens.
     */
    public function enqueue_label_scripts($hook) {
        // Load on WC order screens: HPOS single or list, legacy shop_order CPT
        $screen = get_current_screen();
        if (!$screen) {
            return;
        }

        $is_order_screen = (
            $screen->id === 'shop_order'
            || $screen->id === 'woocommerce_page_wc-orders'
            || (isset($screen->post_type) && $screen->post_type === 'shop_order')
        );

        if (!$is_order_screen) {
            return;
        }

        wp_enqueue_script(
            'pdfjs-lib',
            FLOWDINO_PLUGIN_URL . 'assets/pdf.min.js',
            array(),
            '3.11.174',
            true
        );
        wp_enqueue_script(
            'flowdino-pdf-utils',
            FLOWDINO_PLUGIN_URL . 'assets/pdf-utils.js',
            array('pdfjs-lib'),
            FLOWDINO_VERSION,
            true
        );
        // Pass the worker URL to JS — no other data needed, all passed via data-* attributes
        wp_localize_script('flowdino-pdf-utils', 'flowdinoPdf', array(
            'workerSrc' => FLOWDINO_PLUGIN_URL . 'assets/pdf.worker.min.js',
        ));

        // Mark scripts so all major caching/minification plugins skip them.
        add_filter('autoptimize_filter_js_exclude',   array($this, 'exclude_pdf_scripts_from_autoptimize'));
        add_filter('rocket_exclude_js',               array($this, 'exclude_pdf_scripts_from_rocket'));
        add_filter('litespeed_optimize_js_excludes',  array($this, 'exclude_pdf_scripts_from_litespeed'));
        add_filter('w3tc_minify_js_do_tag_minification', array($this, 'exclude_pdf_scripts_from_w3tc'), 10, 3);
        // Add data-no-optimize attribute recognised by LiteSpeed Cache & W3 Total Cache
        add_filter('script_loader_tag', array($this, 'add_no_optimize_attr'), 10, 3);
    }

    /** Exclude pdf-utils and pdf.js from Autoptimize inlining/concatenation. */
    public function exclude_pdf_scripts_from_autoptimize($exclude) {
        return $exclude . ', assets/pdf-utils.js, assets/pdf.min.js, assets/pdf.worker.min.js';
    }

    /** Exclude pdf-utils and pdf.js from WP Rocket concatenation. */
    public function exclude_pdf_scripts_from_rocket($excluded) {
        $plugin_base = str_replace(WP_CONTENT_DIR, '', FLOWDINO_PLUGIN_PATH);
        $excluded[]  = $plugin_base . 'assets/pdf-utils.js';
        $excluded[]  = $plugin_base . 'assets/pdf.min.js';
        $excluded[]  = $plugin_base . 'assets/pdf.worker.min.js';
        return $excluded;
    }

    /** Exclude pdf-utils and pdf.js from LiteSpeed Cache JS optimisation. */
    public function exclude_pdf_scripts_from_litespeed($excludes) {
        $excludes[] = 'assets/pdf-utils.js';
        $excludes[] = 'assets/pdf.min.js';
        $excludes[] = 'assets/pdf.worker.min.js';
        return $excludes;
    }

    /** Exclude pdf-utils and pdf.js from W3 Total Cache minification. */
    public function exclude_pdf_scripts_from_w3tc($do_minify, $tag, $handle) {
        $handles = array('pdfjs-lib', 'flowdino-pdf-utils');
        if (in_array($handle, $handles, true)) {
            return false;
        }
        return $do_minify;
    }

    /**
     * Add data-no-optimize="1" and data-cfasync="false" to these script tags.
     * Recognised by LiteSpeed Cache, W3 Total Cache, Cloudflare Rocket Loader, etc.
     */
    public function add_no_optimize_attr($tag, $handle, $src) {
        $handles = array('pdfjs-lib', 'flowdino-pdf-utils');
        if (in_array($handle, $handles, true)) {
            $tag = str_replace(' src=', ' data-no-optimize="1" data-cfasync="false" src=', $tag);
        }
        return $tag;
    }

    /**
     * AJAX proxy: fetch the shipping label PDF and return it as a base64 data-URI.
     * Needed to work around cross-origin restrictions in the browser.
     */
    public function ajax_proxy_label() {
        check_ajax_referer('flowdino_proxy_label', 'nonce');

        if (!current_user_can('manage_woocommerce')) {
            wp_send_json_error('Unauthorized', 403);
        }

        $raw_url = isset($_GET['url']) ? esc_url_raw(wp_unslash($_GET['url'])) : '';
        if (empty($raw_url)) {
            wp_send_json_error('Missing url parameter', 400);
        }

        // Only allow http/https
        $scheme = wp_parse_url($raw_url, PHP_URL_SCHEME);
        if (!in_array($scheme, array('http', 'https'), true)) {
            wp_send_json_error('Invalid URL scheme', 400);
        }

        $response = wp_remote_get($raw_url, array(
            'timeout'   => 30,
            'sslverify' => true,
        ));

        if (is_wp_error($response)) {
            wp_send_json_error($response->get_error_message(), 502);
        }

        $code = wp_remote_retrieve_response_code($response);
        if ($code !== 200) {
            wp_send_json_error('Remote returned HTTP ' . $code, 502);
        }

        $body = wp_remote_retrieve_body($response);
        $mime = wp_remote_retrieve_header($response, 'content-type') ?: 'application/pdf';
        // Strip charset suffix if present
        $mime = strtok($mime, ';');

        wp_send_json_success('data:' . $mime . ';base64,' . base64_encode($body)); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- intentional base64 encoding for data URI
    }

    /**
     * Register the FlowDino shipping label meta box on the WC order edit screen.
     */
    public function add_shipping_label_meta_box() {
        // Support both legacy (shop_order) and HPOS (woocommerce_page_wc-orders) screens
        $screens = array('shop_order', 'woocommerce_page_wc-orders');
        foreach ($screens as $screen) {
            add_meta_box(
                'flowdino_shipping_label',
                __('FlowDino — Bordereau d\'expédition', 'flowdino'),
                array($this, 'render_shipping_label_meta_box'),
                $screen,
                'side',
                'high'
            );
        }
    }

    /**
     * Render the FlowDino shipping label meta box content.
     *
     * @param WP_Post|WC_Order $post_or_order
     */
    public function render_shipping_label_meta_box($post_or_order) {
        $order = ($post_or_order instanceof WC_Order)
            ? $post_or_order
            : wc_get_order($post_or_order->ID);

        if (!$order) {
            return;
        }

        $label_url = $order->get_meta('_flowdino_shipping_label_url', true);

        if (empty($label_url)) {
            echo '<p>' . esc_html__('Aucun bordereau disponible pour cette commande.', 'flowdino') . '</p>';
            return;
        }

        // Build a safe product title for the thermal caption
        $title = '';
        foreach ($order->get_items() as $item) {
            $title = $item->get_name();
            break;
        }

        $ajax_url = admin_url('admin-ajax.php');
        $nonce    = wp_create_nonce('flowdino_proxy_label');
        ?>
        <div style="display:flex;flex-direction:column;gap:8px;">
            <button type="button" class="button button-primary flowdino-print-original"
                data-url="<?php echo esc_attr(esc_url_raw($label_url)); ?>"
                data-ajax="<?php echo esc_attr($ajax_url); ?>"
                data-nonce="<?php echo esc_attr($nonce); ?>">
                <span class="dashicons dashicons-printer" style="vertical-align:middle;margin-right:4px;"></span>
                <?php esc_html_e('Imprimer l\'original', 'flowdino'); ?>
            </button>
            <button type="button" class="button flowdino-print-thermal"
                data-url="<?php echo esc_attr(esc_url_raw($label_url)); ?>"
                data-ajax="<?php echo esc_attr($ajax_url); ?>"
                data-nonce="<?php echo esc_attr($nonce); ?>"
                data-title="<?php echo esc_attr($title); ?>">
                <span class="dashicons dashicons-media-document" style="vertical-align:middle;margin-right:4px;"></span>
                <?php esc_html_e('Imprimer thermique', 'flowdino'); ?>
            </button>
        </div>
        <?php
    }

    /**
     * Include required files
     */
    private function includes() {
        $includes = array(
            'includes/class-flowdino-wc-database.php',
            'includes/class-flowdino-wc-api.php',
            'includes/class-flowdino-wc-admin.php',
            'includes/class-flowdino-wc-sync.php'
        );
        
        foreach ($includes as $file) {
            $file_path = FLOWDINO_PLUGIN_PATH . $file;
            if (file_exists($file_path)) {
                require_once $file_path;
            }
        }
    }
    
    /**
     * Load plugin text domain
     */
    public function load_textdomain() {
        // Définir le répertoire des langues
        $languages_path = dirname(plugin_basename(__FILE__)) . '/languages';
        
        // Depuis WordPress 4.6, les traductions sont chargées automatiquement
        // pour les plugins hébergés sur WordPress.org. Cependant, pour les 
        // installations locales ou les versions de développement, nous devons
        // charger manuellement les traductions.
        
        $locale = get_locale();
        
        // Vérifier si le fichier .mo existe pour la locale courante
        $mo_file = FLOWDINO_PLUGIN_PATH . 'languages/flowdino-' . $locale . '.mo';
        
        // Si le fichier .mo n'existe pas pour la locale courante, essayer le français
        if (!file_exists($mo_file) && $locale !== 'fr_FR') {
            $mo_file = FLOWDINO_PLUGIN_PATH . 'languages/flowdino-fr_FR.mo';
            $locale = 'fr_FR';
        }
        
        // Vérifier si le fichier .mo existe, sinon essayer de le générer
        if (!file_exists($mo_file)) {
            $po_file = FLOWDINO_PLUGIN_PATH . 'languages/flowdino-' . $locale . '.po';
            if (file_exists($po_file)) {
                $this->generate_mo_from_po($po_file, $mo_file);
            }
        }
        
        // Charger le fichier de traduction manuellement si il existe
        if (file_exists($mo_file)) {
            load_textdomain('flowdino', $mo_file);
        }
    }
    
    /**
     * Générer un fichier .mo à partir d'un fichier .po
     */
    private function generate_mo_from_po($po_file, $mo_file) {
        if (!file_exists($po_file)) {
            return false;
        }
        
        include_once FLOWDINO_PLUGIN_PATH . 'languages/generate-mo.php';
        
        // Utiliser la fonction generate-mo.php si elle existe
        if (function_exists('flowdino_generate_mo_file')) {
            return flowdino_generate_mo_file($po_file, $mo_file);
        }
        
        return false;
    }
    
    /**
     *
     * Two behaviours :
     *  1. If flowdino_auto_sync is enabled  → full sync regardless of previous state.
     *  2. If the product was already synced → stock-only update (no full re-sync needed).
     */
    public function on_product_update($product_id) {
        if (!class_exists('FlowDino_WC_Sync') || !class_exists('FlowDino_WC_Database')) {
            return;
        }

        // If WooCommerce fires this hook for a variation, delegate to the variation handler.
        if (get_post_type($product_id) === 'product_variation') {
            $this->maybe_sync_variation($product_id);
            return;
        }

        // Case 1 – global auto-sync is ON: push everything.
        if (get_option('flowdino_auto_sync', false)) {
            $sync = new FlowDino_WC_Sync();
            $sync->sync_product($product_id);
            return;
        }

        // Case 2 – product was manually synced by the user via the FlowDino products tab.
        // The products tab sets post meta; the DB table may or may not have an entry.
        $post_meta_status = get_post_meta($product_id, '_flowdino_sync_status', true);
        if ($post_meta_status === 'synced') {
            $sync = new FlowDino_WC_Sync();
            $sync->sync_product($product_id);
            return;
        }

        // Case 3 – fallback: check the DB table (used by the legacy sync path).
        $db       = new FlowDino_WC_Database();
        $sync_row = $db->get_product_sync_status($product_id);

        if ($sync_row && $sync_row->sync_status === 'synced') {
            $sync = new FlowDino_WC_Sync();
            $sync->update_stock($product_id);
        } elseif ($sync_row && $sync_row->sync_status === 'error') {
            $sync = new FlowDino_WC_Sync();
            $sync->sync_product($product_id);
        }
    }
    
    /**
     * Handle product creation
     */
    public function on_product_create($product_id) {
        if (get_option('flowdino_auto_sync', false) && class_exists('FlowDino_WC_Sync')) {
            $sync = new FlowDino_WC_Sync();
            $sync->sync_product($product_id);
        }
    }
    
    /**
     * Handle product deletion
     */
    public function on_product_delete($product_id) {
        if (get_option('flowdino_auto_sync', false) && class_exists('FlowDino_WC_Sync')) {
            $sync = new FlowDino_WC_Sync();
            $sync->delete_product($product_id);
        }
    }
    
    /**
     * Handle variation saved from WooCommerce admin edit screen.
     * Triggered by "Enregistrer les modifications" on the product edit page.
     *
     * @param int $variation_id Variation post ID.
     */
    public function on_variation_update($variation_id) {
        $this->maybe_sync_variation($variation_id);
    }

    /**
     * Handle stock status change (instock / outofstock) for simple / parent products.
     *
     * @param int    $product_id  WooCommerce product ID.
     * @param string $status      New stock status.
     * @param object $product     WC_Product instance.
     */
    public function on_stock_update($product_id, $status = '', $product = null) {
        if (!class_exists('FlowDino_WC_Database') || !class_exists('FlowDino_WC_Sync')) {
            return;
        }

        // If this is a variation, delegate to the variation handler
        if (get_post_type($product_id) === 'product_variation') {
            $this->maybe_sync_variation($product_id);
            return;
        }

        $db       = new FlowDino_WC_Database();
        $sync_row = $db->get_product_sync_status($product_id);
        $sync     = new FlowDino_WC_Sync();
        if ($sync_row && $sync_row->sync_status === 'synced') {
            $sync->update_stock($product_id);
        } elseif ($sync_row && $sync_row->sync_status === 'error') {
            $sync->sync_product($product_id);
        }
    }

    /**
     * Handle stock quantity change for simple / parent products.
     *
     * @param WC_Product $product WooCommerce product object.
     */
    public function on_stock_quantity_update($product) {
        if (!$product || !class_exists('FlowDino_WC_Database') || !class_exists('FlowDino_WC_Sync')) {
            return;
        }
        $product_id = $product->get_id();

        if (get_post_type($product_id) === 'product_variation') {
            $this->maybe_sync_variation($product_id);
            return;
        }

        $db       = new FlowDino_WC_Database();
        $sync_row = $db->get_product_sync_status($product_id);
        $sync     = new FlowDino_WC_Sync();
        if ($sync_row && $sync_row->sync_status === 'synced') {
            $sync->update_stock($product_id);
        } elseif ($sync_row && $sync_row->sync_status === 'error') {
            $sync->sync_product($product_id);
        }
    }

    /**
     * Handle stock STATUS change specifically for product variations.
     *
     * @param int    $variation_id  Variation post ID.
     * @param string $status        New stock status.
     * @param object $variation     WC_Product_Variation instance.
     */
    public function on_variation_stock_status_update($variation_id, $status = '', $variation = null) {
        $this->maybe_sync_variation($variation_id);
    }

    /**
     * Handle stock QUANTITY change specifically for product variations.
     *
     * @param WC_Product_Variation $variation Variation object.
     */
    public function on_variation_stock_quantity_update($variation) {
        if (!$variation) {
            return;
        }
        $this->maybe_sync_variation($variation->get_id());
    }

    /**
     * Sync a variation to FlowDino if it has already been manually synced.
     * Checks the variation's own sync status first, then falls back to the parent's status.
     *
     * @param int $variation_id Variation post ID.
     */
    private function maybe_sync_variation($variation_id) {
        if (!class_exists('FlowDino_WC_Sync')) {
            return;
        }

        // Primary check: variation itself was previously synced.
        $sync_status = get_post_meta($variation_id, '_flowdino_sync_status', true);
        if ($sync_status === 'synced') {
            $sync = new FlowDino_WC_Sync();
            $sync->sync_variation($variation_id);
            return;
        }

        // Fallback: if the PARENT product was synced, sync this variation too.
        // This covers the case where the user synced the parent article (not individual variations).
        $variation = wc_get_product($variation_id);
        if (!$variation) {
            return;
        }
        $parent_id = $variation->get_parent_id();
        if ($parent_id) {
            $parent_meta_status = get_post_meta($parent_id, '_flowdino_sync_status', true);
            if ($parent_meta_status === 'synced') {
                $sync = new FlowDino_WC_Sync();
                $sync->sync_variation($variation_id);
            }
        }
    }

    /**
     * AJAX handler for product sync
     */
    public function ajax_sync_product() {
        check_ajax_referer('flowdino_sync_nonce', 'nonce');
        
        if (!current_user_can('manage_woocommerce')) {
            wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'flowdino'));
        }
        
        // Validate and sanitize product_id parameter
        if (!isset($_POST['product_id']) || empty($_POST['product_id'])) {
            wp_send_json_error('Product ID is required');
        }
        
        $product_id = intval($_POST['product_id']);
        if ($product_id <= 0) {
            wp_send_json_error('Invalid product ID');
        }
        if (class_exists('FlowDino_WC_Sync')) {
            $sync = new FlowDino_WC_Sync();
            $result = $sync->sync_product($product_id);
        } else {
            $result = array('success' => false, 'message' => 'Sync class not available');
        }
        
        wp_send_json($result);
    }
    
    /**
     * AJAX handler for connection test
     */
    public function ajax_test_connection() {
        check_ajax_referer('flowdino_test_nonce', 'nonce');
        
        if (!current_user_can('manage_woocommerce')) {
            wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'flowdino'));
        }
        
        if ($this->api) {
            $result = $this->api->test_connection();
        } else {
            $result = array('success' => false, 'message' => 'API class not available');
        }
        
        wp_send_json($result);
    }
}

/**
 * Plugin activation hook
 */
function flowdino_activate() {
    // Check if WooCommerce is active
    if (!class_exists('WooCommerce')) {
        deactivate_plugins(plugin_basename(__FILE__));
        wp_die(esc_html__('FlowDino requires WooCommerce to be installed and active.', 'flowdino'));
    }
    
    // Include database class
    $database_file = FLOWDINO_PLUGIN_PATH . 'includes/class-flowdino-wc-database.php';
    if (file_exists($database_file)) {
        require_once $database_file;
        
        if (class_exists('FlowDino_WC_Database')) {
            $database = new FlowDino_WC_Database();
            $database->create_tables();
        }
    }
    
    // Set default options
    add_option('flowdino_api_url', 'https://www.flowdino.com');
    add_option('flowdino_auto_sync', false);
    add_option('flowdino_default_color', 1);
    add_option('flowdino_default_brand', 64);
}

/**
 * Plugin deactivation hook
 */
function flowdino_deactivate() {
    // Clear scheduled events
    wp_clear_scheduled_hook('flowdino_sync_products');
}

/**
 * Plugin uninstall hook
 */
function flowdino_uninstall() {
    // Include database class
    $database_file = FLOWDINO_PLUGIN_PATH . 'includes/class-flowdino-wc-database.php';
    if (file_exists($database_file)) {
        require_once $database_file;
        
        if (class_exists('FlowDino_WC_Database')) {
            $database = new FlowDino_WC_Database();
            $database->drop_tables();
        }
    }
    
    // Remove options
    delete_option('flowdino_email');
    delete_option('flowdino_password');
    delete_option('flowdino_token');
    delete_option('flowdino_api_url');
    delete_option('flowdino_auto_sync');
    delete_option('flowdino_default_color');
    delete_option('flowdino_default_brand');
}

// Register hooks
register_activation_hook(__FILE__, 'flowdino_activate');
register_deactivation_hook(__FILE__, 'flowdino_deactivate');
register_uninstall_hook(__FILE__, 'flowdino_uninstall');

// Initialize the plugin after all plugins are loaded
function flowdino_init() {
    FlowDino::get_instance();
}
add_action('plugins_loaded', 'flowdino_init', 20);

/**
 * Hook pour s'assurer que les traductions sont chargées
 */
function flowdino_load_textdomain() {
    // Depuis WordPress 4.6, les traductions sont chargées automatiquement
    // pour les plugins sur WordPress.org. Pour les versions de développement
    // ou les installations locales, charger manuellement.
    
    $locale = get_locale();
    
    // Debug: Forcer le français pour le développement
    if (defined('WP_DEBUG') && WP_DEBUG) {
        $locale = 'fr_FR';
    }
    
    // Charger manuellement uniquement si nécessaire (développement local)
    $mo_file = FLOWDINO_PLUGIN_PATH . 'languages/flowdino-' . $locale . '.mo';
    
    // Si le fichier pour la locale courante n'existe pas, essayer le français
    if (!file_exists($mo_file) && $locale !== 'fr_FR') {
        $mo_file = FLOWDINO_PLUGIN_PATH . 'languages/flowdino-fr_FR.mo';
    }
    
    // Charger le fichier de traduction si il existe
    if (file_exists($mo_file)) {
        load_textdomain('flowdino', $mo_file);
    }
}
add_action('init', 'flowdino_load_textdomain');

/**
 * Force les traductions françaises pour l'admin
 */
function flowdino_force_french_admin() {
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- No nonce needed for reading page parameter to determine locale
    if (is_admin() && isset($_GET['page'])) {
        // Sécuriser l'accès à $_GET['page']
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- No nonce needed for reading page parameter to determine locale
        $page = sanitize_text_field(wp_unslash($_GET['page']));
        
        if (strpos($page, 'flowdino') !== false) {
            // Forcer la locale française pour les pages FlowDino
            add_filter('locale', function($locale) {
                return 'fr_FR';
            });
            
            // Recharger les traductions
            flowdino_load_textdomain();
        }
    }
}
add_action('admin_init', 'flowdino_force_french_admin');
