<?php
/**
 * Plugin Name: Sendi API - Livraison
 * Plugin URI: https://sendi-api.com/plugin
 * Description: SendiAPI delivery platform integration for WooCommerce - Cash on delivery
 * Version: 1.2.1
 * Author: SendiAPI
 * Author URI: https://sendi-api.com
 * Text Domain: sendi-api
 * Domain Path: /languages
 * WC requires at least: 5.0
 * WC tested up to: 8.5
 * Requires Plugins: woocommerce
 * License: GPLv2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 *
 * @package SendiAPI
 */
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

// Constants
define( 'LIVRAISON_API_VERSION', '1.2.1' );
define( 'LIVRAISON_API_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
define( 'LIVRAISON_API_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
define( 'LIVRAISON_API_FILE', __FILE__ );
define( 'LIVRAISON_API_BASENAME', plugin_basename( __FILE__ ) );
define( 'LIVRAISON_API_API_URL', 'https://api.sendi-api.com' );

$livraison_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'
);



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

// Autoloader
spl_autoload_register( function( $class ) {
    $prefix = 'LivraisonAPI\\';
    $base_dir = LIVRAISON_API_PLUGIN_DIR . 'includes/';
    
    if ( strpos( $class, $prefix ) !== 0 ) {
        return;
    }
    
    $class_name = substr( $class, strlen( $prefix ) );
    $file = $base_dir . 'class-' . strtolower( str_replace( '_', '-', $class_name ) ) . '.php';
    
    if ( file_exists( $file ) ) {
        require_once $file;
    }
} );

// Plugin Activation
register_activation_hook( __FILE__, 'livraison_api_activate' );
function livraison_api_activate() {
    global $wpdb;
    
    $table_name = $wpdb->prefix . 'livraison_api_logs';
    
    // ✅ CORRECTION : Utiliser TOUS les pays par défaut
    $default_countries = array('CI', 'BJ', 'BF', 'CM', 'SN', 'ML', 'TG', 'GH', 'NG', 'MA', 'FR');
    
    // ✅ Utiliser add_option avec vérification pour ne pas écraser
    if ( ! get_option( 'livraison_api_allowed_countries' ) ) {
        add_option( 'livraison_api_allowed_countries', $default_countries );
    }
    if ( ! get_option( 'livraison_api_inter_country_enabled' ) ) {
        add_option( 'livraison_api_inter_country_enabled', false );
    }
    if ( ! get_option( 'livraison_api_commercant_country' ) ) {
        add_option( 'livraison_api_commercant_country', 'CI' );
    }
    
    $charset_collate = $wpdb->get_charset_collate();
    $sql = "CREATE TABLE IF NOT EXISTS $table_name (
        id bigint(20) NOT NULL AUTO_INCREMENT,
        order_id bigint(20) NOT NULL,
        course_id varchar(255) NOT NULL,
        code_secret varchar(255) NOT NULL,
        status varchar(50) DEFAULT 'created',
        price decimal(10,2) DEFAULT 0.00,
        client_name varchar(255) DEFAULT NULL,
        client_phone varchar(50) DEFAULT NULL,
        client_address text DEFAULT NULL,
        client_commune varchar(100) DEFAULT NULL,
        merchant_name varchar(255) DEFAULT NULL,
        merchant_phone varchar(50) DEFAULT NULL,
        merchant_email varchar(255) DEFAULT NULL,
        agence_name varchar(255) DEFAULT NULL,
        agence_phone varchar(50) DEFAULT NULL,
        agence_email varchar(255) DEFAULT NULL,
        payer_type varchar(20) DEFAULT 'client',
        is_free tinyint(1) DEFAULT 0,
        free_reason varchar(50) DEFAULT NULL,
        created_at datetime DEFAULT CURRENT_TIMESTAMP,
        updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        KEY order_id (order_id),
        KEY course_id (course_id)
    ) $charset_collate;";
    
    require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
    dbDelta( $sql );
    
    // Default options (avec vérification)
    if ( ! get_option( 'livraison_api_url' ) ) {
        add_option( 'livraison_api_url', 'https://api.sendi-api.com' );
    }
    if ( ! get_option( 'livraison_api_auto_send' ) ) {
        add_option( 'livraison_api_auto_send', 'yes' );
    }
    if ( ! get_option( 'livraison_api_auto_complete' ) ) {
        add_option( 'livraison_api_auto_complete', 'no' );
    }
    if ( ! get_option( 'livraison_api_pickup_commune' ) ) {
        add_option( 'livraison_api_pickup_commune', '' );
    }
    if ( ! get_option( 'livraison_api_pickup_address' ) ) {
        add_option( 'livraison_api_pickup_address', '' );
    }
    if ( ! get_option( 'livraison_api_merchant_name' ) ) {
        add_option( 'livraison_api_merchant_name', '' );
    }
    if ( ! get_option( 'livraison_api_merchant_phone' ) ) {
        add_option( 'livraison_api_merchant_phone', '' );
    }
    if ( ! get_option( 'livraison_api_merchant_email' ) ) {
        add_option( 'livraison_api_merchant_email', '' );
    }
    if ( ! get_option( 'livraison_api_delivery_mode' ) ) {
        add_option( 'livraison_api_delivery_mode', 'client_pays' );
    }
    if ( ! get_option( 'livraison_api_free_threshold' ) ) {
        add_option( 'livraison_api_free_threshold', 0 );
    }
    if ( ! get_option( 'livraison_api_currency' ) ) {
        add_option( 'livraison_api_currency', 'FCFA' );
    }
}

// Plugin Deactivation
register_deactivation_hook( __FILE__, 'livraison_api_deactivate' );
function livraison_api_deactivate() {
    // Cleanup if needed
}

// Initialize Plugin
function livraison_api_init() {
    if ( ! class_exists( 'WooCommerce' ) ) {
        add_action( 'admin_notices', function() {
            echo '<div class="notice notice-error"><p><strong>Livraison API:</strong> ' . esc_html__( 'WooCommerce is required.', 'sendi-api' ) . '</p></div>';
        } );
        return;
    }
    
    if ( class_exists( 'LivraisonAPI\\Admin' ) ) {
        new LivraisonAPI\Admin();
    }
    
    if ( class_exists( 'LivraisonAPI\\WooCommerce' ) ) {
        new LivraisonAPI\WooCommerce();
    }
    
    if ( class_exists( 'LivraisonAPI\\Shortcodes' ) ) {
        new LivraisonAPI\Shortcodes();
    }
    
    if ( class_exists( 'LivraisonAPI\\Ajax' ) ) {
        new LivraisonAPI\Ajax();
    }
    
    if ( class_exists( 'LivraisonAPI\\API' ) ) {
        new LivraisonAPI\API();
    }
}
add_action( 'plugins_loaded', 'livraison_api_init' );

// Register Shipping Method
add_action( 'woocommerce_shipping_init', function() {
    if ( ! class_exists( 'LivraisonAPI\\ShippingMethod' ) ) {
        require_once LIVRAISON_API_PLUGIN_DIR . 'includes/class-shipping-method.php';
    }
} );

add_filter( 'woocommerce_shipping_methods', function( $methods ) {
    $methods['livraison_api'] = 'LivraisonAPI\ShippingMethod';
    return $methods;
} );

// Enable Cash on Delivery
add_filter( 'woocommerce_available_payment_gateways', function( $gateways ) {
    if ( isset( $gateways['cod'] ) ) {
        $gateways['cod']->enabled = 'yes';
        $gateways['cod']->title = __( 'Cash on Delivery', 'sendi-api' );
        $gateways['cod']->description = __( 'Pay upon delivery (cash or mobile money)', 'sendi-api' );
        $gateways['cod']->instructions = __( 'Payment is made to the delivery driver upon receipt.', 'sendi-api' );
    }
    return $gateways;
}, 999 );

