<?php
namespace LivraisonAPI;

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class Admin {

    public function add_plugin_logo( $plugin_meta, $plugin_file, $plugin_data, $status ) {
        if ( $plugin_file === LIVRAISON_API_BASENAME ) {
            $logo_url = LIVRAISON_API_PLUGIN_URL . 'assets/images/logo-32x32.png';
            $logo_html = '<img src="' . esc_url( $logo_url ) . '" alt="Sendi API" style="height: 20px; width: auto; vertical-align: middle; margin-right: 8px;" />';
            $plugin_meta[0] = $logo_html . $plugin_data['Name'];
        }
        return $plugin_meta;
    }

    public function __construct() {
        add_action( 'admin_menu', array( $this, 'add_admin_menu' ) );
        add_action( 'admin_init', array( $this, 'register_settings' ) );
        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_assets' ) );
        add_action( 'admin_post_livraison_test_api', array( $this, 'test_api_connection' ) );
        
        // AJAX ACTIONS
        add_action( 'wp_ajax_livraison_test_api', array( $this, 'ajax_test_api_connection' ) );
        add_action( 'wp_ajax_livraison_save_merchant', array( $this, 'ajax_save_merchant_info' ) );
        
        // Plugin row meta
        add_filter( 'plugin_row_meta', array( $this, 'add_plugin_logo' ), 10, 4 );
    }

    public function register_settings() {
        // API Settings
        register_setting( 'livraison_api_settings', 'livraison_api_url', array(
            'type' => 'string',
            'sanitize_callback' => 'esc_url_raw',
            'default' => LIVRAISON_API_API_URL
        ) );
        
        register_setting( 'livraison_api_settings', 'livraison_api_key', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default' => ''
        ) );
        
        // Merchant Information
        register_setting( 'livraison_api_settings', 'livraison_api_merchant_name', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default' => ''
        ) );
        
        register_setting( 'livraison_api_settings', 'livraison_api_merchant_phone', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default' => ''
        ) );
        
        register_setting( 'livraison_api_settings', 'livraison_api_merchant_email', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_email',
            'default' => ''
        ) );
        
        register_setting( 'livraison_api_settings', 'livraison_api_pickup_address', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default' => 'Abidjan Cocody Angré Djorogobite lot 1163 îlot 118'
        ) );
        
        register_setting( 'livraison_api_settings', 'livraison_api_pickup_commune', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default' => ''
        ) );

        // class-admin.php - Ajouter dans register_settings()

// ✅ Mode de livraison
        register_setting( 'livraison_api_settings', 'livraison_api_delivery_mode', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default' => 'client_pays' // client_pays | merchant_pays | threshold
        ) );

        // ✅ Seuil de livraison gratuite
        register_setting( 'livraison_api_settings', 'livraison_api_free_threshold', array(
            'type' => 'number',
            'sanitize_callback' => 'floatval',
            'default' => 0
        ) );

        // ✅ Devise (déjà existante)
        register_setting( 'livraison_api_settings', 'livraison_api_currency', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default' => 'FCFA'
        ) );
        
        // Options
        register_setting( 'livraison_api_settings', 'livraison_api_auto_send', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default' => 'yes'
        ) );
        
        register_setting( 'livraison_api_settings', 'livraison_api_auto_complete', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default' => 'no'
        ) );

        // Dans register_settings(), ajoutez ceci après les autres registrations :

register_setting( 'livraison_api_settings', 'livraison_api_allowed_countries', array(
    'type' => 'array',
    'sanitize_callback' => function( $value ) {
        if ( is_array( $value ) ) {
            return array_map( 'sanitize_text_field', $value );
        }
        return array('CI');
    },
    'default' => array('CI', 'BJ', 'BF', 'CM', 'SN', 'ML', 'TG', 'GH', 'NG', 'MA', 'FR')
) );

register_setting( 'livraison_api_settings', 'livraison_api_commercant_country', array(
    'type' => 'string',
    'sanitize_callback' => 'sanitize_text_field',
    'default' => 'CI'
) );

