<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
// Fonction pour envoyer un SMS lors de la confirmation de commande

function smap_get_full_order_data_as_array($order_id) {
    $order = wc_get_order($order_id);
    if (!$order) {
        return null;
    }

    $order_data = [];

    // Données principales
    $order_data['id'] = $order->get_id();
    $order_data['status'] = $order->get_status();
    $order_data['created_at'] = $order->get_date_created() ? $order->get_date_created()->date('Y-m-d H:i:s') : '';
    $order_data['modified_at'] = $order->get_date_modified() ? $order->get_date_modified()->date('Y-m-d H:i:s') : '';
    $order_data['completed_at'] = $order->get_date_completed() ? $order->get_date_completed()->date('Y-m-d H:i:s') : '';
    $order_data['paid_at'] = $order->get_date_paid() ? $order->get_date_paid()->date('Y-m-d H:i:s') : '';
    $order_data['total'] = $order->get_total();
    $order_data['subtotal'] = $order->get_subtotal();
    $order_data['total_tax'] = $order->get_total_tax();
    $order_data['shipping_total'] = $order->get_shipping_total();
    $order_data['shipping_tax'] = $order->get_shipping_tax();
    $order_data['discount_total'] = $order->get_discount_total();
    $order_data['discount_tax'] = $order->get_discount_tax();
    $order_data['currency'] = $order->get_currency();

    // Adresses
    $order_data['billing'] = $order->get_address('billing');
    $order_data['shipping'] = $order->get_address('shipping');

    // Client
    $order_data['customer_id'] = $order->get_customer_id();
    $order_data['customer_ip_address'] = $order->get_customer_ip_address();
    $order_data['customer_user_agent'] = $order->get_customer_user_agent();
    $order_data['customer_note'] = $order->get_customer_note();

    // Paiement
    $order_data['payment_method'] = $order->get_payment_method();
    $order_data['payment_method_title'] = $order->get_payment_method_title();
    $order_data['transaction_id'] = $order->get_transaction_id();

    // Articles commandés
    $order_data['items'] = [];
    foreach ($order->get_items() as $item_id => $item) {
        $product = $item->get_product();
        $order_data['items'][] = [
            'item_id' => $item_id,
            'product_id' => $item->get_product_id(),
            'variation_id' => $item->get_variation_id(),
            'name' => $item->get_name(),
            'quantity' => $item->get_quantity(),
            'subtotal' => $item->get_subtotal(),
            'subtotal_tax' => $item->get_subtotal_tax(),
            'total' => $item->get_total(),
            'total_tax' => $item->get_total_tax(),
            'taxes' => $item->get_taxes(),
            'product' => $product ? [
                'sku' => $product->get_sku(),
                'price' => $product->get_price(),
            ] : null,
        ];
    }

    // Frais supplémentaires (shipping, fees, taxes)
    $order_data['shipping_methods'] = [];
    foreach ($order->get_shipping_methods() as $shipping_item) {
        $order_data['shipping_methods'][] = [
            'method_id' => $shipping_item->get_method_id(),
            'method_title' => $shipping_item->get_method_title(),
            'total' => $shipping_item->get_total(),
            'taxes' => $shipping_item->get_taxes(),
        ];
    }

    $order_data['fees'] = [];
    foreach ($order->get_fees() as $fee) {
        $order_data['fees'][] = [
            'name' => $fee->get_name(),
            'total' => $fee->get_total(),
            'tax' => $fee->get_total_tax(),
        ];
    }

    $order_data['taxes'] = [];
    foreach ($order->get_taxes() as $tax) {
        $order_data['taxes'][] = [
            'rate_id' => $tax->get_rate_id(),
            'label' => $tax->get_label(),
            'amount' => $tax->get_amount(),
        ];
    }

 

    // Métadonnées personnalisées
    $order_data['meta_data'] = [];
    foreach ($order->get_meta_data() as $meta) {
        $order_data['meta_data'][] = [
            'key' => $meta->key,
            'value' => maybe_unserialize($meta->value),
        ];
    }

    return $order_data;
}