// Add custom shipping fields to checkout
// Add custom shipping fields to checkout
add_action( 'woocommerce_checkout_before_customer_details', 'livraison_api_custom_shipping_fields', 5 );
function livraison_api_custom_shipping_fields() {
    if ( ! class_exists( 'LivraisonAPI\\API' ) ) {
        return;
    }
    
    $api = new LivraisonAPI\API();
    $communes = $api->get_communes();

    // ✅ Récupérer la configuration des pays autorisés
    $allowed_countries = get_option( 'livraison_api_allowed_countries', array('CI') );
    $inter_country_enabled = get_option( 'livraison_api_inter_country_enabled', false );
    $commercant_country = get_option( 'livraison_api_commercant_country', 'CI' );
    $merchant_country = $commercant_country;
    $client_country_locked = !$inter_country_enabled;
    $default_client_country = $client_country_locked ? $merchant_country : 'CI';
    
    // ✅ Vérification du nonce WooCommerce
    $nonce_valid = false;
    if ( isset( $_POST['woocommerce-process-checkout-nonce'] ) && 
         wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['woocommerce-process-checkout-nonce'] ) ), 'woocommerce-process_checkout' ) ) {
        $nonce_valid = true;
    }

    // ✅ Récupération des valeurs existantes (pour pré-remplir)
    $shipping_full_name = '';
    $shipping_phone = '';
    $shipping_address = '';
    $livraison_commune = '';
    $shipping_instructions = '';
    $client_country = $default_client_country;
    
    if ( $nonce_valid ) {
        $shipping_full_name = isset( $_POST['shipping_full_name'] ) ? sanitize_text_field( wp_unslash( $_POST['shipping_full_name'] ) ) : '';
        $shipping_phone = isset( $_POST['shipping_phone'] ) ? sanitize_text_field( wp_unslash( $_POST['shipping_phone'] ) ) : '';
        $shipping_address = isset( $_POST['shipping_address'] ) ? sanitize_text_field( wp_unslash( $_POST['shipping_address'] ) ) : '';
        $livraison_commune = isset( $_POST['livraison_commune'] ) ? sanitize_text_field( wp_unslash( $_POST['livraison_commune'] ) ) : '';
        $shipping_instructions = isset( $_POST['shipping_instructions'] ) ? sanitize_textarea_field( wp_unslash( $_POST['shipping_instructions'] ) ) : '';
        $client_country = isset( $_POST['client_country'] ) ? sanitize_text_field( wp_unslash( $_POST['client_country'] ) ) : $default_client_country;
    }

    // ✅ Filtrer les communes par pays
    $filtered_communes = array();
    $available_countries_list = $allowed_countries;

    if ( ! $inter_country_enabled ) {
        foreach ( $communes['data'] as $commune ) {
            $commune_country = isset( $commune['countryCode'] ) ? $commune['countryCode'] : 'CI';
            if ( $commune_country === $merchant_country ) {
                $filtered_communes[] = $commune;
            }
        }
    } else {
        foreach ( $communes['data'] as $commune ) {
            $commune_country = isset( $commune['countryCode'] ) ? $commune['countryCode'] : 'CI';
            if ( in_array( $commune_country, $allowed_countries ) ) {
                $filtered_communes[] = $commune;
            }
        }
    }
    
    if ( empty( $filtered_communes ) ) {
        $filtered_communes = $communes['data'];
    }

    global $AVAILABLE_COUNTRIES;
    ?>
    <div class="livraison-shipping-fields" data-pickup-commune="<?php echo esc_attr( get_option( 'livraison_api_pickup_commune', 'Cocody' ) ); ?>">
        <h3><?php esc_html_e( 'Delivery Information', 'sendi-api' ); ?></h3>
        
        <!-- ✅ RECIPIENT FULL NAME -->
        <div class="form-row form-row-wide">
            <label for="shipping_full_name">
                <?php esc_html_e( 'Recipient Full Name', 'sendi-api' ); ?>
                <span class="required">*</span>
            </label>
            <input type="text" 
                   id="shipping_full_name" 
                   name="shipping_full_name" 
                   class="input-text" 
                   value="<?php echo esc_attr( $shipping_full_name ); ?>"
                   placeholder="<?php esc_attr_e( 'Enter recipient full name', 'sendi-api' ); ?>" />
        </div>
        
        <!-- ✅ RECIPIENT PHONE -->
        <div class="form-row form-row-wide">
            <label for="shipping_phone">
                <?php esc_html_e( 'Recipient Phone', 'sendi-api' ); ?>
                <span class="required">*</span>
            </label>
            <input type="tel" 
                   id="shipping_phone" 
                   name="shipping_phone" 
                   class="input-text" 
                   value="<?php echo esc_attr( $shipping_phone ); ?>"
                   placeholder="<?php esc_attr_e( 'Enter recipient phone number', 'sendi-api' ); ?>" />
        </div>
        
        <!-- ✅ DELIVERY ADDRESS -->
        <div class="form-row form-row-wide">
            <label for="shipping_address">
                <?php esc_html_e( 'Delivery Address', 'sendi-api' ); ?>
                <span class="required">*</span>
            </label>
            <input type="text" 
                   id="shipping_address" 
                   name="shipping_address" 
                   class="input-text" 
                   value="<?php echo esc_attr( $shipping_address ); ?>"
                   placeholder="<?php esc_attr_e( 'Enter delivery address', 'sendi-api' ); ?>" />
        </div>
        
        <!-- Client Country -->
        <div class="form-row form-row-wide">
            <label for="client_country">
                <?php esc_html_e( 'Client Country', 'sendi-api' ); ?>
                <span class="required">*</span>
                <?php if ( $client_country_locked ) : ?>
                    <small style="color: #6b7280; font-size: 11px;">(verrouillé)</small>
                <?php endif; ?>
            </label>
            <?php if ( $client_country_locked ) : ?>
                <input type="hidden" name="client_country" value="<?php echo esc_attr( $merchant_country ); ?>" />
                <input type="text" 
                       class="input-text" 
                       value="<?php echo esc_attr( isset( $AVAILABLE_COUNTRIES[ $merchant_country ] ) ? $AVAILABLE_COUNTRIES[ $merchant_country ] : $merchant_country ); ?>"
                       disabled="disabled"
                       style="background-color: #f3f4f6; cursor: not-allowed; color: #6b7280;" />
            <?php else : ?>
                <select id="client_country" name="client_country" class="input-text">
                    <option value=""><?php esc_html_e( 'Select a country', 'sendi-api' ); ?></option>
                    <?php 
                    foreach ( $available_countries_list as $country_code ) {
                        $country_name = isset( $AVAILABLE_COUNTRIES[ $country_code ] ) ? $AVAILABLE_COUNTRIES[ $country_code ] : $country_code;
                        echo '<option value="' . esc_attr( $country_code ) . '"' . selected( $client_country, $country_code, false ) . '>';
                        echo esc_html( $country_name );
                        echo '</option>';
                    }
                    ?>
                </select>
            <?php endif; ?>
        </div>
        
        <!-- Delivery Commune (filtrée par pays) -->
        <div class="form-row form-row-wide">
            <label for="livraison_commune">
                <?php esc_html_e( 'Delivery Commune', 'sendi-api' ); ?>
                <span class="required">*</span>
            </label>
            <select id="livraison_commune" name="livraison_commune" class="input-text">
                <option value=""><?php esc_html_e( 'Select your commune', 'sendi-api' ); ?></option>
                <?php
                if ( $communes['success'] && ! empty( $filtered_communes ) ) {
                    foreach ( $filtered_communes as $commune ) {
                        $selected = selected( $livraison_commune, $commune['name'], false );
						echo '<option value="' . esc_attr($commune['name']) . '"' . selected($livraison_commune, $commune['name'], false) . '>';
                        echo esc_html( $commune['name'] );
                        if ( ! empty( $commune['city'] ) ) {
                            echo ' (' . esc_html( $commune['city'] ) . ')';
                        }
                        echo '</option>';
                    }
                }
                ?>
            </select>
            <small><?php esc_html_e( 'Select your commune to calculate the estimated delivery price.', 'sendi-api' ); ?></small>
        </div>
        
        <div id="livraison-price-display">
            <p>
                <strong><?php esc_html_e( 'Estimated delivery price:', 'sendi-api' ); ?></strong>
                <span id="livraison-price-amount">0 FCFA</span>
            </p>
            <p class="price-hint"><?php esc_html_e( 'Payment upon delivery.', 'sendi-api' ); ?></p>
        </div>
        
        <div class="form-row form-row-wide">
            <label for="shipping_instructions">
                <?php esc_html_e( 'Delivery Instructions', 'sendi-api' ); ?>
            </label>
            <textarea id="shipping_instructions" 
                      name="shipping_instructions" 
                      class="input-text" 
                      placeholder="<?php esc_attr_e( 'Ring the bell, access code, etc.', 'sendi-api' ); ?>"><?php echo esc_textarea( $shipping_instructions ); ?></textarea>
        </div>
    </div>
    <?php
}