register_setting( 'livraison_api_settings', 'livraison_api_inter_country_enabled', array(
    'type' => 'boolean',
    'sanitize_callback' => 'boolval',
    'default' => false
) );
        
        add_settings_section(
            'livraison_api_main_section',
            __( 'API Configuration', 'sendi-api' ),
            null,
            'livraison_api_settings'
        );
    }

    /**
     * Menu admin avec PNG
     */
    public function add_admin_menu() {
        // ✅ Utiliser le PNG 32x32
        $icon_url = LIVRAISON_API_PLUGIN_URL . 'assets/images/logo-32x32.png';
        
        add_menu_page(
            'Sendi API - Livraison',
            'Sendi API',
            'manage_options',
            'sendi-api',
            array( $this, 'render_dashboard' ),
            $icon_url,
            30
        );


        add_submenu_page(
            'sendi-api',
            __( 'Orders', 'sendi-api' ),
            __( 'Orders', 'sendi-api' ),
            'manage_options',
            'sendi-api-orders',
            array( $this, 'render_orders_page' )
        );

        add_submenu_page(
            'sendi-api',
            __( 'Settings', 'sendi-api' ),
            __( 'Settings', 'sendi-api' ),
            'manage_options',
            'sendi-api-settings',
            array( $this, 'render_settings_page' )
        );
        
        add_submenu_page(
            'sendi-api',
            __( 'Logs', 'sendi-api' ),
            __( 'Logs', 'sendi-api' ),
            'manage_options',
            'sendi-api-logs',
            array( $this, 'render_logs_page' )
        );
        
        add_submenu_page(
            'sendi-api',
            __( 'Help', 'sendi-api' ),
            __( 'Help', 'sendi-api' ),
            'manage_options',
            'sendi-api-help',
            array( $this, 'render_help_page' )
        );
    }

    



    public function render_orders_page() {
        include_once LIVRAISON_API_PLUGIN_DIR . 'templates/admin-orders.php';
    }

    public function render_dashboard() {
        require_once LIVRAISON_API_PLUGIN_DIR . 'templates/admin-dashboard.php';
    }
    
    public function render_settings_page() {
        $test_result = get_transient( 'livraison_api_test_result' );
        delete_transient( 'livraison_api_test_result' );
        
        $api_url = get_option( 'livraison_api_url', 'https://api.sendi-api.com' );
        $api_key = get_option( 'livraison_api_key', '' );
        $auto_send = get_option( 'livraison_api_auto_send', 'yes' );
        $auto_complete = get_option( 'livraison_api_auto_complete', 'no' );
        
        $merchant_name = get_option( 'livraison_api_merchant_name', '' );
        $merchant_phone = get_option( 'livraison_api_merchant_phone', '' );
        $merchant_email = get_option( 'livraison_api_merchant_email', '' );
        $pickup_address = get_option( 'livraison_api_pickup_address', 'Abidjan Cocody Angré Djorogobite lot 1163 îlot 118' );
        $pickup_commune = get_option( 'livraison_api_pickup_commune', '' );
        ?>
        <div class="wrap">
            <h1><?php esc_html_e( 'Sendi API Settings', 'sendi-api' ); ?></h1>
            
            <!-- Container pour les notifications AJAX -->
            <div id="livraison-notification-container"></div>
            
            <?php if ( $test_result ) : ?>
                <div class="notice <?php echo $test_result['success'] ? 'notice-success' : 'notice-error'; ?>">
                    <p><strong><?php echo esc_html( $test_result['message'] ); ?></strong></p>
                </div>
            <?php endif; ?>
            
            <form method="post" action="options.php" id="livraison-settings-form">
                <?php
                settings_fields( 'livraison_api_settings' );
                do_settings_sections( 'livraison_api_settings' );
                ?>
                
                <table class="form-table">
                    <!-- API Section -->
                    <tr>
                        <th colspan="2">
                            <h2><?php esc_html_e( 'API Configuration', 'sendi-api' ); ?></h2>
                            <hr />
                        </th>
                    </tr>
                    

<tr>
    <th scope="row">
        <label for="livraison_api_url"><?php esc_html_e( 'API URL', 'sendi-api' ); ?></label>
    </th>
    <td>
        <input type="url" 
               id="livraison_api_url" 
               name="livraison_api_url" 
               value="<?php echo esc_attr( $api_url ); ?>" 
               class="regular-text" 
               placeholder="https://api.sendi-api.com" />
        <p class="description">
            <?php esc_html_e( 'Sendi API endpoint URL.', 'sendi-api' ); ?>
            <br />
            <strong><?php esc_html_e( 'Production:', 'sendi-api' ); ?></strong> 
            <code>https://api.sendi-api.com</code>
        </p>
    </td>
</tr>
                    
                    <tr>
                        <th scope="row">
                            <label for="livraison_api_key"><?php esc_html_e( 'API Key', 'sendi-api' ); ?></label>
                        </th>
                        <td>
                            <input type="password" 
                                   id="livraison_api_key" 
                                   name="livraison_api_key" 
                                   value="<?php echo esc_attr( $api_key ); ?>" 
                                   class="regular-text" 
                                   placeholder="sk_live_xxxxxxxx" />
                            <p class="description">
                                <?php esc_html_e( 'Get your API key from your Sendi account.', 'sendi-api' ); ?>
                            </p>
                        </td>
                    </tr>
                    
                    <!-- Merchant Section -->
                    <tr>
                        <th colspan="2">
                            <h2><?php esc_html_e( 'Merchant Information', 'sendi-api' ); ?></h2>
                            <p class="description"><?php esc_html_e( 'This information will be sent with each order.', 'sendi-api' ); ?></p>
                            <hr />
                        </th>
                    </tr>
                    
                    <tr>
                        <th scope="row">
                            <label for="livraison_api_merchant_name"><?php esc_html_e( 'Store Name', 'sendi-api' ); ?></label>
                        </th>
                        <td>
                            <input type="text" 
                                   id="livraison_api_merchant_name" 
                                   name="livraison_api_merchant_name" 
                                   value="<?php echo esc_attr( $merchant_name ); ?>" 
                                   class="regular-text" 
                                   placeholder="<?php esc_attr_e( 'My Store', 'sendi-api' ); ?>" />
                            <p class="description">
                                <?php esc_html_e( 'Your store name as it appears on deliveries.', 'sendi-api' ); ?>
                            </p>
                        </td>
                    </tr>
                    
                    <tr>
                        <th scope="row">
                            <label for="livraison_api_merchant_phone"><?php esc_html_e( 'Merchant Phone', 'sendi-api' ); ?></label>
                        </th>
                        <td>
                            <input type="tel" 
                                   id="livraison_api_merchant_phone" 
                                   name="livraison_api_merchant_phone" 
                                   value="<?php echo esc_attr( $merchant_phone ); ?>" 
                                   class="regular-text" 
                                   placeholder="0708091011" />
                            <p class="description">
                                <?php esc_html_e( 'Contact phone number for delivery drivers.', 'sendi-api' ); ?>
                            </p>
                        </td>
                    </tr>
                    
                    <tr>
                        <th scope="row">
                            <label for="livraison_api_merchant_email"><?php esc_html_e( 'Merchant Email', 'sendi-api' ); ?></label>
                        </th>
                        <td>
                            <input type="email" 
                                   id="livraison_api_merchant_email" 
                                   name="livraison_api_merchant_email" 
                                   value="<?php echo esc_attr( $merchant_email ); ?>" 
                                   class="regular-text" 
                                   placeholder="contact@store.com" />
                            <p class="description">
                                <?php esc_html_e( 'Contact email for delivery drivers.', 'sendi-api' ); ?>
                            </p>
                        </td>
                    </tr>

                    
                   




                    <tr>
    <th scope="row">
        <label for="livraison_api_commercant_country"><?php esc_html_e( 'Merchant Country', 'sendi-api' ); ?></label>
    </th>
    <td>
        <?php 
        $commercant_country = get_option( 'livraison_api_commercant_country', 'CI' );
        
        // ✅ RÉCUPÉRER LES PAYS AUTORISÉS DEPUIS L'API
        $allowed_countries = array('CI');
        $inter_country_enabled = false;
        
        try {
            $api = new API();
            $config_response = $api->request('/api/v1/delivery/config', 'GET');
            
            if ($config_response['success'] && isset($config_response['data'])) {
                $config = $config_response['data'];
                if (isset($config['allowedCountries']) && is_array($config['allowedCountries'])) {
                    $allowed_countries = $config['allowedCountries'];
                }
                if (isset($config['interCountryEnabled'])) {
                    $inter_country_enabled = $config['interCountryEnabled'];
                }
            }
        } catch (Exception $e) {
            // Fallback sur les options WordPress
            $allowed_countries = get_option('livraison_api_allowed_countries', array('CI'));
            livraison_api_log('⚠️ Erreur récupération config API: ' . $e->getMessage(), 'error');
        }
        
        // ✅ S'assurer que c'est un tableau
        if (!is_array($allowed_countries)) {
            $allowed_countries = array('CI');
        }
        
        $AVAILABLE_COUNTRIES = array(
            'CI' => 'Côte d\'Ivoire',
            'BJ' => 'Bénin',
            'BF' => 'Burkina Faso',
            'CM' => 'Cameroun',
            'SN' => 'Sénégal',
            'ML' => 'Mali',
            'TG' => 'Togo',
            'GH' => 'Ghana',
            'NG' => 'Nigeria',
            'MA' => 'Maroc',
            'FR' => 'France'
        );
        
        // ✅ Afficher TOUS les pays autorisés (peu importe inter_country_enabled)
        $display_countries = array();
        foreach ($allowed_countries as $code) {
            $code = trim($code);
            if (isset($AVAILABLE_COUNTRIES[$code])) {
                $display_countries[$code] = $AVAILABLE_COUNTRIES[$code];
            }
        }
        
        // Si aucun pays autorisé, fallback sur CI
        if (empty($display_countries)) {
            $display_countries = array('CI' => 'Côte d\'Ivoire');
        }
        ?>
        
        <select id="livraison_api_commercant_country" name="livraison_api_commercant_country" class="regular-text">
            <?php foreach ($display_countries as $code => $name) : ?>
                <option value="<?php echo esc_attr($code); ?>" <?php selected($commercant_country, $code); ?>>
                    <?php echo esc_html($name); ?>
                </option>
            <?php endforeach; ?>
        </select>
        
        <p class="description">
            <?php esc_html_e( 'Select your country of operation from the allowed countries list.', 'sendi-api' ); ?>
        </p>
    </td>
</tr>

<!-- Dans class-admin.php, après le champ Merchant Email, ajoutez : -->

<tr>
    <th scope="row">
        <label for="livraison_api_pickup_address"><?php esc_html_e( 'Pickup Address', 'sendi-api' ); ?></label>
    </th>
    <td>
        <input type="text" 
               id="livraison_api_pickup_address" 
               name="livraison_api_pickup_address" 
               value="<?php echo esc_attr( $pickup_address ); ?>" 
               class="regular-text" 
               placeholder="<?php esc_attr_e( 'Enter your pickup address', 'sendi-api' ); ?>" />
        <p class="description">
            <?php esc_html_e( 'Address where the driver will pick up the package.', 'sendi-api' ); ?>
        </p>
    </td>
</tr>







<tr>
    <th scope="row">
        <label for="livraison_api_pickup_commune"><?php esc_html_e( 'Pickup Commune', 'sendi-api' ); ?></label>
    </th>
    <td>
        <?php
        $livraison_pickup_commune = get_option( 'livraison_api_pickup_commune', '' );
        $livraison_api = new API();
        $livraison_communes_response = $livraison_api->get_communes();
        
        // ✅ Récupérer le pays actuel du commerçant
        $commercant_country = get_option( 'livraison_api_commercant_country', 'CI' );
        
        // ✅ Récupérer les pays autorisés depuis l'API
        $allowed_countries = array('CI');
        try {
            $config_response = $livraison_api->request('/api/v1/delivery/config', 'GET');
            if ($config_response['success'] && isset($config_response['data'])) {
                $config = $config_response['data'];
                if (isset($config['allowedCountries']) && is_array($config['allowedCountries'])) {
                    $allowed_countries = $config['allowedCountries'];
                }
            }
        } catch (Exception $e) {
            $allowed_countries = get_option('livraison_api_allowed_countries', array('CI'));
        }
        
        if (!is_array($allowed_countries)) {
            $allowed_countries = array('CI');
        }
        
        // ✅ Filtrer les communes par pays du commerçant
        $filtered_communes = array();
        if ($livraison_communes_response['success'] && !empty($livraison_communes_response['data'])) {
            $communes = $livraison_communes_response['data'];
            
            foreach ($communes as $commune) {
                $commune_country = isset($commune['countryCode']) ? $commune['countryCode'] : 'CI';
                // ✅ Filtrer par pays du commerçant (pas par inter_country_enabled)
                if ($commune_country === $commercant_country) {
                    $filtered_communes[] = $commune;
                }
            }
        }
        
        // Fallback si aucune commune filtrée
        if (empty($filtered_communes)) {
            $filtered_communes = isset($communes) ? $communes : array();
        }
        ?>
        <select id="livraison_api_pickup_commune" name="livraison_api_pickup_commune" style="min-width: 200px;">
            <option value=""><?php esc_html_e( 'Select a commune', 'sendi-api' ); ?></option>
            <?php
            foreach ($filtered_communes as $commune) {
                $name = isset($commune['name']) ? $commune['name'] : (isset($commune['nom']) ? $commune['nom'] : '');
                if (empty($name)) {
                    continue;
                }
                echo '<option value="' . esc_attr($name) . '"' . selected($livraison_pickup_commune, $name, false) . '>';
                echo esc_html($name);
                if (!empty($commune['city'])) {
                    echo ' (' . esc_html($commune['city']) . ')';
                }
                echo '</option>';
            }
            ?>
        </select>
        <p class="description">
            <?php esc_html_e( 'Commune where the driver will pick up the package.', 'sendi-api' ); ?>
            <br />
            <small><?php esc_html_e( 'Communes filtered by your selected country.', 'sendi-api' ); ?></small>
        </p>
    </td>
</tr>

<tr>
    <th scope="row">
        <label><?php esc_html_e( 'International Delivery', 'sendi-api' ); ?></label>
    </th>
    <td>
        <?php 
        $inter_country_enabled = get_option( 'livraison_api_inter_country_enabled', false );
        $commercant_country = get_option( 'livraison_api_commercant_country', 'CI' );
        $AVAILABLE_COUNTRIES = array(
            'CI' => 'Côte d\'Ivoire',
            'BJ' => 'Bénin',
            'BF' => 'Burkina Faso',
            'CM' => 'Cameroun',
            'SN' => 'Sénégal',
            'ML' => 'Mali',
            'TG' => 'Togo',
            'GH' => 'Ghana',
            'NG' => 'Nigeria',
            'MA' => 'Maroc',
            'FR' => 'France'
        );
        $country_name = isset( $AVAILABLE_COUNTRIES[ $commercant_country ] ) ? $AVAILABLE_COUNTRIES[ $commercant_country ] : $commercant_country;
        ?>
        
        <?php if ( $inter_country_enabled ) : ?>
            <!-- ✅ Si inter-pays activé, le commerçant peut activer/désactiver -->
            <label>
                <input type="checkbox" 
                       id="livraison_api_inter_country_enabled" 
                       name="livraison_api_inter_country_enabled" 
                       value="1" 
                       <?php checked( $inter_country_enabled, true ); ?> />
                <?php esc_html_e( 'Allow customers to order from other countries', 'sendi-api' ); ?>
            </label>
            <p class="description">
                <?php esc_html_e( 'Enable to allow customers from other countries.', 'sendi-api' ); ?>
            </p>
        <?php else : ?>
            <!-- ❌ Si inter-pays désactivé, ne pas permettre de cocher -->
            <div style="background: #fef3c7; padding: 12px 16px; border-radius: 6px; border-left: 4px solid #f59e0b; max-width: 500px;">
                <p style="margin: 0; font-weight: 500; color: #92400e;">
                    🔒 <?php esc_html_e( 'International delivery is disabled by the administrator.', 'sendi-api' ); ?>
                </p>
                <p style="margin: 4px 0 0 0; font-size: 13px; color: #78350f;">
                    <?php 
                    printf(
                        /* translators: %s: country name */
                        esc_html__( 'For now, we only accept deliveries in %s.', 'sendi-api' ),
                        esc_html( $country_name )
                    ); 
                    ?>
                </p>
                <input type="hidden" name="livraison_api_inter_country_enabled" value="0" />
            </div>
        <?php endif; ?>
        
        <!-- Allowed Countries (visible uniquement si inter-pays activé) -->
        <?php if ( $inter_country_enabled ) : ?>
            <?php 
            $allowed_countries = get_option( 'livraison_api_allowed_countries', array('CI') );
            ?>
            <div id="livraison_allowed_countries_wrap" style="margin-top: 10px;">
                <label><?php esc_html_e( 'Allowed countries for delivery', 'sendi-api' ); ?></label>
                <select id="livraison_api_allowed_countries" name="livraison_api_allowed_countries[]" multiple style="min-width: 200px; height: 120px; display: block; margin-top: 4px;">
                    <?php foreach ( $AVAILABLE_COUNTRIES as $code => $name ) : ?>
                        <option value="<?php echo esc_attr( $code ); ?>" <?php echo in_array( $code, $allowed_countries ) ? 'selected' : ''; ?>>
                            <?php echo esc_html( $name ); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                <p class="description">
                    <?php esc_html_e( 'Select countries where customers can order from. Hold Ctrl/Cmd to select multiple.', 'sendi-api' ); ?>
                </p>
            </div>
        <?php endif; ?>
    </td>
</tr>


<!-- ✅ SECTION LIVRAISON -->
<tr>
    <th colspan="2">
        <h2><?php esc_html_e( 'Delivery Fees Management', 'sendi-api' ); ?></h2>
        <p class="description">
            <?php esc_html_e( 'Choose who pays for delivery and when.', 'sendi-api' ); ?>
        </p>
        <hr />
    </th>
</tr>

<tr>
    <th scope="row">
        <label><?php esc_html_e( 'Delivery fees policy', 'sendi-api' ); ?></label>
    </th>
    <td>
        <?php 
        $delivery_mode = get_option( 'livraison_api_delivery_mode', 'client_pays' );
        $free_threshold = floatval( get_option( 'livraison_api_free_threshold', 0 ) );
        $currency = get_option( 'livraison_api_currency', 'FCFA' );
        ?>
        
        <div class="livraison-delivery-options">
            <!-- Option 1: Client pays -->
            <label class="livraison-option-card <?php echo $delivery_mode === 'client_pays' ? 'selected' : ''; ?>">
                <input type="radio" 
                       name="livraison_api_delivery_mode" 
                       value="client_pays" 
                       <?php checked( $delivery_mode, 'client_pays' ); ?> />
                <div class="livraison-option-content">
                    <span class="livraison-option-icon">👤</span>
                    <div>
                        <strong><?php esc_html_e( 'Customer pays', 'sendi-api' ); ?></strong>
                        <p class="description">
                            <?php esc_html_e( 'The customer always pays for delivery (cash on delivery).', 'sendi-api' ); ?>
                        </p>
                    </div>
                </div>
            </label>
            
            <!-- Option 2: Merchant pays (always free) -->
            <label class="livraison-option-card <?php echo $delivery_mode === 'merchant_pays' ? 'selected' : ''; ?>">
                <input type="radio" 
                       name="livraison_api_delivery_mode" 
                       value="merchant_pays" 
                       <?php checked( $delivery_mode, 'merchant_pays' ); ?> />
                <div class="livraison-option-content">
                    <span class="livraison-option-icon">🏪</span>
                    <div>
                        <strong><?php esc_html_e( 'Always free (merchant pays)', 'sendi-api' ); ?></strong>
                        <p class="description">
                            <?php esc_html_e( 'All deliveries are free for customers. The merchant covers all delivery costs.', 'sendi-api' ); ?>
                        </p>
                    </div>
                </div>
            </label>
            
            <!-- Option 3: Threshold based -->
            <label class="livraison-option-card <?php echo $delivery_mode === 'threshold' ? 'selected' : ''; ?>">
                <input type="radio" 
                       name="livraison_api_delivery_mode" 
                       value="threshold" 
                       <?php checked( $delivery_mode, 'threshold' ); ?> />
                <div class="livraison-option-content">
                    <span class="livraison-option-icon">🎯</span>
                    <div>
                        <strong><?php esc_html_e( 'Free above a threshold', 'sendi-api' ); ?></strong>
                        <p class="description">
                            <?php esc_html_e( 'Delivery is free if the order total exceeds a set amount.', 'sendi-api' ); ?>
                        </p>
                    </div>
                </div>
            </label>
        </div>
    </td>
</tr>

<!-- ✅ Seuil de livraison gratuite (affiché uniquement si mode threshold) -->
<tr id="livraison_threshold_row" style="<?php echo $delivery_mode === 'threshold' ? '' : 'display: none;'; ?>">
    <th scope="row">
        <label for="livraison_api_free_threshold">
            <?php esc_html_e( 'Free delivery threshold', 'sendi-api' ); ?>
        </label>
    </th>
    <td>
        <div style="display: flex; align-items: center; gap: 10px; flex-wrap: wrap;">
            <span><?php esc_html_e( 'Free delivery for orders over', 'sendi-api' ); ?></span>
            <input type="number" 
                   id="livraison_api_free_threshold" 
                   name="livraison_api_free_threshold" 
                   value="<?php echo esc_attr( $free_threshold ); ?>" 
                   style="width: 150px;"
                   min="0"
                   step="100"
                   placeholder="50000" />
            <strong><?php echo esc_html( $currency ); ?></strong>
        </div>
        <p class="description">
            <?php esc_html_e( 'When the order total exceeds this amount, delivery is free for the customer.', 'sendi-api' ); ?>
        </p>
        <div id="livraison_threshold_preview" style="margin-top: 10px; padding: 12px 16px; background: #f0f7ff; border-radius: 6px; border-left: 4px solid #007cba; display: <?php echo $delivery_mode === 'threshold' && $free_threshold > 0 ? 'block' : 'none'; ?>;">
            <span class="dashicons dashicons-info" style="color: #007cba;"></span>
            <span>
                <?php esc_html_e( 'Customers will get free delivery when their cart exceeds', 'sendi-api' ); ?> 
                <strong><span id="livraison_threshold_display"><?php echo number_format( $free_threshold, 0, ',', ' ' ); ?></span> <?php echo esc_html( $currency ); ?></strong>.
                <?php esc_html_e( 'Below this amount, the customer pays for delivery.', 'sendi-api' ); ?>
            </span>
        </div>
    </td>
</tr>
                    
                    <!-- Options Section -->
                    <tr>
                        <th colspan="2">
                            <h2><?php esc_html_e( 'Options', 'sendi-api' ); ?></h2>
                            <hr />
                        </th>
                    </tr>
                    
                    <tr>
                        <th scope="row">
                            <label for="livraison_api_auto_send"><?php esc_html_e( 'Auto Send', 'sendi-api' ); ?></label>
                        </th>
                        <td>
                            <select id="livraison_api_auto_send" name="livraison_api_auto_send">
                                <option value="yes" <?php selected( $auto_send, 'yes' ); ?>>
                                    <?php esc_html_e( 'Yes', 'sendi-api' ); ?>
                                </option>
                                <option value="no" <?php selected( $auto_send, 'no' ); ?>>
                                    <?php esc_html_e( 'No', 'sendi-api' ); ?>
                                </option>
                            </select>
                            <p class="description">
                                <?php esc_html_e( 'Automatically send orders to the Sendi API.', 'sendi-api' ); ?>
                            </p>
                        </td>
                    </tr>
                    
                    <tr>
                        <th scope="row">
                            <label for="livraison_api_auto_complete"><?php esc_html_e( 'Auto Complete', 'sendi-api' ); ?></label>
                        </th>
                        <td>
                            <select id="livraison_api_auto_complete" name="livraison_api_auto_complete">
                                <option value="yes" <?php selected( $auto_complete, 'yes' ); ?>>
                                    <?php esc_html_e( 'Yes', 'sendi-api' ); ?>
                                </option>
                                <option value="no" <?php selected( $auto_complete, 'no' ); ?>>
                                    <?php esc_html_e( 'No', 'sendi-api' ); ?>
                                </option>
                            </select>
                            <p class="description">
                                <?php esc_html_e( 'Automatically complete the order after delivery.', 'sendi-api' ); ?>
                            </p>
                        </td>
                    </tr>
                </table>
                
                <!-- Boutons d'action -->
                <div class="livraison-actions-wrap" style="margin-top: 20px; display: flex; gap: 10px; flex-wrap: wrap; align-items: center;">
                    <button type="button" id="livraison-test-api" class="button button-secondary">
                        <?php esc_html_e( 'Test Connection', 'sendi-api' ); ?>
                    </button>
                    
                    <button type="button" id="livraison-save-merchant" class="button button-primary">
                        <?php esc_html_e( 'Save Merchant Info', 'sendi-api' ); ?>
                    </button>
                    
                    <button type="submit" class="button button-primary">
                        <?php esc_html_e( 'Save All Settings', 'sendi-api' ); ?>
                    </button>
                </div>
            </form>
            
            <hr />
            
            <!-- Summary -->
            <div class="card" style="background: #f0f7ff; padding: 20px; border-radius: 8px; margin-top: 20px; border-left: 4px solid #007cba;">
                <h3><?php esc_html_e( 'Configuration Summary', 'sendi-api' ); ?></h3>
                <p><?php esc_html_e( 'This information will be sent with each order:', 'sendi-api' ); ?></p>
                <ul style="list-style: none; padding: 0;">
                    <li><strong><?php esc_html_e( 'Store:', 'sendi-api' ); ?></strong> <span class="livraison-summary-store"><?php echo ! empty( $merchant_name ) ? esc_html( $merchant_name ) : '<span style="color: #dc3232;">' . esc_html__( 'Not configured', 'sendi-api' ) . '</span>'; ?></span></li>
                    <li><strong><?php esc_html_e( 'Phone:', 'sendi-api' ); ?></strong> <span class="livraison-summary-phone"><?php echo ! empty( $merchant_phone ) ? esc_html( $merchant_phone ) : '<span style="color: #dc3232;">' . esc_html__( 'Not configured', 'sendi-api' ) . '</span>'; ?></span></li>
                    <li><strong><?php esc_html_e( 'Email:', 'sendi-api' ); ?></strong> <span class="livraison-summary-email"><?php echo ! empty( $merchant_email ) ? esc_html( $merchant_email ) : '<span style="color: #dc3232;">' . esc_html__( 'Not configured', 'sendi-api' ) . '</span>'; ?></span></li>
                    <li><strong><?php esc_html_e( 'Pickup Address:', 'sendi-api' ); ?></strong> <span class="livraison-summary-address"><?php echo ! empty( $pickup_address ) ? esc_html( $pickup_address ) : '<span style="color: #dc3232;">' . esc_html__( 'Not configured', 'sendi-api' ) . '</span>'; ?></span></li>
                    <li><strong><?php esc_html_e( 'Pickup Commune:', 'sendi-api' ); ?></strong> <span class="livraison-summary-commune"><?php echo ! empty( $pickup_commune ) ? esc_html( $pickup_commune ) : '<span style="color: #dc3232;">' . esc_html__( 'Not configured', 'sendi-api' ) . '</span>'; ?></span></li>
                </ul>
            </div>
            
            <div class="card" style="background: #f8f9fa; padding: 20px; border-radius: 8px; margin-top: 20px;">
                <h2><?php esc_html_e( 'Test API Connection', 'sendi-api' ); ?></h2>
                <p><?php esc_html_e( 'Test the connection with the Sendi API using the current configuration.', 'sendi-api' ); ?></p>
                <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' )); ?>">
                    <?php wp_nonce_field( 'livraison_api_test_nonce', 'livraison_api_test_nonce' ); ?>
                    <input type="hidden" name="action" value="livraison_test_api" />
                    <button type="submit" class="button button-primary">
                        <?php esc_html_e( 'Test Connection (Legacy)', 'sendi-api' ); ?>
                    </button>
                </form>
            </div>
        </div>
        <?php
    }
    
    /**
     * Render Logs Page with Cache
     */
    public function render_logs_page() {
        global $wpdb;
        
        // ✅ CORRECTION: Utiliser le cache pour les logs
        $cache_key = 'livraison_admin_logs';
        $cache_group = 'livraison_api';
        $livraison_logs = wp_cache_get( $cache_key, $cache_group );
        
        if ( false === $livraison_logs ) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
            $livraison_logs = $wpdb->get_results(
                "SELECT * FROM {$wpdb->prefix}livraison_api_logs ORDER BY created_at DESC LIMIT 50"
            );
            // Mettre en cache pendant 5 minutes (300 secondes)
            wp_cache_set( $cache_key, $livraison_logs, $cache_group, 300 );
        }
        ?>
        <div class="wrap">
            <h1><?php esc_html_e( 'Sendi API Logs', 'sendi-api' ); ?></h1>
            
            <div class="card">
                <h2><?php esc_html_e( 'Recent Logs', 'sendi-api' ); ?></h2>
                <?php if ( $livraison_logs ) : ?>
                    <table class="wp-list-table widefat fixed striped sendi-api-logs-table">
                        <thead>
                            <tr>
                                <th><?php esc_html_e( 'ID', 'sendi-api' ); ?></th>
                                <th><?php esc_html_e( 'Order', 'sendi-api' ); ?></th>
                                <th><?php esc_html_e( 'Course ID', 'sendi-api' ); ?></th>
                                <th><?php esc_html_e( 'Secret Code', 'sendi-api' ); ?></th>
                                <th><?php esc_html_e( 'Status', 'sendi-api' ); ?></th>
                                <th><?php esc_html_e( 'Date', 'sendi-api' ); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ( $livraison_logs as $livraison_log ) : ?>
                                <tr>
                                    <td><?php echo esc_html( $livraison_log->id ); ?></td>
                                    <td>
                                        <a href="<?php echo esc_url( admin_url( 'post.php?post=' . (int) $livraison_log->order_id . '&action=edit' )); ?>">
                                            #<?php echo esc_html( $livraison_log->order_id ); ?>
                                        </a>
                                    </td>
                                    <td><code><?php echo esc_html( $livraison_log->course_id ); ?></code></td>
                                    <td><code><?php echo esc_html( $livraison_log->code_secret ); ?></code></td>
                                    <td>
                                        <span class="status-<?php echo esc_attr( $livraison_log->status ); ?>">
                                            <?php 
                                            // Labels de statut
                                            $livraison_status_labels = array(
                                                'sent' => __( 'Sent', 'sendi-api' ),
                                                'assigned' => __( 'Assigned', 'sendi-api' ),
                                                'in_progress' => __( 'In Progress', 'sendi-api' ),
                                                'delivered' => __( 'Delivered', 'sendi-api' ),
                                                'failed' => __( 'Failed', 'sendi-api' ),
                                                'cancelled' => __( 'Cancelled', 'sendi-api' ),
                                                'created' => __( 'Created', 'sendi-api' )
                                            );
                                            echo esc_html( isset( $livraison_status_labels[ $livraison_log->status ] ) ? $livraison_status_labels[ $livraison_log->status ] : ucfirst( $livraison_log->status ) );
                                            ?>
                                        </span>
                                    </td>
                                    <td>
                                        <?php 
                                        $livraison_timestamp = strtotime( $livraison_log->created_at );
                                        if ( $livraison_timestamp ) {
                                            echo esc_html( date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), $livraison_timestamp ) );
                                        } else {
                                            echo esc_html( $livraison_log->created_at );
                                        }
                                        ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php else : ?>
                    <p><?php esc_html_e( 'No logs found.', 'sendi-api' ); ?></p>
                <?php endif; ?>
            </div>
        </div>
        <?php
    }


    // class-admin.php - Ajouter cette méthode