function smap_send_sms_on_thankyou($order_id) {
	
	$smap_sendsms = get_option('smap_sendsms');
$smap_sendwa = get_option('smap_sendwa');



    // Validation de l'ID de commande
    if (!is_numeric($order_id)) {
        SMAP_insert_log_entry("Invalid order ID: $order_id", 0, 0,$smap_sendsms,$smap_sendwa);
        return;
    }

    $order = wc_get_order($order_id);
	$order_data =json_encode(smap_get_full_order_data_as_array($order_id));
    if (!$order) {
        SMAP_insert_log_entry("Order not found for ID $order_id", $order_id, 0,$smap_sendsms,$smap_sendwa);
        return;
    }
























    // Vérifier si le SMS a déjà été envoyé pour cette commande
    if (get_post_meta($order_id, 'sms_sent_from_smsmobileapi', true)) {
        SMAP_insert_log_entry("SMS already sent for order $order_id. No action required", $order_id, 0,$smap_sendsms,$smap_sendwa);
        return;
    }

    // Récupérer le numéro de téléphone en s'assurant qu'il est bien formaté
	$phone_number = $order->get_billing_phone();
    if($phone_number =="")
	{
	 $phone_number = $order->get_shipping_phone();	
	}

    // Valider que le numéro de téléphone n'est pas vide
    if (empty($phone_number)) {
        SMAP_insert_log_entry("Phone number missing for the order $order_id", $order_id, 0,$smap_sendsms,$smap_sendwa);
        return;
    }

    // Vérifier que l'option d'envoi de SMS est activée
    if (get_option('smap_order_confirmation_sms')) {
        $api_key = sanitize_text_field(get_option('smap_api_key'));

        // Récupérer le message personnalisé avec validation et échappement
        $message_template = sanitize_text_field(get_option('smap_thankyou_sms_message', 'Votre commande a été confirmée. Merci pour votre achat ! [order_id]'));
      


 $message = str_replace('[order_id]', $order_id, $message_template);
		









		$placeholders = [
    // 🟢 Informations générales de la commande
    '[order_id]'              => $order->get_id(),
    '[order_status]'          => $order->get_status(),
    '[order_total]'           => wc_price($order->get_total()),
    '[order_currency]'        => $order->get_currency(),
    '[order_payment_method]'  => $order->get_payment_method(),
    '[order_payment_title]'   => $order->get_payment_method_title(),
    '[order_transaction_id]'  => $order->get_transaction_id(),
    '[order_discount_total]'  => wc_price($order->get_discount_total()),
    '[order_discount_tax]'    => wc_price($order->get_discount_tax()),
    '[order_shipping_total]'  => wc_price($order->get_shipping_total()),
    '[order_shipping_tax]'    => wc_price($order->get_shipping_tax()),
    '[order_tax_total]'       => wc_price($order->get_total_tax()),
    '[order_subtotal]'        => wc_price($order->get_subtotal()),
    '[order_key]'             => $order->get_order_key(),
    '[order_cart_hash]'       => $order->get_cart_hash(),
    '[order_created_via]'     => $order->get_created_via(),
    '[order_ip_address]'      => $order->get_customer_ip_address(),
    '[order_user_agent]'      => $order->get_customer_user_agent(),

    // 🕒 Dates importantes de la commande
    '[order_date_created]'    => $order->get_date_created() ? $order->get_date_created()->date('Y-m-d H:i:s') : '',
    '[order_date_modified]'   => $order->get_date_modified() ? $order->get_date_modified()->date('Y-m-d H:i:s') : '',
    '[order_date_paid]'       => $order->get_date_paid() ? $order->get_date_paid()->date('Y-m-d H:i:s') : '',
    '[order_date_completed]'  => $order->get_date_completed() ? $order->get_date_completed()->date('Y-m-d H:i:s') : '',

    // 🟡 Informations du client
    '[customer_id]'           => $order->get_customer_id(),
    '[customer_email]'        => $order->get_billing_email(),
    '[customer_phone]'        => $order->get_billing_phone(),

    // 🔵 Adresse de facturation
    '[billing_first_name]'    => $order->get_billing_first_name(),
    '[billing_last_name]'     => $order->get_billing_last_name(),
    '[billing_company]'       => $order->get_billing_company(),
    '[billing_address_1]'     => $order->get_billing_address_1(),
    '[billing_address_2]'     => $order->get_billing_address_2(),
    '[billing_city]'          => $order->get_billing_city(),
    '[billing_state]'         => $order->get_billing_state(),
    '[billing_postcode]'      => $order->get_billing_postcode(),
    '[billing_country]'       => $order->get_billing_country(),

    // 🟣 Adresse de livraison
    '[shipping_first_name]'   => $order->get_shipping_first_name(),
    '[shipping_last_name]'    => $order->get_shipping_last_name(),
    '[shipping_company]'      => $order->get_shipping_company(),
    '[shipping_address_1]'    => $order->get_shipping_address_1(),
    '[shipping_address_2]'    => $order->get_shipping_address_2(),
    '[shipping_city]'         => $order->get_shipping_city(),
    '[shipping_state]'        => $order->get_shipping_state(),
    '[shipping_postcode]'     => $order->get_shipping_postcode(),
    '[shipping_country]'      => $order->get_shipping_country(),
    '[shipping_phone]'        => $order->get_shipping_phone(),

    // 🛒 Produits commandés (Liste brute)
    '[order_items]'           => implode(', ', array_map(function($item) {
                                    return $item->get_name() . ' (x' . $item->get_quantity() . ')';
                                }, $order->get_items())),

    // 🚚 Informations d'expédition
    '[shipping_method]'       => implode(', ', array_map(function($method) {
                                    return $method->get_method_title();
                                }, $order->get_shipping_methods())),
    
    '[shipping_tracking_number]' => $order->get_meta('_tracking_number'), // Si un plugin d'expédition ajoute un tracking

    // 💳 Transactions & Notes
    '[customer_note]'         => $order->get_customer_note(),
    '[transaction_id]'        => $order->get_transaction_id(),
    '[order_notes]'           => implode("\n", array_map(function($note) {
                                    return $note->content;
                                }, wc_get_order_notes(['order_id' => $order->get_id()])))
];



$placeholders2 = [];

$order_meta = get_post_meta($order_id);
if (!empty($order_meta) && is_array($order_meta)) {
    foreach ($order_meta as $meta_key => $meta_value) {
        if (is_array($meta_value)) {
            $meta_value = reset($meta_value);
        }
        $placeholders2["[$meta_key]"] = $meta_value;
    }
}

if (!empty($placeholders2)) {
    $message_template = str_replace(array_keys($placeholders2), array_values($placeholders2), $message_template);
}



				$message = str_replace(array_keys($placeholders), array_values($placeholders), $message_template);


				
				// Construire le corps de la requête
						$body = array(
							'recipients' => sanitize_text_field($phone_number),
							'message'    => sanitize_text_field($message),
							'apikey'     => $api_key,
							'from'       => 'woocommerce',
							'sendsms'    => $smap_sendsms,
							'sendwa'     => $smap_sendwa
						);

						// Envoyer le SMS via wp_remote_post()
						$response = wp_remote_post("https://api.smsmobileapi.com/sendsms/", array(
							'method'    => 'POST',
							'body'      => $body,
							'timeout'   => 10,
							'sslverify' => false, // Désactiver la vérification SSL
						));

						// Gestion des erreurs WordPress
						if (is_wp_error($response)) {
							$error_message = sanitize_text_field($response->get_error_message());
							SMAP_insert_log_entry("WP_Error while sending SMS to $phone_number for a new order placed, order: $order_id. Error: $error_message", $order_id, 0, $smap_sendsms, $smap_sendwa, '', $order_data,sanitize_text_field($message),'WP_Error');
							return;
						}

						// Analyse de la réponse HTTP et du contenu
						$response_code = wp_remote_retrieve_response_code($response);
						$response_body = wp_remote_retrieve_body($response);

						if ($response_code !== 200) {
							SMAP_insert_log_entry("HTTP error $response_code while sending SMS to $phone_number for a new order placed, order: $order_id", $order_id, 0, $smap_sendsms, $smap_sendwa, $response_body, $order_data,sanitize_text_field($message),'HTTP error');
							return;
						}

						// Vérifie si l'API renvoie une erreur malgré le 200 OK
						if (stripos($response_body, '"error":1') !== false || stripos($response_body, 'sent":"0"') !== false) {
							SMAP_insert_log_entry("API Error in response body while sending SMS to $phone_number for a new order placed, order: $order_id: $response_body", $order_id, 0, $smap_sendsms, $smap_sendwa, $response_body, $order_data,sanitize_text_field($message),'API Error');
							return;
						}

						// Succès
						SMAP_insert_log_entry("Confirmation SMS sent to $phone_number for a new order placed, order: $order_id", $order_id, 0, $smap_sendsms, $smap_sendwa, $response_body, $order_data,sanitize_text_field($message),'ok');

						// Marquer le SMS comme envoyé
						update_post_meta($order_id, 'sms_sent_from_smsmobileapi', 1);

						// Ajouter un commentaire à la commande
						if ($order && is_a($order, 'WC_Order')) {
							$order->add_order_note(esc_html__('SMS Sent To Customer From SmSMobileApi', 'sms-mobile-api'));
						}


				
    }
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	



 // ✅ Vérification des règles définies dans smap_rules
 global $wpdb;

// Préparer la clé de cache pour ce statut
$order_status = 'thank_you_page';
$cache_key    = 'smap_rules_' . md5($order_status);

// Tenter de récupérer les règles depuis le cache
$rules = wp_cache_get($cache_key, 'smap_rules');

if ($rules === false) {
    // Requête SQL préparée
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.PreparedSQL.NotPrepared
    $rules = $wpdb->get_results(
        $wpdb->prepare(
            "SELECT * FROM {$wpdb->prefix}smap_rules WHERE order_status = %s AND status = 'active'",
            $order_status
        )
    );

    // Stocker les résultats dans le cache pendant 5 minutes (300 secondes)
    wp_cache_set($cache_key, $rules, 'smap_rules', 300);
}



    if ($wpdb->last_error) {
        SMAP_insert_log_entry("MySQL ERROR: " . $wpdb->last_error, $order_id, 0, $smap_sendsms, $smap_sendwa);
    }else{

	}

    if (!empty($rules)) {
		
		  
		  
        foreach ($rules as $rule) {
            $conditions = json_decode($rule->conditions, true);
            $rule_name = $rule->rule_name;
            $is_valid = true;


            foreach ($conditions as $condition) {
                $variable = $condition['variable'];
                $operator = $condition['operator'];
                $comparison_value = $condition['comparison_value'];

                // Vérifier si la variable existe dans la commande
				
				$order_values = [
    '[order_id]'              => $order->get_id(),
    '[order_status]'          => $order->get_status(),
    '[order_total]'           => wc_price($order->get_total()),
    '[order_currency]'        => $order->get_currency(),
    '[order_payment_method]'  => $order->get_payment_method(),
    '[order_payment_title]'   => $order->get_payment_method_title(),
    '[order_transaction_id]'  => $order->get_transaction_id(),
    '[order_discount_total]'  => wc_price($order->get_discount_total()),
    '[order_discount_tax]'    => wc_price($order->get_discount_tax()),
    '[order_shipping_total]'  => wc_price($order->get_shipping_total()),
    '[order_shipping_tax]'    => wc_price($order->get_shipping_tax()),
    '[order_tax_total]'       => wc_price($order->get_total_tax()),
    '[order_subtotal]'        => wc_price($order->get_subtotal()),
    '[order_key]'             => $order->get_order_key(),
    '[order_cart_hash]'       => $order->get_cart_hash(),
    '[order_created_via]'     => $order->get_created_via(),
    '[order_ip_address]'      => $order->get_customer_ip_address(),
    '[order_user_agent]'      => $order->get_customer_user_agent(),

    // 🕒 Dates importantes de la commande
    '[order_date_created]'    => $order->get_date_created() ? $order->get_date_created()->date('Y-m-d H:i:s') : '',
    '[order_date_modified]'   => $order->get_date_modified() ? $order->get_date_modified()->date('Y-m-d H:i:s') : '',
    '[order_date_paid]'       => $order->get_date_paid() ? $order->get_date_paid()->date('Y-m-d H:i:s') : '',
    '[order_date_completed]'  => $order->get_date_completed() ? $order->get_date_completed()->date('Y-m-d H:i:s') : '',

    // 🟡 Informations du client
    '[customer_id]'           => $order->get_customer_id(),
    '[customer_email]'        => $order->get_billing_email(),
    '[customer_phone]'        => $order->get_billing_phone(),

    // 🔵 Adresse de facturation
    '[billing_first_name]'    => $order->get_billing_first_name(),
    '[billing_last_name]'     => $order->get_billing_last_name(),
    '[billing_company]'       => $order->get_billing_company(),
    '[billing_address_1]'     => $order->get_billing_address_1(),
    '[billing_address_2]'     => $order->get_billing_address_2(),
    '[billing_city]'          => $order->get_billing_city(),
    '[billing_state]'         => $order->get_billing_state(),
    '[billing_postcode]'      => $order->get_billing_postcode(),
    '[billing_country]'       => $order->get_billing_country(),

    // 🟣 Adresse de livraison
    '[shipping_first_name]'   => $order->get_shipping_first_name(),
    '[shipping_last_name]'    => $order->get_shipping_last_name(),
    '[shipping_company]'      => $order->get_shipping_company(),
    '[shipping_address_1]'    => $order->get_shipping_address_1(),
    '[shipping_address_2]'    => $order->get_shipping_address_2(),
    '[shipping_city]'         => $order->get_shipping_city(),
    '[shipping_state]'        => $order->get_shipping_state(),
    '[shipping_postcode]'     => $order->get_shipping_postcode(),
    '[shipping_country]'      => $order->get_shipping_country(),
    '[shipping_phone]'        => $order->get_shipping_phone(),

    // 🛒 Produits commandés (Liste brute)
    '[order_items]'           => implode(', ', array_map(function($item) {
                                    return $item->get_name() . ' (x' . $item->get_quantity() . ')';
                                }, $order->get_items())),

    // 🚚 Informations d'expédition
    '[shipping_method]'       => implode(', ', array_map(function($method) {
                                    return $method->get_method_title();
                                }, $order->get_shipping_methods())),
    
    '[shipping_tracking_number]' => $order->get_meta('_tracking_number'), // Si un plugin d'expédition ajoute un tracking

    // 💳 Transactions & Notes
    '[customer_note]'         => $order->get_customer_note(),
    '[transaction_id]'        => $order->get_transaction_id(),
    '[order_notes]'           => implode("\n", array_map(function($note) {
                                    return $note->content;
                                }, wc_get_order_notes(['order_id' => $order->get_id()])))
];

				
				
                $order_value = isset($order_values[$variable]) ? $order_values[$variable] : '';

				if($variable =="[order_subtotal]" ||
				$variable =="[order_total]" || 
				$variable =="[order_discount_total]" || 
				$variable =="[order_discount_tax]" || 
				$variable =="[order_shipping_total]" || 
				$variable =="[order_shipping_tax]" || 
				$variable =="[order_tax_total]" 
				
				
				
				) {
                   $order_value = isset($order_values[$variable]) ? $order_values[$variable] : '';

					// Remplacer les virgules par des points pour la cohérence des décimaux
					$order_value = str_replace(',', '.', $order_value);

					// Supprimer tous les caractères sauf les chiffres et les séparateurs de décimales (le dernier point)
					$order_value = preg_replace('/[^\d.]/', '', $order_value);

					// Vérifier que la valeur est bien un nombre
					$order_value = is_numeric($order_value) ? floatval($order_value) : 0;
                }

                $order_value = is_numeric($order_value) ? floatval($order_value) : $order_value;
			//	SMAP_insert_log_entry("order_value : " . $order_value, $order_id, 0, $smap_sendsms, $smap_sendwa);
                // Comparaison des conditions
                 // Comparaison selon l'opérateur
                
				
				
				
					$is_valid = true;

					switch ($operator) {
						case 'equal':
							if ($order_value != $comparison_value) {
								$is_valid = false;
								break;
							}
							break;

						case 'not_equal':
							if ($order_value == $comparison_value) {
								$is_valid = false;
								break;
							}
							break;

						case 'greater_than':
							if (!(is_numeric($order_value) && is_numeric($comparison_value) && $order_value > $comparison_value)) {
								$is_valid = false;
								break;
							}
							break;

						case 'less_than':
							if (!(is_numeric($order_value) && is_numeric($comparison_value) && $order_value < $comparison_value)) {
								$is_valid = false;
								break;
							}
							break;

						case 'contains':
							if (strpos(strtolower($order_value), strtolower($comparison_value)) === false) {
								$is_valid = false;
								break;
							}
							break;

						default:
							$is_valid = false;
							break;
					}

					// Si la condition n'est pas remplie, on sort de la boucle
					if (!$is_valid) {
						break;
					}

				
				
				
				
				
            }

            if ($is_valid) {
                SMAP_insert_log_entry("All conditions are OK for rule name : " . $rule_name, $order_id, 0, $smap_sendsms, $smap_sendwa);

                // Récupérer le message personnalisé avec validation et échappement
                $message_template = sanitize_text_field($rule->message);
                $messagex = str_replace(array_keys($order_values), array_values($order_values), $message_template);

                // ✅ Envoi du SMS / WhatsApp


//SMS SEND DEBUT 

// Récupérer toutes les méta-données de la commande

/*
$placeholders2 = [];

$order_meta = get_post_meta($order_id);
if (!empty($order_meta) && is_array($order_meta)) {
    foreach ($order_meta as $meta_key => $meta_value) {
        if (is_array($meta_value)) {
            $meta_value = reset($meta_value);
        }
        $placeholders2["[$meta_key]"] = $meta_value;
    }
}

*/
$placeholders2 = [];

$order = wc_get_order($order_id);

// 1. Métadonnées WooCommerce complètes via WC_Meta_Data
$meta_data = $order->get_meta_data();

foreach ($meta_data as $meta) {
    $meta_key = $meta->key;
    $meta_value = $meta->value;

    // Si tableau ou objet, convertir pour l'affichage
    if (is_array($meta_value) || is_object($meta_value)) {
        $meta_value = json_encode($meta_value);
    }

    $placeholders2["[$meta_key]"] = $meta_value;
}

// 2. Métadonnées de post_meta (en plus, si jamais certaines y figurent uniquement)
$order_meta = get_post_meta($order_id);
if (!empty($order_meta) && is_array($order_meta)) {
    foreach ($order_meta as $meta_key => $meta_value) {
        if (is_array($meta_value)) {
            $meta_value = reset($meta_value);
        }

        // Évite d'écraser ce qui a été défini via WC_Meta_Data
        if (!isset($placeholders2["[$meta_key]"])) {
            $placeholders2["[$meta_key]"] = $meta_value;
        }
    }
}




if (!empty($placeholders2)) {
    $messagex = str_replace(array_keys($placeholders2), array_values($placeholders2), $messagex);
}



	$messagex = str_replace(array_keys($placeholders), array_values($placeholders), $messagex);


	// Construire le corps de la requête
$body = array(
    'recipients' => sanitize_text_field($phone_number),
    'message'    => sanitize_text_field($message),
    'apikey'     => $api_key,
    'from'       => 'woocommerce',
    'sendsms'    => $smap_sendsms,
    'sendwa'     => $smap_sendwa
);

// Envoyer le SMS via wp_remote_post()
$response = wp_remote_post("https://api.smsmobileapi.com/sendsms/", array(
    'method'    => 'POST',
    'body'      => $body,
    'timeout'   => 10,
    'sslverify' => false, // Désactiver la vérification SSL
));

// Gestion des erreurs WordPress
if (is_wp_error($response)) {
    $error_message = sanitize_text_field($response->get_error_message());
    SMAP_insert_log_entry("WP_Error while sending SMS to $phone_number for a new order placed, order: $order_id. Error: $error_message", $order_id, 0, $smap_sendsms, $smap_sendwa, '', $order_data,sanitize_text_field($message),"WP_Error");
    return;
}

// Analyse de la réponse HTTP et du contenu
$response_code = wp_remote_retrieve_response_code($response);
$response_body = wp_remote_retrieve_body($response);

if ($response_code !== 200) {
    SMAP_insert_log_entry("HTTP error $response_code while sending SMS to $phone_number for a new order placed, order: $order_id", $order_id, 0, $smap_sendsms, $smap_sendwa, $response_body, $order_data,sanitize_text_field($message),"HTTP error");
    return;
}

// Vérifie si l'API renvoie une erreur malgré le 200 OK
if (stripos($response_body, '"error":1') !== false || stripos($response_body, 'sent":"0"') !== false) {
    SMAP_insert_log_entry("API Error in response body while sending SMS to $phone_number for a new order placed, order:  $order_id: $response_body", $order_id, 0, $smap_sendsms, $smap_sendwa, $response_body, $order_data,sanitize_text_field($message),"API Error");
    return;
}

// Succès
SMAP_insert_log_entry("Confirmation SMS sent to $phone_number for a new order placed, order:  $order_id", $order_id, 0, $smap_sendsms, $smap_sendwa, $response_body, $order_data,sanitize_text_field($message),"ok");

// Marquer le SMS comme envoyé
update_post_meta($order_id, 'sms_sent_from_smsmobileapi', 1);

// Ajouter un commentaire à la commande
if ($order && is_a($order, 'WC_Order')) {
    $order->add_order_note(esc_html__('SMS Sent To Customer From SmSMobileApi', 'sms-mobile-api'));
}
//SMS SEND FIN 




                // Marquer le SMS comme envoyé
                update_post_meta($order_id, 'sms_sent_from_smsmobileapi', 1);

                // Ajouter un commentaire à la commande
                $order->add_order_note(esc_html__('SMS Sent To Customer From SmSMobileApi', 'sms-mobile-api'));
            }
        }
    }


	
	
	
	
	
	
	
	
}
add_action('woocommerce_thankyou', 'smap_send_sms_on_thankyou', 10);

?>