// AJAX - Calculate Price
add_action( 'wp_ajax_livraison_calculate_price', 'livraison_ajax_calculate_price' );
add_action( 'wp_ajax_nopriv_livraison_calculate_price', 'livraison_ajax_calculate_price' );

// AJAX - Track Order
add_action( 'wp_ajax_livraison_track_order', 'livraison_ajax_track_order' );

// AJAX - TEST API CONNECTION
add_action( 'wp_ajax_livraison_test_api', 'livraison_ajax_test_api' );

function livraison_ajax_test_api() {
    if ( ! check_ajax_referer( 'livraison_api_nonce', 'nonce', false ) ) {
        wp_send_json_error( array( 'message' => 'Invalid nonce' ) );
        return;
    }
    
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_send_json_error( array( 'message' => 'Unauthorized' ) );
        return;
    }
    
    $api = new LivraisonAPI\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
add_action( 'wp_ajax_livraison_save_merchant', 'livraison_ajax_save_merchant' );

function livraison_ajax_save_merchant() {
    if ( ! check_ajax_referer( 'livraison_api_nonce', 'nonce', false ) ) {
        wp_send_json_error( array( 'message' => 'Invalid nonce' ) );
        return;
    }
    
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_send_json_error( array( 'message' => 'Unauthorized' ) );
        return;
    }
    
    $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'] ) ) : '';
    
    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
        )
    ) );
}

function livraison_ajax_track_order() {
    if ( ! check_ajax_referer( 'livraison_track_nonce', 'nonce', false ) ) {
        wp_send_json_error( 'Invalid nonce' );
    }
    
    $course_id = isset( $_POST['course_id'] ) ? sanitize_text_field( wp_unslash( $_POST['course_id'] ) ) : '';
    
    if ( empty( $course_id ) ) {
        wp_send_json_error( 'No course ID provided' );
    }
    
    $api = new LivraisonAPI\API();
    $result = $api->get_order_status( $course_id );
    
    if ( ! $result['success'] || empty( $result['data'] ) ) {
        wp_send_json_error( 'Unable to track order' );
    }
    
    $data = $result['data'];
    $steps = array();
    
    $status_labels = array(
        'pending' => __( 'Order Created', 'sendi-api' ),
        'assigned' => __( 'Assigned to Agency', 'sendi-api' ),
        'in_progress' => __( 'In Progress', 'sendi-api' ),
        'delivered' => __( 'Delivered', 'sendi-api' ),
        'cancelled' => __( 'Cancelled', 'sendi-api' ),
        'failed' => __( 'Failed', 'sendi-api' )
    );
    
    $current_status = $data['status'] ?? 'pending';
    $status_order = array( 'pending', 'assigned', 'in_progress', 'delivered', 'cancelled', 'failed' );
    
    $current_index = array_search( $current_status, $status_order );
    if ( $current_index === false ) {
        $current_index = 0;
    }
    
    for ( $i = 0; $i <= $current_index; $i++ ) {
        $status = $status_order[ $i ];
        $is_completed = ( $i < $current_index ) || 
                        in_array( $status, array( 'delivered', 'cancelled', 'failed' ) );
        $is_active = ( $i === $current_index ) && ! in_array( $status, array( 'delivered', 'cancelled', 'failed' ) );
        
        $step = array(
            'label' => $status_labels[ $status ] ?? ucfirst( $status ),
            'date' => null,
            'completed' => $is_completed,
            'active' => $is_active
        );
        
        if ( $status === 'pending' && isset( $data['createdAt'] ) ) {
            $step['date'] = date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), strtotime( $data['createdAt'] ) );
        } elseif ( $status === 'assigned' && isset( $data['assignedAt'] ) ) {
            $step['date'] = date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), strtotime( $data['assignedAt'] ) );
        } elseif ( $status === 'in_progress' && isset( $data['inProgressAt'] ) ) {
            $step['date'] = date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), strtotime( $data['inProgressAt'] ) );
        } elseif ( $status === 'delivered' && isset( $data['deliveredAt'] ) ) {
            $step['date'] = date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), strtotime( $data['deliveredAt'] ) );
        } elseif ( $status === 'cancelled' && isset( $data['cancelledAt'] ) ) {
            $step['date'] = date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), strtotime( $data['cancelledAt'] ) );
        }
        
        $steps[] = $step;
    }
    
    wp_send_json_success( array( 'steps' => $steps ) );
}

function livraison_ajax_calculate_price() {
    // ✅ Activer les logs pour debug
    livraison_api_log( '========================================', 'info' );
    livraison_api_log( '📊 AJAX Price Calculation Started', 'info' );
    
    // ✅ Vérifier le nonce
    if ( ! check_ajax_referer( 'livraison_price_nonce', 'nonce', false ) ) {
        livraison_api_log( '❌ Invalid nonce', 'error' );
        wp_send_json_error( 'Invalid nonce' );
        return;
    }
    
    // ✅ Récupérer les paramètres
    $pickup_commune = isset( $_POST['pickup_commune'] ) ? sanitize_text_field( wp_unslash( $_POST['pickup_commune'] ) ) : '';
    $client_commune = isset( $_POST['client_commune'] ) ? sanitize_text_field( wp_unslash( $_POST['client_commune'] ) ) : '';
    $payer_type = isset( $_POST['payer_type'] ) ? sanitize_text_field( wp_unslash( $_POST['payer_type'] ) ) : 'client';
    $order_total = isset( $_POST['order_total'] ) ? floatval( $_POST['order_total'] ) : 0;
    $free_threshold = floatval( get_option( 'livraison_api_free_threshold', 0 ) );
    $delivery_mode = get_option( 'livraison_api_delivery_mode', 'client_pays' );
    
    livraison_api_log( '📊 Params - pickup: ' . $pickup_commune . ', client: ' . $client_commune . ', payer: ' . $payer_type, 'info' );
    livraison_api_log( '📊 Delivery mode: ' . $delivery_mode . ', threshold: ' . $free_threshold . ', order total: ' . $order_total, 'info' );
    
    if ( empty( $pickup_commune ) || empty( $client_commune ) ) {
        livraison_api_log( '❌ Missing communes', 'error' );
        wp_send_json_error( 'Missing communes' );
        return;
    }
    
    // ✅ Vérifier la clé API
    $api_key = get_option( 'livraison_api_key', '' );
    if ( empty( $api_key ) ) {
        livraison_api_log( '❌ API key missing', 'error' );
        wp_send_json_error( 'API key not configured' );
        return;
    }
    
    livraison_api_log( '✅ API Key configured (length: ' . strlen( $api_key ) . ')', 'info' );
    
    // ✅ DÉTERMINER SI LA LIVRAISON EST GRATUITE
    $is_free_delivery = false;
    $free_delivery_reason = 'none';
    
    // Mode 1: Le commerçant paie toujours (livraison gratuite)
    if ( $delivery_mode === 'merchant_pays' ) {
        $is_free_delivery = true;
        $free_delivery_reason = 'merchant_pays';
        livraison_api_log( '✅ Free delivery: merchant pays all', 'info' );
    }
    // Mode 2: Seuil de livraison gratuite
    elseif ( $delivery_mode === 'threshold' && $free_threshold > 0 && $order_total >= $free_threshold ) {
        $is_free_delivery = true;
        $free_delivery_reason = 'threshold_reached';
        livraison_api_log( '✅ Free delivery: threshold reached (' . $order_total . ' >= ' . $free_threshold . ')', 'info' );
    }
    // Mode 3: payer_type spécifié comme commerçant
    elseif ( $payer_type === 'commercant' ) {
        $is_free_delivery = true;
        $free_delivery_reason = 'payer_commercant';
        livraison_api_log( '✅ Free delivery: merchant pays (payer_type=commercant)', 'info' );
    }
    
    // ✅ SI LIVRAISON GRATUITE, retourner directement
    if ( $is_free_delivery ) {
        wp_send_json_success( array(
            'price' => '0',
            'raw_price' => 0,
            'pickup_commune' => $pickup_commune,
            'client_commune' => $client_commune,
            'is_same_commune' => $pickup_commune === $client_commune,
            'payer_type' => 'commercant',
            'is_free' => true,
            'free_reason' => $free_delivery_reason,
            'agence_id' => null,
            'agence_name' => 'Livraison gratuite'
        ) );
        return;
    }
    
    // ✅ Appel API pour obtenir le prix normal (le client paie)
    try {
        $api = new LivraisonAPI\API();
        $agences_response = $api->get_available_agences( $pickup_commune, $pickup_commune, $client_commune );
        
        livraison_api_log( '📡 API Response success: ' . ( $agences_response['success'] ? 'true' : 'false' ), 'info' );
        livraison_api_log( '📡 Status code: ' . ( $agences_response['status_code'] ?? 'N/A' ), 'info' );
        
        if ( ! $agences_response['success'] || empty( $agences_response['data']['agences'] ) ) {
            livraison_api_log( '❌ No agency available', 'error' );
            if ( isset( $agences_response['error'] ) ) {
                livraison_api_log( '❌ API Error: ' . $agences_response['error'], 'error' );
            }
            if ( isset( $agences_response['raw_response'] ) ) {
                livraison_api_log( '❌ Raw response: ' . substr( $agences_response['raw_response'], 0, 500 ), 'error' );
            }
            wp_send_json_error( 'No agency available for this commune' );
            return;
        }
        
        $agences = $agences_response['data']['agences'];
        livraison_api_log( '📊 ' . count( $agences ) . ' agences trouvées', 'info' );
        
        // ✅ Trouver la meilleure agence (même logique que le backend)
        // PRIORITÉ 1: Pickup + Solde suffisant
        $covering_agences = array_filter( $agences, function( $agence ) use ( $pickup_commune ) {
            return in_array( $pickup_commune, $agence['communes'] ?? [] );
        } );
        
        // PRIORITÉ 2: Pickup seulement
        if ( empty( $covering_agences ) ) {
            $covering_agences = $agences;
        }
        
        // Trier par solde (le plus élevé d'abord)
        usort( $covering_agences, function( $a, $b ) {
            return ( $b['solde'] ?? 0 ) - ( $a['solde'] ?? 0 );
        } );
        
        $best_agence = $covering_agences[0] ?? null;
        
        if ( ! $best_agence ) {
            livraison_api_log( '❌ No best agency found', 'error' );
            wp_send_json_error( 'No agency available' );
            return;
        }
        
        // ✅ Calculer le prix
        $is_same_commune = $pickup_commune === $client_commune;
        $price = 0;
        
        if ( $is_same_commune ) {
            $price = $best_agence['deliveryPriceSame'] ?? 1500;
        } else {
            $price = $best_agence['deliveryPriceDifferent'] ?? 2000;
        }
        
        // ✅ Récupérer la commission
        $commission_rate = $best_agence['commissionRate'] ?? 18;
        $commission_mode = $best_agence['commissionMode'] ?? 'percentage';
        $commission_amount = 0;
        
        if ( $commission_mode === 'percentage' ) {
            $commission_amount = ( $price * $commission_rate ) / 100;
        } else {
            $commission_amount = $is_same_commune ? 
                ( $best_agence['fixedCommissionSame'] ?? 0 ) : 
                ( $best_agence['fixedCommissionDifferent'] ?? 0 );
        }
        
        livraison_api_log( '✅ Price: ' . $price . ' FCFA (same: ' . ( $is_same_commune ? 'yes' : 'no' ) . ')', 'info' );
        livraison_api_log( '✅ Agency: ' . ( $best_agence['companyName'] ?? 'Unknown' ), 'info' );
        livraison_api_log( '✅ Commission: ' . $commission_amount . ' FCFA (mode: ' . $commission_mode . ')', 'info' );
        
        wp_send_json_success( array(
            'price' => number_format( $price, 0, ',', ' ' ),
            'raw_price' => $price,
            'pickup_commune' => $pickup_commune,
            'client_commune' => $client_commune,
            'is_same_commune' => $is_same_commune,
            'payer_type' => 'client',
            'is_free' => false,
            'free_reason' => 'none',
            'agence_id' => $best_agence['id'] ?? null,
            'agence_name' => $best_agence['companyName'] ?? 'Agency',
            'commission_amount' => $commission_amount,
            'commission_rate' => $commission_rate,
            'commission_mode' => $commission_mode
        ) );
        
    } catch ( Exception $e ) {
        livraison_api_log( '❌ Exception: ' . $e->getMessage(), 'error' );
        livraison_api_log( '❌ Stack: ' . $e->getTraceAsString(), 'error' );
        wp_send_json_error( $e->getMessage() );
    }
}