/**
 * Récupérer la configuration de livraison
 */
private function get_delivery_config() {
    $cache_key = 'livraison_delivery_config';
    $cached = wp_cache_get( $cache_key, 'livraison_api' );
    
    if ( false !== $cached ) {
        return $cached;
    }
    
    $api = new API();
    $result = $api->request( '/api/v1/delivery/config', 'GET' );
    
    if ( $result['success'] ) {
        wp_cache_set( $cache_key, $result['data'], 'livraison_api', 3600 );
        return $result['data'];
    }
    
    // Fallback
    $default = array(
        'allowedCountries' => array( 'CI' ),
        'interCountryEnabled' => false
    );
    wp_cache_set( $cache_key, $default, 'livraison_api', 3600 );
    return $default;
}
    
    public function render_help_page() {
        ?>
        <div class="wrap">
            <h1><?php esc_html_e( 'Help - Sendi API', 'sendi-api' ); ?></h1>
            
            <div class="card">
                <h2><?php esc_html_e( 'Requirements', 'sendi-api' ); ?></h2>
                <ol>
                    <li><?php esc_html_e( 'Configure your API key in the settings.', 'sendi-api' ); ?></li>
                    <li><?php esc_html_e( 'Set the default pickup commune.', 'sendi-api' ); ?></li>
                    <li><?php esc_html_e( 'Fill in your merchant information.', 'sendi-api' ); ?></li>
                    <li><?php esc_html_e( 'Test the connection.', 'sendi-api' ); ?></li>
                </ol>
            </div>
            
            <div class="card">
                <h2><?php esc_html_e( 'Available Shortcodes', 'sendi-api' ); ?></h2>
                <table class="wp-list-table widefat fixed striped">
                    <thead>
                        <tr>
                            <th><?php esc_html_e( 'Shortcode', 'sendi-api' ); ?></th>
                            <th><?php esc_html_e( 'Description', 'sendi-api' ); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td><code>[livraison-prix depart="Yopougon" arrivee="Cocody"]</code></td>
                            <td><?php esc_html_e( 'Display delivery price between two communes.', 'sendi-api' ); ?></td>
                        </tr>
                        <tr>
                            <td><code>[livraison-tracking order_id="123"]</code></td>
                            <td><?php esc_html_e( 'Display tracking for a course.', 'sendi-api' ); ?></td>
                        </tr>
                        <tr>
                            <td><code>[livraison-solde]</code></td>
                            <td><?php esc_html_e( 'Display credit balance.', 'sendi-api' ); ?></td>
                        </tr>
                    </tbody>
                </table>
            </div>
            
            <div class="card">
                <h2><?php esc_html_e( 'Webhook URL', 'sendi-api' ); ?></h2>
                <p><?php esc_html_e( 'Configure this webhook URL in the Sendi API:', 'sendi-api' ); ?></p>
                <code style="display: block; padding: 10px; background: #f0f0f0; border-radius: 4px;">
                    <?php echo esc_url( rest_url( 'sendi-api/v1/webhook' ) ); ?>
                </code>
            </div>
        </div>
        <?php
    }
    
    /**
     * Test API Connection - Admin Post (Legacy)
     */
    public function test_api_connection() {
        check_admin_referer( 'livraison_api_test_nonce', 'livraison_api_test_nonce' );
        
        $api = new API();
        $result = $api->test_connection();
        
        if ( $result['success'] ) {
            $message = 'Connection successful! HTTP ' . $result['status'] . ' OK';
            $success = true;
        } else {
            $error = isset( $result['error'] ) ? $result['error'] : 'Unknown error';
            $status = isset( $result['status'] ) ? $result['status'] : '???';
            $message = 'Connection error (HTTP ' . $status . '): ' . $error;
            $success = false;
        }
        
        set_transient( 'livraison_api_test_result', array(
            'success' => $success,
            'message' => $message,
            'details' => $result
        ), 30 );
        
        wp_safe_redirect( admin_url( 'admin.php?page=sendi-api-settings' ) );
        exit;
    }
    
    /**
     * AJAX - Test API Connection
     */
    public function ajax_test_api_connection() {
        // Vérification du nonce
        if ( ! check_ajax_referer( 'livraison_api_nonce', 'nonce', false ) ) {
            wp_send_json_error( array( 'message' => 'Invalid nonce' ) );
            return;
        }
        
        // Vérification des droits
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => 'Unauthorized' ) );
            return;
        }
        
        $api = new API();
        $result = $api->test_connection();
        
        if ( $result['success'] ) {
            wp_send_json_success( array(
                'message' => '✅ Connection successful!',
                'data' => $result['data']
            ) );
        } else {
            wp_send_json_error( array(
                'message' => '❌ Connection failed: ' . ( $result['error'] ?? 'Unknown error' ),
                'status' => $result['status'] ?? 0
            ) );
        }
    }
    
    /**
     * AJAX - Save Merchant Info
     */
    public function ajax_save_merchant_info() {
        // Vérification du nonce
        if ( ! check_ajax_referer( 'livraison_api_nonce', 'nonce', false ) ) {
            wp_send_json_error( array( 'message' => 'Invalid nonce' ) );
            return;
        }
        
        // Vérification des droits
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => 'Unauthorized' ) );
            return;
        }
        
        // ✅ CORRECTION: Ajouter wp_unslash() avant sanitization
        $merchant_name = isset( $_POST['merchant_name'] ) ? sanitize_text_field( wp_unslash( $_POST['merchant_name'] ) ) : '';
        $merchant_phone = isset( $_POST['merchant_phone'] ) ? sanitize_text_field( wp_unslash( $_POST['merchant_phone'] ) ) : '';
        $merchant_email = isset( $_POST['merchant_email'] ) ? sanitize_email( wp_unslash( $_POST['merchant_email'] ) ) : '';
        $pickup_address = isset( $_POST['pickup_address'] ) ? sanitize_text_field( wp_unslash( $_POST['pickup_address'] ) ) : '';
        $pickup_commune = isset( $_POST['pickup_commune'] ) ? sanitize_text_field( wp_unslash( $_POST['pickup_commune'] ) ) : '';
        
        // Sauvegarde des options
        update_option( 'livraison_api_merchant_name', $merchant_name );
        update_option( 'livraison_api_merchant_phone', $merchant_phone );
        update_option( 'livraison_api_merchant_email', $merchant_email );
        update_option( 'livraison_api_pickup_address', $pickup_address );
        update_option( 'livraison_api_pickup_commune', $pickup_commune );
        
        wp_send_json_success( array(
            'message' => '✅ Merchant information saved successfully!',
            'data' => array(
                'merchant_name' => $merchant_name,
                'merchant_phone' => $merchant_phone,
                'merchant_email' => $merchant_email,
                'pickup_address' => $pickup_address,
                'pickup_commune' => $pickup_commune
            )
        ) );
    }
    
    /**
 * Enqueue Admin Assets
 */