// ✅ GARDER CELUI-CI (avec les logs)
add_action( 'woocommerce_checkout_create_order', function( $order, $data ) {
    if ( ! isset( $_POST['woocommerce-process-checkout-nonce'] ) || 
         ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['woocommerce-process-checkout-nonce'] ) ), 'woocommerce-process_checkout' ) ) {
        return;
    }

    // ✅ Sauvegarder TOUS les champs de livraison
    $fields_to_save = array(
        'shipping_full_name' => '_shipping_full_name',
        'shipping_phone' => '_shipping_phone',
        'shipping_address' => '_shipping_address',
        'shipping_instructions' => '_shipping_instructions',
        'livraison_commune' => '_livraison_commune',
        'client_country' => '_client_country',
        'merchant_country' => '_merchant_country'
    );
    
    foreach ( $fields_to_save as $post_key => $meta_key ) {
        if ( isset( $_POST[ $post_key ] ) ) {
            $value = sanitize_text_field( wp_unslash( $_POST[ $post_key ] ) );
            $order->update_meta_data( $meta_key, $value );
            livraison_api_log( '✅ Saved ' . $meta_key . ': ' . $value, 'info' );
        }
    }
    
    $order->update_meta_data( '_livraison_paiement_arrivee', 'yes' );
    $order->update_meta_data( '_livraison_frais_arrivee', true );
    
    livraison_api_log( '✅ Order meta saved for order ' . $order->get_id(), 'info' );
}, 10, 2 );

// Créer la table manuellement
function livraison_api_create_table() {
    global $wpdb;
    
    $table_name = $wpdb->prefix . 'livraison_api_logs';
    $charset_collate = $wpdb->get_charset_collate();
    
    $sql = "CREATE TABLE IF NOT EXISTS $table_name (
        id bigint(20) NOT NULL AUTO_INCREMENT,
        order_id bigint(20) NOT NULL,
        course_id varchar(255) NOT NULL,
        code_secret varchar(255) NOT NULL,
        status varchar(50) DEFAULT 'created',
        price decimal(10,2) DEFAULT 0.00,
        client_name varchar(255) DEFAULT NULL,
        client_phone varchar(50) DEFAULT NULL,
        client_address text DEFAULT NULL,
        client_commune varchar(100) DEFAULT NULL,
        merchant_name varchar(255) DEFAULT NULL,
        merchant_phone varchar(50) DEFAULT NULL,
        merchant_email varchar(255) DEFAULT NULL,
        agence_name varchar(255) DEFAULT NULL,
        agence_phone varchar(50) DEFAULT NULL,
        agence_email varchar(255) DEFAULT NULL,
        payer_type varchar(20) DEFAULT 'client',
        is_free tinyint(1) DEFAULT 0,
        free_reason varchar(50) DEFAULT NULL,
        created_at datetime DEFAULT CURRENT_TIMESTAMP,
        updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        KEY order_id (order_id),
        KEY course_id (course_id)
    ) $charset_collate;";
    
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
    
livraison_api_log('✅ Table livraison_api_logs créée avec succès', 'info');
}




// Log function
function livraison_api_log( $message, $type = 'info' ) {
    $upload_dir = wp_upload_dir();
    $log_dir = $upload_dir['basedir'] . '/sendi-api-logs/';
    
    if ( ! file_exists( $log_dir ) ) {
        wp_mkdir_p( $log_dir );
    }
    
    $log_file = $log_dir . 'sendi-api.log';
    $timestamp = gmdate( 'Y-m-d H:i:s' );
    $log_entry = "[$timestamp] [$type] $message" . PHP_EOL;
    file_put_contents( $log_file, $log_entry, FILE_APPEND );
}

// Send Order to API
add_action( 'woocommerce_order_status_processing', 'livraison_api_send_order', 10, 2 );
add_action( 'woocommerce_order_status_completed', 'livraison_api_send_order', 10, 2 );
add_action( 'woocommerce_thankyou', 'livraison_api_send_order_from_thankyou', 10, 1 );

/**
 * Enqueue admin assets for settings page
 */
add_action( 'admin_enqueue_scripts', 'livraison_api_admin_enqueue_settings' );
function livraison_api_admin_enqueue_settings( $hook ) {
    // Vérifier que nous sommes sur la page des paramètres SendiAPI
    if ( 'sendi-api_page_sendi-api-settings' !== $hook && 'toplevel_page_sendi-api-settings' !== $hook ) {
        return;
    }
    
    // Enqueue CSS
    wp_enqueue_style(
        'livraison-admin-settings',
        LIVRAISON_API_PLUGIN_URL . 'assets/css/admin-settings.css',
        array(),
        LIVRAISON_API_VERSION
    );
    
    // Enqueue JS
    wp_enqueue_script(
        'livraison-admin-settings',
        LIVRAISON_API_PLUGIN_URL . 'assets/js/admin-settings.js',
        array( 'jquery' ),
        LIVRAISON_API_VERSION,
        true
    );
    
    // Localize script for translations and settings
    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' ),
            )
        )
    );
}

/**
 * Enqueue admin assets for orders page
 */
add_action( 'admin_enqueue_scripts', 'livraison_api_admin_enqueue_orders' );
function livraison_api_admin_enqueue_orders( $hook ) {
    if ( 'sendi-api_page_sendi-api-orders' !== $hook && 'toplevel_page_sendi-api-orders' !== $hook ) {
        return;
    }
    
    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' ),
            )
        )
    );
}


/**
 * Enqueue admin assets for dashboard page
 */
add_action( 'admin_enqueue_scripts', 'livraison_api_admin_enqueue_dashboard' );
function livraison_api_admin_enqueue_dashboard( $hook ) {
    if ( 'toplevel_page_sendi-api-dashboard' !== $hook && 'sendi-api_page_sendi-api-dashboard' !== $hook ) {
        return;
    }
    
    wp_enqueue_style(
        'livraison-admin-dashboard',
        LIVRAISON_API_PLUGIN_URL . 'assets/css/admin-dashboard.css',
        array(),
        LIVRAISON_API_VERSION
    );
}

/**
 * Enqueue frontend assets
 */
add_action( 'wp_enqueue_scripts', 'livraison_api_frontend_enqueue_scripts' );
function livraison_api_frontend_enqueue_scripts() {
    // Enqueue CSS
    wp_enqueue_style(
        'livraison-frontend',
        LIVRAISON_API_PLUGIN_URL . 'assets/css/frontend.css',
        array(),
        LIVRAISON_API_VERSION
    );
    
    // Enqueue JS pour le frontend (checkout)
    if ( is_checkout() || is_cart() || is_shop() ) {
        wp_enqueue_script(
            'livraison-frontend',
            LIVRAISON_API_PLUGIN_URL . 'assets/js/frontend.js',
            array( 'jquery' ),
            LIVRAISON_API_VERSION,
            true
        );
        
        wp_localize_script(
            'livraison-frontend',
            'livraisonFrontend',
            array(
                'ajaxUrl' => admin_url( 'admin-ajax.php' ),
                'priceNonce' => wp_create_nonce( 'livraison_price_nonce' ),
                'l10n' => array(
                    'calculating' => __( 'Calculating...', 'sendi-api' ),
                    'error' => __( 'Error', 'sendi-api' ),
                    'connectionError' => __( 'Connection error', 'sendi-api' ),
                    'selectCommune' => __( 'Select your commune', 'sendi-api' ),
                )
            )
        );
    }
}