public function enqueue_admin_assets( $hook ) {
    if ( strpos( $hook, 'sendi-api' ) === false ) {
        return;
    }
    
    // Dashboard
    if ( 'toplevel_page_sendi-api-dashboard' === $hook ) {
        wp_enqueue_style(
            'livraison-admin-dashboard',
            LIVRAISON_API_PLUGIN_URL . 'assets/css/admin-dashboard.css',
            array(),
            LIVRAISON_API_VERSION
        );
    }
    
    // Orders
    if ( 'sendi-api_page_sendi-api-orders' === $hook ) {
        wp_enqueue_style(
            'livraison-admin-orders',
            LIVRAISON_API_PLUGIN_URL . 'assets/css/admin-orders.css',
            array(),
            LIVRAISON_API_VERSION
        );
        
        wp_enqueue_script(
            'livraison-admin-orders',
            LIVRAISON_API_PLUGIN_URL . 'assets/js/admin-orders.js',
            array( 'jquery' ),
            LIVRAISON_API_VERSION,
            true
        );
        
        wp_localize_script(
            'livraison-admin-orders',
            'livraisonAdmin',
            array(
                'ajaxUrl' => admin_url( 'admin-ajax.php' ),
                'trackNonce' => wp_create_nonce( 'livraison_track_nonce' ),
                'l10n' => array(
                    'loading' => __( 'Loading...', 'sendi-api' ),
                    'errorTracking' => __( 'Error tracking order', 'sendi-api' ),
                    'connectionError' => __( 'Connection error', 'sendi-api' ),
                )
            )
        );
    }
    
    // Settings
    if ( 'sendi-api_page_sendi-api-settings' === $hook ) {
        wp_enqueue_style(
            'livraison-admin-settings',
            LIVRAISON_API_PLUGIN_URL . 'assets/css/admin-settings.css',
            array(),
            LIVRAISON_API_VERSION
        );
        
        wp_enqueue_script(
            'livraison-admin-settings',
            LIVRAISON_API_PLUGIN_URL . 'assets/js/admin-settings.js',
            array( 'jquery' ),
            LIVRAISON_API_VERSION,
            true
        );
        
        wp_localize_script(
            'livraison-admin-settings',
            'livraisonSettings',
            array(
                'ajaxUrl' => admin_url( 'admin-ajax.php' ),
                'nonce' => wp_create_nonce( 'livraison_api_nonce' ),
                'l10n' => array(
                    'testing' => __( 'Testing...', 'sendi-api' ),
                    'saving' => __( 'Saving...', 'sendi-api' ),
                    'testSuccess' => __( '✅ Connection successful!', 'sendi-api' ),
                    'testError' => __( '❌ Connection failed', 'sendi-api' ),
                    'saveSuccess' => __( '✅ Merchant information saved successfully!', 'sendi-api' ),
                    'saveError' => __( '❌ Error saving', 'sendi-api' ),
                    'confirmDelete' => __( 'Are you sure you want to delete this item?', 'sendi-api' ),
                    'copySuccess' => __( 'Shortcode copied to clipboard!', 'sendi-api' ),
                )
            )
        );
    }
}
}