function livraison_api_send_order( $order_id, $order ) {
    if ( ! $order_id || ! $order ) {
        return;
    }
    
    if ( get_option( 'livraison_api_auto_send', 'yes' ) !== 'yes' ) {
        livraison_api_log( 'Auto-send disabled', 'warning' );
        return;
    }
    
    $existing_course = $order->get_meta( '_livraison_course_id' );
    if ( $existing_course ) {
        livraison_api_log( 'Order already sent: ' . $existing_course, 'warning' );
        return;
    }
    
    // ✅ Récupérer la configuration de livraison
    $delivery_mode = get_option( 'livraison_api_delivery_mode', 'client_pays' );
    $free_threshold = floatval( get_option( 'livraison_api_free_threshold', 0 ) );
    $order_total = $order->get_total();
    
    // ✅ Déterminer qui paie les frais de livraison
    $payer_type = 'client';
    $is_free_delivery = false;
    
    livraison_api_log( '========================================', 'info' );
    livraison_api_log( '📦 Delivery Mode: ' . $delivery_mode, 'info' );
    livraison_api_log( '💰 Order Total: ' . $order_total . ' FCFA', 'info' );
    
    switch ( $delivery_mode ) {
        case 'client_pays':
            $payer_type = 'client';
            $is_free_delivery = false;
            livraison_api_log( '👤 Customer pays for delivery', 'info' );
            break;
            
        case 'merchant_pays':
            $payer_type = 'commercant';
            $is_free_delivery = true;
            livraison_api_log( '🏪 Merchant pays (free delivery)', 'info' );
            break;
            
        case 'threshold':
            if ( $free_threshold > 0 && $order_total >= $free_threshold ) {
                $payer_type = 'commercant';
                $is_free_delivery = true;
                livraison_api_log( '🎯 Free delivery (threshold reached: ' . $order_total . ' >= ' . $free_threshold . ')', 'info' );
            } else {
                $payer_type = 'client';
                $is_free_delivery = false;
                livraison_api_log( '👤 Customer pays (threshold not reached: ' . $order_total . ' < ' . $free_threshold . ')', 'info' );
            }
            break;
            
        default:
            $payer_type = 'client';
            $is_free_delivery = false;
            livraison_api_log( '⚠️ Unknown mode, default to customer pays', 'warning' );
            break;
    }
    
    // ✅ Récupérer les autres infos
    $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', 'Cocody' );
    
    if ( empty( $pickup_commune ) ) {
        $pickup_commune = 'Cocody';
        livraison_api_log( 'Pickup commune missing, fallback: ' . $pickup_commune, 'warning' );
    }
    
    livraison_api_log( 'Merchant info (admin):', 'info' );
    livraison_api_log( '   - Store Name: ' . $merchant_name, 'info' );
    livraison_api_log( '   - Phone: ' . $merchant_phone, 'info' );
    livraison_api_log( '   - Email: ' . $merchant_email, 'info' );
    livraison_api_log( '   - Pickup Address: ' . $pickup_address, 'info' );
    livraison_api_log( '   - Pickup Commune: ' . $pickup_commune, 'info' );
    
    $client_name = $order->get_meta( '_shipping_full_name' );
    if ( empty( $client_name ) ) {
        $client_name = trim( $order->get_billing_first_name() . ' ' . $order->get_billing_last_name() );
    }
    if ( empty( $client_name ) ) {
        $client_name = 'Unknown Client';
        livraison_api_log( 'Client name missing, fallback: ' . $client_name, 'warning' );
    }
    
    $client_phone = $order->get_meta( '_shipping_phone' );
    if ( empty( $client_phone ) ) {
        $client_phone = $order->get_billing_phone();
    }
    if ( empty( $client_phone ) ) {
        $client_phone = '0708091011';
        livraison_api_log( 'Client phone missing, fallback: ' . $client_phone, 'warning' );
    }
    
    $client_address = $order->get_meta( '_shipping_address' );
    if ( empty( $client_address ) ) {
        $client_address = $order->get_shipping_address_1();
    }
    if ( empty( $client_address ) ) {
        $client_address = $order->get_billing_address_1();
    }
    if ( empty( $client_address ) ) {
        $client_address = 'Address not specified';
        livraison_api_log( 'Client address missing, fallback: ' . $client_address, 'warning' );
    }
    
    $client_commune = $order->get_meta( '_livraison_commune' );
    if ( empty( $client_commune ) ) {
        $client_commune = $order->get_shipping_city();
    }
    if ( empty( $client_commune ) ) {
        $client_commune = $order->get_billing_city();
    }
    if ( empty( $client_commune ) ) {
        $client_commune = 'Cocody';
        livraison_api_log( 'Client commune missing, fallback: ' . $client_commune, 'warning' );
    }
    
    livraison_api_log( 'Client data:', 'info' );
    livraison_api_log( '   - Name: ' . $client_name, 'info' );
    livraison_api_log( '   - Phone: ' . $client_phone, 'info' );
    livraison_api_log( '   - Address: ' . $client_address, 'info' );
    livraison_api_log( '   - Commune: ' . $client_commune, 'info' );
    
    $price = 0;
    $agence_id = '';
    $agence_name = '';
    $agence_phone = '';
    $agence_email = '';
    
    $api = new LivraisonAPI\API();
    $agences_response = $api->get_available_agences( $pickup_commune, $pickup_commune, $client_commune );
    
    if ( $agences_response['success'] && ! empty( $agences_response['data']['agences'] ) ) {
        $agences = $agences_response['data']['agences'];
        
        $covering = array_filter( $agences, function( $a ) use ( $pickup_commune ) {
            return in_array( $pickup_commune, $a['communes'] ?? [] );
        } );
        
        $best = ! empty( $covering ) ? reset( $covering ) : reset( $agences );
        
        if ( $best ) {
            $is_same = $pickup_commune === $client_commune;
            $price = $is_same ? ( $best['deliveryPriceSame'] ?? 1500 ) : ( $best['deliveryPriceDifferent'] ?? 2000 );
            $agence_id = $best['id'] ?? '';
            $agence_name = $best['companyName'] ?? '';
            $agence_phone = $best['phone'] ?? $best['phoneNumber'] ?? '';
            $agence_email = $best['email'] ?? '';
            
            livraison_api_log( '💰 Price: ' . $price . ' FCFA', 'info' );
            livraison_api_log( '🏢 Agency: ' . $agence_name, 'info' );
        }
    } else {
        // Fallback si aucune agence trouvée
        $price = 2000;
        $agence_id = '1';
        $agence_name = 'Default Agency';
        livraison_api_log( '⚠️ No agency found, using default price: ' . $price, 'warning' );
    }
    
    if ( $is_free_delivery ) {
        livraison_api_log( '✅ Free delivery: price ' . $price . ' FCFA paid by merchant', 'info' );
    }
    
    // ✅ Construction des données avec payerType
    $order_data = array(
        'clientName' => trim( $client_name ),
        'clientPhone' => trim( $client_phone ),
        'clientAddress' => trim( $client_address ),
        'clientCommune' => trim( $client_commune ),
        'pickupAddress' => trim( $pickup_address ),
        'pickupCommune' => trim( $pickup_commune ),
        'phonecommercant' => trim( $merchant_phone ),
        'merchantName' => trim( $merchant_name ),
        'merchantPhone' => trim( $merchant_phone ),
        'merchantEmail' => trim( $merchant_email ),
        'price' => floatval( $price ),
        'agenceId' => trim( $agence_id ),
        'agenceName' => trim( $agence_name ),
        'commissionMode' => 'percentage',
        'commissionRate' => 18,
        'commissionAmount' => ( floatval( $price ) * 18 ) / 100,
        'payerType' => $payer_type,
        'isFreeDelivery' => $is_free_delivery,
        'freeDeliveryReason' => $is_free_delivery ? $delivery_mode : 'none'
    );
    
    livraison_api_log( '📤 Payer: ' . $payer_type, 'info' );
    livraison_api_log( '📤 Free delivery: ' . ( $is_free_delivery ? 'YES' : 'NO' ), 'info' );
    livraison_api_log( '📤 Price: ' . $price . ' FCFA', 'info' );
    livraison_api_log( '📤 Data sent: ' . json_encode( $order_data, JSON_PRETTY_PRINT ), 'info' );
    $result = $api->create_order( $order_data );
    
    livraison_api_log( 'Response status: ' . ( $result['status_code'] ?? 'N/A' ), 'info' );
    
    if ( $result['success'] && ! empty( $result['data'] ) ) {
        $course_id = $result['data']['courseId'] ?? '';
        $code_secret = $result['data']['codeSecret'] ?? '';
        $price_sent = $result['data']['price'] ?? 0;
        
        $response_data = $result['data'];
        $agence_name_from_api = $response_data['agenceName'] ?? $agence_name;
        $agence_phone_from_api = $response_data['agencePhone'] ?? $agence_phone;
        $agence_email_from_api = $response_data['agenceEmail'] ?? $agence_email;
        
        $order->update_meta_data( '_livraison_course_id', $course_id );
        $order->update_meta_data( '_livraison_code_secret', $code_secret );
        $order->update_meta_data( '_livraison_sent_at', current_time( 'mysql' ) );
        $order->update_meta_data( '_livraison_merchant_name', $merchant_name );
        $order->update_meta_data( '_livraison_merchant_phone', $merchant_phone );
        $order->update_meta_data( '_livraison_merchant_email', $merchant_email );
        $order->update_meta_data( '_livraison_agence_name', $agence_name_from_api );
        $order->update_meta_data( '_livraison_agence_phone', $agence_phone_from_api );
        $order->update_meta_data( '_livraison_agence_email', $agence_email_from_api );
        $order->update_meta_data( '_livraison_estimated_price', floatval( $price_sent ) );
        $order->update_meta_data( '_livraison_order_total', $order->get_total() );
        
        $order->update_meta_data( '_livraison_payer_type', $payer_type );
        $order->update_meta_data( '_livraison_is_free', $is_free_delivery );
        $order->update_meta_data( '_livraison_free_reason', $is_free_delivery ? $delivery_mode : 'none' );
        
        $order->add_order_note( sprintf(
            'Order sent to SendiAPI - Course #%s, Secret Code: %s, Price: %s FCFA, Store: %s, Agency: %s',
            $course_id,
            $code_secret,
            number_format( $price_sent, 0, ',', ' ' ),
            $merchant_name,
            $agence_name_from_api
        ) );
        $order->save();
        
        livraison_api_log( 'Send successful - Course ID: ' . $course_id . ', Code: ' . $code_secret, 'success' );
        
        global $wpdb;
$table_name = $wpdb->prefix . 'livraison_api_logs';

// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
$insert_result = $wpdb->insert(
    $table_name,
    array(
        'order_id' => $order_id,
        'course_id' => $course_id,
        'code_secret' => $code_secret,
        'status' => 'sent',
        'price' => floatval( $price_sent ),
        'client_name' => $client_name,
        'client_phone' => $client_phone,
        'client_address' => $client_address,
        'client_commune' => $client_commune,
        'merchant_name' => $merchant_name,
        'merchant_phone' => $merchant_phone,
        'merchant_email' => $merchant_email,
        'agence_name' => $agence_name_from_api,
        'agence_phone' => $agence_phone_from_api,
        'agence_email' => $agence_email_from_api,
        'payer_type' => $payer_type,
        'is_free' => $is_free_delivery ? 1 : 0,
        'free_reason' => $is_free_delivery ? $delivery_mode : 'none'
    ),
    array( '%d', '%s', '%s', '%s', '%f', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%s' )
);
        
        if ( false === $insert_result ) {
            $error_message = $wpdb->last_error;
            livraison_api_log( '❌ ERREUR D\'INSERTION dans la table de logs : ' . $error_message, 'error' );
            $order->add_order_note( '⚠️ Erreur d\'enregistrement dans les logs SendiAPI : ' . $error_message );
        } else {
            livraison_api_log( '✅ Insertion réussie dans la table de logs pour la commande #' . $order_id, 'info' );
            
            // Invalider le cache après insertion réussie
            if ( class_exists( 'LivraisonAPI\\Cache' ) ) {
                LivraisonAPI\Cache::invalidate_orders_cache( $course_id );
            }
        }
        
    } else {
        $error = $result['error'] ?? 'Unknown';
        $raw = isset( $result['raw_response'] ) ? $result['raw_response'] : '';
        
        $order->add_order_note( 'Send error: ' . $error );
        livraison_api_log( 'Error: ' . $error, 'error' );
        
        if ( $raw ) {
            livraison_api_log( 'Raw response: ' . $raw, 'error' );
        }
    }
}

function livraison_api_send_order_from_thankyou( $order_id ) {
    $order = wc_get_order( $order_id );
    if ( ! $order ) {
        return;
    }
    
    $existing_course = $order->get_meta( '_livraison_course_id' );
    if ( $existing_course ) {
        return;
    }
    
    $shipping_methods = $order->get_shipping_methods();
    foreach ( $shipping_methods as $method ) {
        if ( strpos( $method->get_method_id(), 'livraison_api' ) !== false ) {
            livraison_api_log( 'Sending from thank you page #' . $order_id, 'info' );
            livraison_api_send_order( $order_id, $order );
            break;
        }
    }
}

// Admin Order Display
add_action( 'woocommerce_admin_order_data_after_shipping_address', function( $order ) {
    $full_name = $order->get_meta( '_shipping_full_name' );
    $phone = $order->get_meta( '_shipping_phone' );
    $address = $order->get_meta( '_shipping_address' );
    $commune = $order->get_meta( '_livraison_commune' );
    $instructions = $order->get_meta( '_shipping_instructions' );
    $price = $order->get_meta( '_livraison_estimated_price' );
    $course_id = $order->get_meta( '_livraison_course_id' );
    $code_secret = $order->get_meta( '_livraison_code_secret' );
    $merchant_name = $order->get_meta( '_livraison_merchant_name' );
    $merchant_phone = $order->get_meta( '_livraison_merchant_phone' );
    $merchant_email = $order->get_meta( '_livraison_merchant_email' );
    $client_country = $order->get_meta( '_client_country' );
    $merchant_country = $order->get_meta( '_merchant_country' );
    

    if ( ! empty( $client_country ) ) {
        echo '<p><strong>Client Country:</strong> ' . esc_html( $client_country ) . '</p>';
    }
    if ( ! empty( $merchant_country ) ) {
        echo '<p><strong>Merchant Country:</strong> ' . esc_html( $merchant_country ) . '</p>';
    }


    echo '<div class="livraison-order-meta">';
    echo '<h4>Delivery - SendiAPI</h4>';
    
    if ( ! empty( $full_name ) ) echo '<p><strong>Recipient:</strong> ' . esc_html( $full_name ) . '</p>';
    if ( ! empty( $phone ) ) echo '<p><strong>Phone:</strong> ' . esc_html( $phone ) . '</p>';
    if ( ! empty( $address ) ) echo '<p><strong>Address:</strong> ' . esc_html( $address ) . '</p>';
    if ( ! empty( $commune ) ) echo '<p><strong>Delivery Commune:</strong> ' . esc_html( $commune ) . '</p>';
    if ( ! empty( $merchant_name ) ) echo '<p><strong>Store:</strong> ' . esc_html( $merchant_name ) . '</p>';
    if ( ! empty( $merchant_phone ) ) echo '<p><strong>Store Phone:</strong> ' . esc_html( $merchant_phone ) . '</p>';
    if ( ! empty( $merchant_email ) ) echo '<p><strong>Store Email:</strong> ' . esc_html( $merchant_email ) . '</p>';
    if ( ! empty( $price ) ) echo '<p><strong>Estimated Price:</strong> ' . wp_kses_post( wc_price( $price ) ) . ' (paid on delivery)</p>';
    if ( ! empty( $course_id ) ) echo '<p><strong>Course ID:</strong> <code>' . esc_html( $course_id ) . '</code></p>';
    if ( ! empty( $code_secret ) ) echo '<p><strong>Secret Code:</strong> <code>' . esc_html( $code_secret ) . '</code></p>';
    if ( ! empty( $instructions ) ) echo '<p><strong>Instructions:</strong> ' . esc_html( $instructions ) . '</p>';
    echo '<p><strong>Payment:</strong> Cash on delivery</p>';
    echo '</div>';
} );

// Add column to orders list
add_filter( 'manage_edit-shop_order_columns', function( $columns ) {
    $columns['sendi_status'] = 'SendiAPI';
    return $columns;
} );

add_action( 'manage_shop_order_posts_custom_column', function( $column, $post_id ) {
    if ( $column === 'sendi_status' ) {
        $order = wc_get_order( $post_id );
        if ( $order ) {
            $course_id = $order->get_meta( '_livraison_course_id' );
            if ( $course_id ) {
                echo '<span class="livraison-order-status">' . esc_html( $course_id ) . '</span>';
            } else {
                echo '<span>Pending</span>';
            }
        }
    }
}, 10, 2 );

// Planifier la mise à jour des statuts toutes les 5 minutes
add_action( 'wp', function() {
    if ( ! wp_next_scheduled( 'livraison_api_update_statuses' ) ) {
        wp_schedule_event( time(), 'five_minutes', 'livraison_api_update_statuses' );
    }
} );

// Ajouter un intervalle de 5 minutes
add_filter( 'cron_schedules', function( $schedules ) {
    $schedules['five_minutes'] = array(
        'interval' => 300,
        'display' => __( 'Every 5 Minutes', 'sendi-api' )
    );
    return $schedules;
} );

// Fonction de mise à jour des statuts
add_action( 'livraison_api_update_statuses', 'livraison_api_update_order_statuses' );

function livraison_api_update_order_statuses() {
    global $wpdb;
    
    $cache_key = 'livraison_pending_orders';
    $orders = wp_cache_get($cache_key, 'livraison_api');

    if (false === $orders) {
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
        $orders = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT id, order_id, course_id, status 
                FROM {$wpdb->prefix}livraison_api_logs 
                WHERE status NOT IN (%s, %s, %s) 
                AND course_id != ''
                ORDER BY created_at DESC 
                LIMIT %d",
                'delivered', 'cancelled', 'failed', 100
            )
        );
        wp_cache_set($cache_key, $orders, 'livraison_api', 300);
    }
    
    if ( empty( $orders ) ) {
        livraison_api_log( '📭 No orders to update', 'info' );
        return;
    }
    
    $api = new LivraisonAPI\API();
    $updated = false;
    
    foreach ( $orders as $order ) {
        if ( empty( $order->course_id ) ) {
            continue;
        }
        
        livraison_api_log( "🔍 Checking order #{$order->order_id} (course: {$order->course_id})", 'info' );
        
        $result = $api->get_order_status( $order->course_id );
        
        if ( ! $result['success'] || empty( $result['data'] ) ) {
            livraison_api_log( "❌ Failed to get status for course {$order->course_id}", 'error' );
            continue;
        }
        
        $new_status = $result['data']['status'] ?? '';
        livraison_api_log( "📊 Plugin status: {$order->status} → {$new_status}", 'info' );
        
        if ( ! empty( $new_status ) && $new_status !== $order->status ) {
			// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
            $wpdb->update(
				// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
                $wpdb->prefix . 'livraison_api_logs',
                array( 'status' => $new_status ),
                array( 'id' => $order->id )
            );
            
            $updated = true;
            
            // ✅ 2. Mettre à jour WooCommerce
            $wc_order = wc_get_order( $order->order_id );
            if ( $wc_order ) {
                $wc_order->update_meta_data( '_livraison_status', $new_status );
                
                $status_mapping = array(
                    'pending'     => 'pending',
                    'created'     => 'pending',
                    'sent'        => 'processing',
                    'assigned'    => 'processing',
                    'in_progress' => 'processing',
                    'delivered'   => 'completed',
                    'cancelled'   => 'cancelled',
                    'failed'      => 'failed'
                );
                
                $new_wc_status = $status_mapping[ $new_status ] ?? '';
                $current_wc_status = $wc_order->get_status();
                
                livraison_api_log( "📊 WooCommerce status: {$current_wc_status} → {$new_wc_status}", 'info' );
                
                if ( ! empty( $new_wc_status ) && $new_wc_status !== $current_wc_status ) {
                    $notes = array(
                        'sent'        => __( '📦 Order sent to delivery service', 'sendi-api' ),
                        'assigned'    => __( '📋 Order assigned to delivery agency', 'sendi-api' ),
                        'in_progress' => __( '🚚 Order is being delivered', 'sendi-api' ),
                        'delivered'   => __( '✅ Order delivered successfully!', 'sendi-api' ),
                        'cancelled'   => __( '❌ Order cancelled', 'sendi-api' ),
                        'failed'      => __( '⚠️ Delivery failed', 'sendi-api' )
                    );
                    
/* translators: %s: New order status */
$note = $notes[ $new_status ] ?? sprintf( __( 'Status updated to: %s', 'sendi-api' ), $new_status );                    $wc_order->update_status( $new_wc_status, $note );
                    
                    livraison_api_log( "✅ Order #{$order->order_id} WooCommerce: {$current_wc_status} → {$new_wc_status}", 'info' );
                } else {
                    livraison_api_log( "ℹ️ Order #{$order->order_id} WooCommerce already: {$current_wc_status}", 'info' );
                }
                
                $wc_order->save();
            }
        }
    }
    
    if ( $updated ) {
        if ( class_exists( 'LivraisonAPI\\Cache' ) ) {
            LivraisonAPI\Cache::invalidate_orders_cache();
        }
        livraison_api_log( '🧹 Caches invalidated', 'info' );
    }
}

function livraison_api_invalidate_caches( $course_id = null ) {
    wp_cache_delete( 'livraison_dashboard_stats', 'livraison_api' );
    wp_cache_delete( 'livraison_recent_logs', 'livraison_api' );
    wp_cache_delete( 'livraison_ajax_stats', 'livraison_api' );
    wp_cache_delete( 'livraison_admin_logs', 'livraison_api' );
    wp_cache_delete( 'livraison_communes', 'livraison_api' );
    
    global $wpdb;
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
$cache_keys = $wpdb->get_col(
    "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE '_transient_livraison_orders_stats_%'"
);
    foreach ( $cache_keys as $key ) {
        $cache_name = str_replace( '_transient_', '', $key );
        wp_cache_delete( $cache_name, 'livraison_api' );
    }
    
    if ( $course_id ) {
        wp_cache_delete( 'livraison_order_status_' . md5( $course_id ), 'livraison_api' );
        wp_cache_delete( 'livraison_price_' . md5( $course_id ), 'livraison_api' );
        wp_cache_delete( 'livraison_status_' . md5( $course_id ), 'livraison_api' );
    }
    
    livraison_api_log( '🧹 Caches invalidés', 'info' );
}

add_action( 'admin_post_livraison_purge_cache', 'livraison_api_purge_cache' );

function livraison_api_purge_cache() {
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_die( 'Unauthorized' );
    }
    
    global $wpdb;
    $cache_key_all_transients = 'livraison_all_transient_keys';
    $cache_keys = wp_cache_get($cache_key_all_transients, 'livraison_api');

    if (false === $cache_keys) {
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
        $cache_keys = $wpdb->get_col(
            "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE '_transient_livraison_%'"
        );
        wp_cache_set($cache_key_all_transients, $cache_keys, 'livraison_api', 300);
    }
    foreach ( $cache_keys as $key ) {
        $transient_name = str_replace( '_transient_', '', $key );
        delete_transient( $transient_name );
    }
    
    wp_cache_flush();
    
    livraison_api_log( '🧹 All caches purged manually', 'info' );
    
    wp_safe_redirect( add_query_arg( 'purged', '1', wp_get_referer() ) );
    exit;
}

add_action( 'admin_post_livraison_update_statuses', 'livraison_api_force_update_statuses' );

function livraison_api_force_update_statuses() {
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_die( 'Unauthorized' );
    }
    
    livraison_api_update_order_statuses();
    
    wp_safe_redirect( add_query_arg( 'updated', '1', wp_get_referer() ) );
    exit;
}

// AFFICHAGE SUR LA PAGE ORDER RECEIVED
add_action( 'woocommerce_thankyou', 'livraison_api_display_delivery_info', 25, 1 );

function livraison_api_display_delivery_info( $order_id ) {
    $order = wc_get_order( $order_id );
    if ( ! $order ) {
        return;
    }
    
    $course_id = $order->get_meta( '_livraison_course_id' );
    if ( empty( $course_id ) ) {
        return;
    }
    
    $code_secret = $order->get_meta( '_livraison_code_secret' );
    $agence_name = $order->get_meta( '_livraison_agence_name' );
    $status = $order->get_meta( '_livraison_status' );
    $estimated_price = $order->get_meta( '_livraison_estimated_price' );
    $client_commune = $order->get_meta( '_livraison_commune' );
    $order_total = $order->get_meta( '_livraison_order_total' );
    $payer_type = $order->get_meta( '_livraison_payer_type' );
    $is_free_delivery = $order->get_meta( '_livraison_is_free' );
    
    // Récupérer le prix depuis la table des logs
    if ( empty( $estimated_price ) ) {
        global $wpdb;
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
        $estimated_price = $wpdb->get_var(
            $wpdb->prepare(
                "SELECT price FROM {$wpdb->prefix}livraison_api_logs WHERE course_id = %s ORDER BY id DESC LIMIT 1",
                $course_id
            )
        );
    }
    
    if ( empty( $estimated_price ) || $estimated_price == 0 ) {
        $shipping_items = $order->get_items( 'shipping' );
        foreach ( $shipping_items as $shipping_item ) {
            if ( strpos( $shipping_item->get_method_id(), 'livraison_api' ) !== false ) {
                $estimated_price = $shipping_item->get_total();
                break;
            }
        }
    }
    
    if ( empty( $estimated_price ) ) {
    global $wpdb;
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
    $estimated_price = $wpdb->get_var(
        $wpdb->prepare(
            "SELECT price FROM {$wpdb->prefix}livraison_api_logs WHERE course_id = %s ORDER BY id DESC LIMIT 1",
            $course_id
        )
    );
}
    
    // Récupérer le statut depuis la table des logs
    global $wpdb;
	// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
$log_status = $wpdb->get_var(
    $wpdb->prepare(
        "SELECT status FROM {$wpdb->prefix}livraison_api_logs WHERE course_id = %s ORDER BY id DESC LIMIT 1",
        $course_id
    )
);
    
    $final_status = ! empty( $log_status ) ? $log_status : $status;
    
    $status_labels = array(
        'pending' => 'En attente',
        'created' => 'Créée',
        'sent' => 'Envoyée à SendiAPI',
        'assigned' => 'Assignée à un livreur',
        'in_progress' => 'En cours de livraison',
        'delivered' => 'Livrée',
        'failed' => 'Échouée',
        'cancelled' => 'Annulée'
    );
    
    $status_label = $status_labels[ $final_status ] ?? 'En attente de traitement';
    
    $price_display = '';
    if ( $is_free_delivery || $payer_type === 'commercant' ) {
        $price_display = '0 FCFA <span style="color: #22c55e; font-size: 0.9em;">(💰 pris en charge par le commerçant)</span>';
    } elseif ( $estimated_price > 0 ) {
        $price_display = wp_kses_post( wc_price( $estimated_price ) );
    } else {
        $price_display = '0 FCFA';
    }
    ?>
    <div class="livraison-delivery-status">
        <h3><?php esc_html_e( 'Suivi de livraison', 'sendi-api' ); ?></h3>
        
        <table>
            <tr>
                <td>Statut</td>
                <td>
                    <span class="livraison-status-badge"><?php echo esc_html( $status_label ); ?></span>
                </td>
            </tr>
            <?php if ( ! empty( $code_secret ) ) : ?>
            <tr>
                <td>Code de suivi</td>
                <td>
                    <code><?php echo esc_html( $code_secret ); ?></code>
                    <span>(À communiquer au livreur)</span>
                </td>
            </tr>
            <?php endif; ?>
            <?php if ( ! empty( $agence_name ) ) : ?>
            <tr>
                <td>Agence de livraison</td>
                <td><?php echo esc_html( $agence_name ); ?></td>
            </tr>
            <?php endif; ?>
            <tr>
                <td>Frais de livraison</td>
                <td>
                    <?php echo $price_display; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
                </td>
            </tr>
            <?php if ( ! empty( $order_total ) && $order_total > 0 ) : ?>
            <tr>
                <td>Total commande</td>
                <td>
                    <span>
                        <?php echo wp_kses_post( wc_price( $order_total ) ); ?>
                    </span>
                </td>
            </tr>
            <?php endif; ?>
        </table>
        
        <div>
            <strong>Paiement de la livraison</strong>
            <span>
                <?php if ( $is_free_delivery || $payer_type === 'commercant' ) : ?>
                    La livraison est gratuite ! Les frais de livraison sont pris en charge par le commerçant.
                <?php else : ?>
                    Le paiement de la livraison s'effectue directement au livreur à la réception de votre colis, 
                    en espèces ou par mobile money (Orange Money, MTN Mobile Money, Wave).
                <?php endif; ?>
            </span>
        </div>
    </div>
    <?php
}

// ✅ Ajouter l'action pour le force sync
add_action('admin_post_livraison_force_update', 'livraison_api_force_update_handler');

function livraison_api_force_update_handler() {
    if (!current_user_can('manage_options')) {
        wp_die('Unauthorized');
    }
    
    // Appeler la fonction de mise à jour
    livraison_api_update_order_statuses();
    
    wp_safe_redirect(add_query_arg('force_updated', '1', wp_get_referer()));
    exit;
}

// Dans sendi-api.php, ajoutez ou vérifiez cette fonction
function livraison_api_migrate_country_options() {
    // Initialiser allowed countries avec TOUS les pays disponibles par défaut
    if ( ! get_option( 'livraison_api_allowed_countries' ) ) {
        // Par défaut, autoriser tous les pays disponibles
        $default_countries = array('CI', 'BJ', 'BF', 'CM', 'SN', 'ML', 'TG', 'GH', 'NG', 'MA', 'FR');
        add_option( 'livraison_api_allowed_countries', $default_countries );
    }
    
    if ( ! get_option( 'livraison_api_commercant_country' ) ) {
        add_option( 'livraison_api_commercant_country', 'CI' );
    }
    
    if ( ! get_option( 'livraison_api_inter_country_enabled' ) ) {
        add_option( 'livraison_api_inter_country_enabled', false );
    }
}
add_action( 'init', 'livraison_api_migrate_country_options' );