<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
// Ajouter des pages pour les configurations, logs, et obtenir une clé API

load_plugin_textdomain('sms-mobile-api', false, dirname(plugin_basename(__FILE__)) . '/languages');





   
	

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


add_action('admin_init', 'smap_check_quickstart_redirect');
function smap_check_quickstart_redirect() {
    if (is_admin()) {
        $seen = get_option('smsmobileapi_quickstart_seen', 0);
        if (!$seen) {
            update_option('smsmobileapi_quickstart_seen', 1);
            wp_safe_redirect(admin_url('admin.php?page=smsmobileapi_quickstart'));
            exit;
        }
    }
}


function smsmobileapi_quickstart_admin_page() {
    // Gestion de la sauvegarde lors du POST
    $message = ''; 
	if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['smsmobileapi_quickstart_submit'])) {

    // Vérification du nonce pour la sécurité WordPress
    if (
    !isset($_POST['_wpnonce']) ||
    !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_wpnonce'])), 'smsmobileapi_quickstart')
	) {
		$message = '<span style="color:red;">' . esc_html__('Security check failed. Please try again.', 'sms-mobile-api') . '</span>';
	}else {
        // Gestion des cases à cocher
        update_option('smap_sendsms', isset($_POST['enable_sms']) ? '1' : '0');
        update_option('smap_sendwa', isset($_POST['enable_whatsapp']) ? '1' : '0');

        // Sécurisation et sauvegarde des champs texte
        $api_key = isset($_POST['api_key']) ? sanitize_text_field(wp_unslash($_POST['api_key'])) : '';
		$phone_number = isset($_POST['phone_number']) ? sanitize_text_field(wp_unslash($_POST['phone_number'])) : '';

        update_option('smap_api_key', $api_key);
        update_option('smap_test_phone', $phone_number);
echo '
<style>
#smap-modal-overlay {
    position: fixed; 
    z-index: 9999; 
    top: 0; left: 0; 
    width: 100vw; 
    height: 100vh;
    background: rgba(0,0,0,0.4); 
    display: flex; 
    align-items: center; 
    justify-content: center;
}
#smap-modal-box {
    background: #fff; 
    padding: 32px 24px 24px 24px; 
    border-radius: 10px; 
    box-shadow: 0 8px 32px rgba(0,0,0,0.22);
    text-align: center; 
    min-width: 320px; 
    max-width: 94vw; 
    font-family: Arial,sans-serif;
}
#smap-modal-box h2 {
    font-size: 22px; 
    margin-bottom: 10px; 
    color: #1976D2;
}
#smap-modal-box p {
    font-size: 16px; 
    margin-bottom: 16px; 
    color: #222;
}
.smap-btn {
    font-size: 16px; 
    border: none; 
    padding: 10px 26px; 
    border-radius: 5px; 
    margin: 0 8px;
    cursor: pointer; 
    transition: background 0.15s; 
    font-weight: bold;
}
.smap-btn-main { background: #1976D2; color: #fff; }
.smap-btn-main:hover { background: #1356a3; }
.smap-btn-sec { background: #e0e0e0; color: #333; }
.smap-btn-sec:hover { background: #bdbdbd; }
</style>

<div id="smap-modal-overlay">
  <div id="smap-modal-box">
    <h2>' . esc_html(__('What would you like to do?', 'sms-mobile-api')) . '</h2>
    <p>' . esc_html(__('Do you want to go to the main configuration page of the plugin, or stay here to test SMS and WhatsApp sending?', 'sms-mobile-api')) . '</p>
    <p style="margin-bottom:18px; color: #555; font-size:15px;">' . esc_html(__('The next step allows you to configure when and which message will be sent to your customers regarding their order.', 'sms-mobile-api')) . '</p>

    <button class="smap-btn smap-btn-main" id="smap-btn-go">' . esc_html(__('Go to next step', 'sms-mobile-api')) . '</button>
    <button class="smap-btn smap-btn-sec" id="smap-btn-stay">' . esc_html(__('Stay here', 'sms-mobile-api')) . '</button>
  </div>
</div>

<script type="text/javascript">
document.getElementById("smap-btn-go").onclick = function() {
    window.location.href = "' . esc_url(admin_url('admin.php?page=sms-notification-plugin#sms-message-options')) . '";
};
document.getElementById("smap-btn-stay").onclick = function() {
    window.location.href = "' . esc_url(admin_url('admin.php?page=smsmobileapi_quickstart')) . '";
};
document.body.style.overflow = "hidden";
</script>
';

exit;


    }
}



    // Charger les infos existantes pour affichage
    $sms_enabled = get_option('smap_sendsms', '1');
    $wa_enabled = get_option('smap_sendwa', '0');
    $api_key = get_option('smap_api_key', '');
    $phone = get_option('smap_test_phone', '');

    ?>
    <div id="smsmobileapi-quickstart-wizard" style="max-width:640px;margin:36px auto;padding:32px;background:#fff;border-radius:8px;box-shadow:0 3px 16px rgba(0,0,0,0.08)">
        <center>
            <img src="<?php echo esc_url( plugins_url( 'assets/logo.png', __FILE__ ) ); ?>" style="width:300px; margin-bottom:10px;" alt="<?php echo esc_attr__( 'Plugin Logo', 'sms-mobile-api' ); ?>">

            <h2 style="margin-top:0;"><?php esc_html_e('Quickstart Wizard', 'sms-mobile-api'); ?></h2>

        </center>
        <div style="margin-bottom:18px;font-size:15px;color:#333;">
            <div style="margin-bottom:10px; color:#118df1">
                <i class="fa-solid fa-rocket" style="font-size:15px;"></i>
                <b><?php esc_html_e('What does this plugin do?', 'sms-mobile-api'); ?></b><br>
            </div>
           <?php
echo wp_kses_post(__('It allows you to automatically send SMS and/or WhatsApp messages for <b>each order status</b> change in WooCommerce, or <b>directly to a customer</b> for notifications.', 'sms-mobile-api'));
?>
            <div style="margin:15px 0; background: #eafaf3; border-left: 5px solid #28a745; padding:14px 20px; border-radius:7px; font-size:16px;">
                <strong><?php esc_html_e('Unique:', 'sms-mobile-api'); ?></strong>
             <?php
echo wp_kses_post(__('All SMS and WhatsApp messages are sent <b>from your own phone number</b>, using your existing mobile plan.<br> <b>No extra costs</b>: The messages are sent as if you were sending them yourself, so SMS and WhatsApp messages are <span style="color:#28a745;"><b>completely free!</b></span>', 'sms-mobile-api'));
?>
            </div>
<?php
$text = 'You can enable SMS, WhatsApp, or both.<br>Each channel can be used independently or at the same time.<br>For more information about this plugin, check out <a href="https://smsmobileapi.com/plugin-woocommerce/" target="_blank">our presentation page</a>.';
echo wp_kses_post($text,'sms-mobile-api');
?>        </div>
        <?php if ($message) : ?>
            <div id="smsmobileapi-quickstart-result" style="margin-bottom:16px;"><?php echo wp_kses_post($message); ?></div>
        <?php endif; ?>
        <form id="smsmobileapi-quickstart-form" method="post">
            <?php wp_nonce_field('smsmobileapi_quickstart'); ?>
            <p>
                <div style="margin-bottom:10px; color:#118df1">
                    <b>
                        <i class="fa-solid fa-sliders" style="font-size:15px;"></i>
                        <span style="font-size:15px;; color:#118df1">
                            <?php esc_html_e('Which channels do you want to enable?', 'sms-mobile-api'); ?>
                        </span>
                    </b>
                </div>
            </p>
            <div style="margin-bottom:24px;">
                <div style="display:flex;gap:36px;justify-content:center;align-items:center;">
                    <label style="display:flex;align-items:center;gap:14px;padding:20px 32px;border:2px solid #ececf9;border-radius:14px;background:#f9faff;box-shadow:0 2px 10px rgba(52,56,134,0.04);font-size:19px;min-width:180px;cursor:pointer;">
                        <input type="checkbox" id="smsmobileapi-enable-sms" name="enable_sms" value="1" <?php checked($sms_enabled, '1'); ?>>
                        <span style="display:inline-block;line-height:1.18;">
                            <?php esc_html_e('I want to send', 'sms-mobile-api'); ?><br><b><?php esc_html_e('SMS', 'sms-mobile-api'); ?></b>
                        </span>
                    </label>
                    <label style="display:flex;align-items:center;gap:14px;padding:20px 32px;border:2px solid #ececf9;border-radius:14px;background:#f9faff;box-shadow:0 2px 10px rgba(52,56,134,0.04);font-size:19px;min-width:180px;cursor:pointer;">
                        <input type="checkbox" id="smsmobileapi-enable-wa" name="enable_whatsapp" value="1" <?php checked($wa_enabled, '1'); ?>>
                        <span style="display:inline-block;line-height:1.18;">
                            <?php esc_html_e('I want to send', 'sms-mobile-api'); ?><br><b><?php esc_html_e('WhatsApp', 'sms-mobile-api'); ?></b>
                        </span>
                    </label>
                </div>
            </div>
            <div id="smsmobileapi-quickstart-help" style="background:#f8f8ff;padding:13px 15px;border-radius:6px;margin-bottom:14px;font-size:14px;border:1px solid #e0e0f7;display:none"></div>
            <p>
                <label><b><?php esc_html_e('API Key:', 'sms-mobile-api'); ?></b>
                    <span style="position:relative;display:inline-block;">
                        <svg id="api-key-help-btn" xmlns="https://www.w3.org/2000/svg" viewBox="0 0 19 19" width="19" height="19" style="vertical-align:middle;margin-left:5px;cursor:pointer;fill:#6566ee;">
                            <circle cx="9.5" cy="9.5" r="9.5" fill="#eef0ff"/>
                            <text x="9.5" y="14" text-anchor="middle" font-size="12" font-family="Arial" dy="-2">?</text>
                        </svg>
                        <span id="api-key-help-tooltip" style="display:none;position:absolute;top:28px;left:0;z-index:99;min-width:240px;background:#fff;color:#222;border:1.5px solid #dadcff;border-radius:9px;box-shadow:0 3px 24px #6c71b91c;font-size:14px;padding:13px 15px;line-height:1.5;">
                            <b><?php esc_html_e('Where is my API Key?', 'sms-mobile-api'); ?></b><br>
                            <?php esc_html_e('Your API Key is available in your <a href="https://dashboard.smsmobileapi.com" target="_blank">SMSMobileAPI.com dashboard</a>.<br><br>You also received it by email when you created your account.<br><br><i>If you need help or lost your API key, contact support from your dashboard.</i>', 'sms-mobile-api'); ?>
                        </span>
                    </span>
                    <br>
                    <input type="text" name="api_key" style="width:100%" value="<?php echo esc_attr($api_key); ?>" placeholder="<?php esc_attr_e('Paste your API Key', 'sms-mobile-api'); ?>">
                </label>
            </p>
            <p>
                <label><b><?php esc_html_e('Default phone number (for tests):', 'sms-mobile-api'); ?></b><br>
                    <input type="text" name="phone_number" style="width:100%" value="<?php echo esc_attr($phone); ?>" placeholder="<?php esc_attr_e('Phone number (+123456789)', 'sms-mobile-api'); ?>">
                </label>
            </p>
            <div class="sms-actions" style="margin-top:28px;">
                <button class="button button-primary" type="submit" name="smsmobileapi_quickstart_submit"><?php esc_html_e('Save & Continue', 'sms-mobile-api'); ?></button>
            </div>
        </form>
        <hr style="margin-top:10px">
        <div id="smsmobileapi-test-sms-area" style="<?php if(!$api_key || !$phone) echo 'display:none;'; ?>">
            <div style="font-size:15px; margin-top:10px; margin-bottom:10px; display:flex;align-items:center;gap:9px;">
                <strong>
                    <div style="; color:#118df1;font-size:15px;">
                        <i class="fa-solid fa-bolt" style="font-size:15px;"></i>
                        <?php esc_html_e('Test your setup', 'sms-mobile-api'); ?>
                    </div>
                </strong>
                <span style="position:relative;display:inline-block;">
                    <svg id="sms-test-help-btn" xmlns="https://www.w3.org/2000/svg" viewBox="0 0 19 19" width="19" height="19" style="vertical-align:middle;cursor:pointer;fill:#6566ee;">
                        <circle cx="9.5" cy="9.5" r="9.5" fill="#eef0ff"/>
                        <text x="9.5" y="14" text-anchor="middle" font-size="12" font-family="Arial" dy="-2">?</text>
                    </svg>
                    <span id="sms-test-help-tooltip" style="display:none;position:absolute;top:28px;left:0;z-index:99;min-width:260px;background:#fff;color:#222;border:1.5px solid #dadcff;border-radius:9px;box-shadow:0 3px 24px #6c71b91c;font-size:14px;padding:13px 16px;line-height:1.5;">
                        <b><?php esc_html_e('How does test work?', 'sms-mobile-api'); ?></b><br>
                        <?php esc_html_e('The message will be sent to the number you entered below.<br><br><b>For SMS:</b> Make sure the SMSMobileAPI app is running and open on your mobile phone to send messages. Please take your phone and launch the app now.<br><br><b>For WhatsApp:</b> Your WhatsApp account must be connected and authenticated from your dashboard at <a href="https://dashboard.smsmobileapi.com/" target="_blank">dashboard.smsmobileapi.com</a>.<br><br><i>If you have any issue, double-check your app and connection status.</i>', 'sms-mobile-api'); ?>
                    </span>
                </span>
            </div>
            <form method="post">
                <?php wp_nonce_field('smsmobileapi_quickstart_test'); ?>
                <input type="hidden" name="smsmobileapi_test_number" placeholder="<?php esc_attr_e('Phone number (+123456789)', 'sms-mobile-api'); ?>" value="<?php echo esc_attr($phone); ?>" style="width:180px;">
                <button type="submit" class="button" name="smsmobileapi_test_send_btn" style="text-align:left   " ><?php esc_html_e('Send Test SMS', 'sms-mobile-api'); ?> ->  <?php echo esc_attr($phone); ?> </button>
            </form>
			<br>
			    <form method="post">
                <?php wp_nonce_field('smsmobileapi_quickstart_test'); ?>
                <input type="hidden" name="smsmobileapi_test_number_wa" placeholder="<?php esc_attr_e('Phone number (+123456789)', 'sms-mobile-api'); ?>" value="<?php echo esc_attr($phone); ?>" style="width:180px;">
                <button type="submit" class="button" name="smsmobileapi_test_send_btn_wa"  style=" text-align:left  " ><?php esc_html_e('Send Test WhatsApp', 'sms-mobile-api'); ?>  ->  <?php echo esc_attr($phone); ?> </button>
            </form>
			

            <?php if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['smsmobileapi_test_send_btn'])): ?>
                <script>
                    // Scroller automatiquement jusqu'à l'ancre des résultats de test
                    document.addEventListener("DOMContentLoaded", function() {
                        var anchor = document.getElementById('smsmobileapi_test_result_anchor');
                        if(anchor) anchor.scrollIntoView({ behavior: "smooth", block: "start" });
                    });
                </script>
            <?php endif; ?>
			
			
			 <?php if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['smsmobileapi_test_send_btn_wa'])): ?>
                <script>
                    // Scroller automatiquement jusqu'à l'ancre des résultats de test
                    document.addEventListener("DOMContentLoaded", function() {
                        var anchor = document.getElementById('smsmobileapi_test_result_anchor');
                        if(anchor) anchor.scrollIntoView({ behavior: "smooth", block: "start" });
                    });
                </script>
            <?php endif; ?>
			
			
            <?php
            // Gestion de l'envoi test
            if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['smsmobileapi_test_send_btn'])) {
    // Vérification du nonce (sécurité WordPress)
   if (
    !isset($_POST['_wpnonce']) ||
    !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_wpnonce'])), 'smsmobileapi_quickstart_test')
) {
        echo '<span style="color:red;">' . esc_html__('Security check failed for test SMS.', 'sms-mobile-api') . '</span>';
    } else {
        // Nettoyage du numéro
        $test_number = '';
        if (isset($_POST['smsmobileapi_test_number'])) {
            if (isset($_POST['smsmobileapi_test_number'])) {
				// Déséchappe d'abord les slashs ajoutés automatiquement par PHP
				$raw_test_number = isset($_POST['smsmobileapi_test_number']) ? sanitize_text_field(wp_unslash($_POST['smsmobileapi_test_number'])) : '';
				// Puis applique la sanitation / nettoyage spécifique
				$test_number = preg_replace('/[^+\d]/', '', $raw_test_number);
			} else {
				$test_number = '';
			}
        }
        $apikey = get_option('smap_api_key');
        if (empty($test_number) || empty($apikey)) {
            echo '<span style="color:red;">' . esc_html__('Number or API key missing.', 'sms-mobile-api') . '</span>';
        } else {
			
            $url = 'https://api.smsmobileapi.com/sendsms/?recipients=' . urlencode($test_number) . '&message=' . urlencode(__('Test from Quickstart SMS Mobile API WooCommerce Plugin', 'sms-mobile-api')) . '&from=woocommerce&apikey=' . urlencode($apikey);
			$message = "Test from Quickstart SMS Mobile API WooCommerce Plugin";
			$smap_sendsms = "1";
			$smap_sendwa = "0";
			$response_body = "";
            $resp = wp_remote_get($url, array('timeout' => 10));
            if (is_wp_error($resp)) {
                echo '<span style="color:red;">' . esc_html__('Error:', 'sms-mobile-api') . ' ' . esc_html($resp->get_error_message()) . '</span>';
            } else {
                $body = wp_remote_retrieve_body($resp);
                $json = json_decode($body, true);
                $sent_val = null;
                if (is_array($json) && isset($json['result']) && isset($json['result']['sent'])) {
                    $sent_val = $json['result']['sent'];
                }
                if ($sent_val === 1 || $sent_val === "1") {
                    echo '<br><span style="color:green;"><b>' . esc_html__('Test message sent successfully!', 'sms-mobile-api') . '</b><br>' . esc_html__('Please verify the connection with your SMSMobileAPI mobile app or WhatsApp account.', 'sms-mobile-api') . '</span>';
					smap_insert_log_entry("Test Message successfully sent to $test_number", 0, 0, $smap_sendsms, $smap_sendwa, $response_body, array(), sanitize_text_field($message), "ok");

                } elseif (!is_null($sent_val)) {
                    echo '<br><span style="color:red;"><b>' . esc_html__('Message not sent.', 'sms-mobile-api') . '</b><br>' . esc_html__('Response from server:', 'sms-mobile-api') . ' <b>' . esc_html($sent_val) . '</b></span>';
					smap_insert_log_entry("Message not sent to $test_number", 0, 0, $smap_sendsms, $smap_sendwa, $response_body, array(), sanitize_text_field($message), "API Error");

                } else {
                    echo '<br><span style="color:red;"><b>' . esc_html__('Message not sent.', 'sms-mobile-api') . '</b><br>' . esc_html__('Unexpected API response.', 'sms-mobile-api') . '</span>';
					smap_insert_log_entry("Message not sent to $test_number", 0, 0, $smap_sendsms, $smap_sendwa, $response_body, array(), sanitize_text_field($message), "HTTP  Error");

                }
            }
        }
    }
}









 if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['smsmobileapi_test_send_btn_wa'])) {
    // Vérification du nonce (sécurité WordPress)
  if (
    !isset($_POST['_wpnonce']) ||
    !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_wpnonce'])), 'smsmobileapi_quickstart_test')
) {
        echo '<span style="color:red;">' . esc_html__('Security check failed for test SMS.', 'sms-mobile-api') . '</span>';
    } else {
        // Nettoyage du numéro
        $test_number = '';
			  if ( isset( $_POST['smsmobileapi_test_number_wa'] ) ) {
			$test_number = preg_replace(
				'/[^+\d]/',
				'',
				sanitize_text_field( wp_unslash( $_POST['smsmobileapi_test_number_wa'] ) )
			);
		} else {
			$test_number = '';
		}
        $apikey = get_option('smap_api_key');
        if (empty($test_number) || empty($apikey)) {
            echo '<span style="color:red;">' . esc_html__('Number or API key missing.', 'sms-mobile-api') . '</span>';
        } else {
            $url = 'https://api.smsmobileapi.com/sendsms/?recipients=' . urlencode($test_number) . '&message=' . urlencode(__('Test from Quickstart SMS Mobile API WooCommerce Plugin', 'sms-mobile-api')) . '&waonly=yes&from=woocommerce&apikey=' . urlencode($apikey);
			
	$message = "Test from Quickstart SMS Mobile API WooCommerce Plugin";
			$smap_sendsms = "0";
			$smap_sendwa = "1";
			$response_body = "";
            $resp = wp_remote_get($url, array('timeout' => 10));
            if (is_wp_error($resp)) {
                echo '<span style="color:red;">' . esc_html__('Error:', 'sms-mobile-api') . ' ' . esc_html($resp->get_error_message()) . '</span>';
            } else {
                $body = wp_remote_retrieve_body($resp);
                $json = json_decode($body, true);
                $sent_val = null;
                if (is_array($json) && isset($json['result']) && isset($json['result']['sent'])) {
                    $sent_val = $json['result']['sent'];
                }
                if ($sent_val === 1 || $sent_val === "1") {
                    echo '<br><span style="color:green;"><b>' . esc_html__('Test message sent successfully!', 'sms-mobile-api') . '</b><br>' . esc_html__('Please verify the connection with your SMSMobileAPI mobile app or WhatsApp account.', 'sms-mobile-api') . '</span>';
					smap_insert_log_entry("Test Message successfully sent to $test_number", 0, 0, $smap_sendsms, $smap_sendwa, $response_body, array(), sanitize_text_field($message), "ok");

                } elseif (!is_null($sent_val)) {
                    echo '<br><span style="color:red;"><b>' . esc_html__('Message not sent.', 'sms-mobile-api') . '</b><br>' . esc_html__('Response from server:', 'sms-mobile-api') . ' <b>' . esc_html($sent_val) . '</b></span>';
					smap_insert_log_entry("Message not sent to $test_number", 0, 0, $smap_sendsms, $smap_sendwa, $response_body, array(), sanitize_text_field($message), "API Error");

                } else {
                    echo '<br><span style="color:red;"><b>' . esc_html__('Message not sent.', 'sms-mobile-api') . '</b><br>' . esc_html__('Unexpected API response.', 'sms-mobile-api') . '</span>';
					smap_insert_log_entry("Message not sent to $test_number", 0, 0, $smap_sendsms, $smap_sendwa, $response_body, array(), sanitize_text_field($message), "HTTP Error");

                }
            }
        }
    }
}


            ?>
        </div>
    </div>
    <div style="width:100%; display:flex; justify-content:center; align-items:center; gap: 32px; margin: 36px 0;">
    <div style="border-radius: 8px; width: 180px; height: 60px; text-align: center; display: flex; align-items: center; justify-content: center;">
        <a href="https://play.google.com/store/apps/details?id=com.smsmobileapiapp" target="_blank" rel="noopener noreferrer">
            <img src="<?php echo esc_url(plugins_url('assets/BIG_ANDROID.png', __FILE__)); ?>" alt="<?php echo esc_attr__('Android', 'sms-mobile-api'); ?>" style="max-height: 50px; max-width: 180px;">
        </a>
    </div>
    <div style="border-radius: 8px; width: 180px; height: 60px; text-align: center; display: flex; align-items: center; justify-content: center;">
        <a href="https://apps.apple.com/us/app/sms-mobile-api/id6667092442" target="_blank" rel="noopener noreferrer">
            <img src="<?php echo esc_url(plugins_url('assets/BIG_APPLE_IOS.png', __FILE__)); ?>" alt="<?php echo esc_attr__('iOS', 'sms-mobile-api'); ?>" style="max-height: 50px; max-width: 180px;">
        </a>
    </div>
</div>

    <a id="smsmobileapi_test_result_anchor"></a>
    <script>
    // Zone d’aide dynamique selon sélection des canaux
    function smsmobileapiShowHelp() {
        let sms = document.getElementById('smsmobileapi-enable-sms').checked;
        let wa = document.getElementById('smsmobileapi-enable-wa').checked;
        let help = document.getElementById('smsmobileapi-quickstart-help');
        let txt = '';
        if (sms && wa) {
            txt = `<b><?php echo esc_js(__('You selected SMS & WhatsApp:', 'sms-mobile-api')); ?></b><br>
                - <a href="https://smsmobileapi.com/download/" target="_blank"><?php echo esc_js(__('Install the SMS Mobile API app', 'sms-mobile-api')); ?></a> <?php echo esc_js(__('on your phone to send SMS directly from your own number.', 'sms-mobile-api')); ?><br>
                - <a href="https://smsmobileapi.com/signup/?source_page=wa" target="_blank"><?php echo esc_js(__('Create your WhatsApp sender account here', 'sms-mobile-api')); ?></a>.<br>
                <i><?php echo esc_js(__('You can manage both in your dashboard!', 'sms-mobile-api')); ?></i>`;
        } else if (sms) {
            txt = `<b><?php echo esc_js(__('You selected SMS only:', 'sms-mobile-api')); ?></b><br>
                - <a href="https://smsmobileapi.com/download/" target="_blank"><?php echo esc_js(__('Download the SMS Mobile API app', 'sms-mobile-api')); ?></a> <?php echo esc_js(__('on your phone to send SMS directly from your own number.', 'sms-mobile-api')); ?><br>
                <span style="color:#888;font-size:13px;"><?php echo esc_js(__('Or', 'sms-mobile-api')); ?> <a href="https://smsmobileapi.com/signup/?source_page=sms_gateway" target="_blank"><?php echo esc_js(__('set up your own SMS Gateway here', 'sms-mobile-api')); ?></a> (<?php echo esc_js(__('advanced', 'sms-mobile-api')); ?>)</span>`;
        } else if (wa) {
            txt = `<b><?php echo esc_js(__('You selected WhatsApp only:', 'sms-mobile-api')); ?></b><br>
                - <a href="https://smsmobileapi.com/signup/?source_page=wa" target="_blank"><?php echo esc_js(__('Create your WhatsApp sender account here', 'sms-mobile-api')); ?></a>.`;
        }
        help.innerHTML = txt;
        help.style.display = txt ? 'block' : 'none';
    }
    document.addEventListener('DOMContentLoaded', function() {
        document.getElementById('smsmobileapi-enable-sms').addEventListener('change', smsmobileapiShowHelp);
        document.getElementById('smsmobileapi-enable-wa').addEventListener('change', smsmobileapiShowHelp);
        smsmobileapiShowHelp();
    });
    </script>
    <?php
}




function smap_add_admin_menu() {
	
	
    add_menu_page(
        esc_html__('SMS Mobile API', 'sms-mobile-api'),
        esc_html__('SMS Mobile API', 'sms-mobile-api'),
        'manage_options',
        'sms-notification-plugin',
        'smap_settings_page'
    );


    add_submenu_page(
        'sms-notification-plugin', // Slug du menu principal de ton plugin (à adapter)
        'Quickstart Wizard',
        'Quickstart Wizard',
        'manage_options',
        'smsmobileapi_quickstart',
        'smsmobileapi_quickstart_admin_page'
    );
	
	
    add_submenu_page(
        'sms-notification-plugin',
        esc_html__('Settings', 'sms-mobile-api'),
        esc_html__('Settings', 'sms-mobile-api'),
        'manage_options',
        'sms-notification-plugin',
        'smap_settings_page'
    );
	  add_submenu_page(
        'sms-notification-plugin',
        esc_html__('SMS Gateway Settings', 'sms-mobile-api'),
        esc_html__('SMS Gateway Settings', 'sms-mobile-api'),
        'manage_options',
        'smap_smsgateway',
        'smap_smsgateway_page'
    );
	
	


	

    add_submenu_page(
        'sms-notification-plugin',
        esc_html__('Rule Manager', 'sms-mobile-api'),
        esc_html__('Rule Manager', 'sms-mobile-api'),
        'manage_options',
        'smap_rule_manager',
        'smap_rule_manager_page'
    );

    add_submenu_page(
        'sms-notification-plugin',
        esc_html__('WhatsApp Config', 'sms-mobile-api'),
        esc_html__('WhatsApp Config', 'sms-mobile-api'),
        'manage_options',
        'whatsApp_config',
        'smap_whatsApp_config_page'
    );

    add_submenu_page(
        'sms-notification-plugin',
        esc_html__('Get API KEY', 'sms-mobile-api'),
        esc_html__('Get API KEY', 'sms-mobile-api'),
        'manage_options',
        'sms-get-api-key',
        'smap_get_api_key_page'
    );

    add_submenu_page(
        'sms-notification-plugin',
        esc_html__('Subscription', 'sms-mobile-api'),
        esc_html__('Subscription', 'sms-mobile-api'),
        'manage_options',
        'sms-subscriptions',
        'smap_subscriptions_page'
    );

    add_submenu_page(
        'sms-notification-plugin',
        esc_html__('Logs SMS', 'sms-mobile-api'),
        esc_html__('Log SMS', 'sms-mobile-api'),
        'manage_options',
        'sms-notification-logs',
        'smap_logs_page'
    );

    add_submenu_page(
        'sms-notification-plugin',
        esc_html__('Logs WhatsApp', 'sms-mobile-api'),
        esc_html__('Log WhatsApp', 'sms-mobile-api'),
        'manage_options',
        'sms-notification-logs-whatsapp',
        'smap_logs_wa_page'
    );

    add_submenu_page(
        'sms-notification-plugin',
        esc_html__('Check Order', 'sms-mobile-api'),
        esc_html__('Check Order', 'sms-mobile-api'),
        'manage_options',
        'sms-check-order',
        'smap_check_order_page'
    );

    add_submenu_page(
        'sms-notification-plugin',
        esc_html__('Help & Support', 'sms-mobile-api'),
        esc_html__('Help & Support', 'sms-mobile-api'),
        'manage_options',
        'sms-notification-support',
        'smap_support'
    );
}

add_action('admin_menu', 'smap_add_admin_menu');



function smap_enqueue_font_awesome() {
    wp_enqueue_style(
        'font-awesome',
        plugins_url('css/all.min.css', __FILE__),
        array(),
        '6.4.0' // Remplace par la version exacte de ta font-awesome si connue, sinon '1.0.0' ou time() pour développement
    );
}
add_action('admin_enqueue_scripts', 'smap_enqueue_font_awesome');
 


//rule start ****************************** 


// ✅ Vérifier et créer la table MySQL à chaque chargement du plugin si elle n'existe pas
add_action('plugins_loaded', 'smap_check_and_create_table');

function smap_check_and_create_table() {
    global $wpdb;

    $table_name = $wpdb->prefix . 'smap_rules';

    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared -- safe because table name is controlled and not user input
    $table_exists = $wpdb->get_var("SHOW TABLES LIKE '{$wpdb->prefix}smap_rules'");

    if ($table_exists !== $table_name) {
        smap_create_database_table(); // Appeler la fonction de création de la table
    }
}

// ✅ Fonction pour créer la table si elle n'existe pas
function smap_create_database_table() {
    global $wpdb;

    $table_name = $wpdb->prefix . 'smap_rules';
    $charset_collate = $wpdb->get_charset_collate();

    // Requête SQL de création de la table (dbDelta nécessite cette syntaxe sans IF NOT EXISTS)
    $sql = "CREATE TABLE `$table_name` (
        id INT(11) NOT NULL AUTO_INCREMENT,
        rule_name VARCHAR(255) NOT NULL,
        order_status VARCHAR(50) NOT NULL,
        variable VARCHAR(255) NOT NULL,
        operator VARCHAR(50) NOT NULL,
        comparison_value TEXT NOT NULL,
        message TEXT NOT NULL,
        status VARCHAR(50) NOT NULL DEFAULT 'active',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        conditions LONGTEXT NOT NULL,
        PRIMARY KEY  (id)
    ) $charset_collate;";

    // Inclure les fichiers nécessaires pour exécuter dbDelta()
    require_once ABSPATH . 'wp-admin/includes/upgrade.php';

    // Exécuter la requête
    dbDelta($sql);

    // Log en cas d'erreur SQL
	/*
 if (!empty($wpdb->last_error)) {
    if (defined('WP_DEBUG') && WP_DEBUG && defined('WP_DEBUG_LOG') && WP_DEBUG_LOG) {
        error_log('SMSMobileAPI DB Error: ' . $wpdb->last_error);
        error_log('Last query: ' . $wpdb->last_query);
    }
	}	*/
}










function smap_check_order_page() {
    // Génère le nonce pour cette action
    $smap_nonce = wp_create_nonce('smap_fetch_order_variables');
    ?>
    <div class="wrap">
        <h1><?php esc_html_e('Check Order Data', 'sms-mobile-api'); ?></h1>
        <p><?php esc_html_e('WooCommerce provides a lot of information that can be retrieved for creating your custom rules.', 'sms-mobile-api'); ?><br>
        <?php esc_html_e('We have developed this tool that allows you to enter an existing order number from your website and understand the structure of your orders.', 'sms-mobile-api'); ?></p>
        <input type="text" id="order_id_input" placeholder="<?php esc_html_e('Enter Order ID', 'sms-mobile-api'); ?>">
        <button id="fetch_order_data"><?php esc_html_e('Retrieve Order Variables', 'sms-mobile-api'); ?></button>
        <!-- Champ caché pour le nonce -->
        <input type="hidden" id="smap_nonce" value="<?php echo esc_attr($smap_nonce); ?>">

        <div id="order_data_container" style="display:none;border:1px solid #ccc;padding:15px;margin-top:15px;">
            <button id="close_order_data" style="float:right;"><?php esc_html_e('Close', 'sms-mobile-api'); ?></button>
            <h2><?php esc_html_e('Order Details', 'sms-mobile-api'); ?></h2>
            <div id="order_data_content"></div>
        </div>
    </div>

    <script type="text/javascript">
       jQuery(document).ready(function($) {
    $('#fetch_order_data').click(function() {
        var orderID = $('#order_id_input').val().trim();
        var smapNonce = $('#smap_nonce').val();

        if (!orderID) {
            alert('<?php echo esc_js(__('Please enter a valid Order ID.', 'sms-mobile-api')); ?>');
            return;
        }

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            dataType: 'json',  // Important pour dire que la réponse est JSON
            data: {
                action: 'smap_fetch_order_variables',
                order_id: orderID,
                smap_nonce: smapNonce
            },
            beforeSend: function() {
                $('#order_data_content').html('<p><?php echo esc_js(__('Loading...', 'sms-mobile-api')); ?></p>');
                $('#order_data_container').show();
            },
            success: function(response) {
    if (response.success) {
        $('#order_data_content').html('<pre>' + JSON.stringify(response.data, null, 2) + '</pre>');
    } else {
        $('#order_data_content').html('<p style="color:red;">' + (response.data || 'Unknown error') + '</p>');
    }
},
            error: function() {
                $('#order_data_content').html('<p style="color:red;"><?php echo esc_js(__('Failed to retrieve order data.', 'sms-mobile-api')); ?></p>');
            }
        });
    });

    $('#close_order_data').click(function() {
        $('#order_data_container').hide();
    });
});

    </script>
    <?php
}


// AJAX Handler
add_action('wp_ajax_smap_fetch_order_variables', 'smap_fetch_order_variables_callback');
add_action('wp_ajax_nopriv_smap_fetch_order_variables', 'smap_fetch_order_variables_callback');

function smap_fetch_order_variables_callback() {
    if (
        !isset($_POST['smap_nonce']) ||
        !wp_verify_nonce(
            sanitize_text_field(wp_unslash($_POST['smap_nonce'])),
            'smap_fetch_order_variables'
        )
    ) {
        wp_send_json_error(__('Security check failed (nonce).', 'sms-mobile-api'));
        wp_die();
    }

    if (!current_user_can('manage_woocommerce')) {
        wp_send_json_error(__('You do not have permission to perform this action.', 'sms-mobile-api'));
        wp_die();
    }

    if (!isset($_POST['order_id']) || empty($_POST['order_id'])) {
        wp_send_json_error(__('Order ID is required.', 'sms-mobile-api'));
        wp_die();
    }

    $order_id = absint($_POST['order_id']);
    $order_data = smap_get_full_order_data_as_array2($order_id);

    if (is_null($order_data)) {
        wp_send_json_error(__('Order not found.', 'sms-mobile-api'));
        wp_die();
    }

    wp_send_json_success($order_data);
    wp_die();
}
// Ta fonction existante pour récupérer les données de la commande en tableau (à inclure dans ton code)
function smap_get_full_order_data_as_array2($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_sms_mobile_api_ensure_status_options() { 
    // Ton tableau des statuts à vérifier/créer
 $statuses = [
    'thank_you_page' => esc_html__('New order confirmed by customer', 'sms-mobile-api'),
    'wc-pending'    => esc_html__('Pending payment', 'sms-mobile-api'),
    'wc-processing' => esc_html__('Processing', 'sms-mobile-api'),
    'wc-on-hold'    => esc_html__('On hold', 'sms-mobile-api'),
    'wc-completed'  => esc_html__('Completed', 'sms-mobile-api'),
    'wc-cancelled'  => esc_html__('Cancelled', 'sms-mobile-api'),
    'wc-refunded'   => esc_html__('Refunded', 'sms-mobile-api'),
    'wc-failed'     => esc_html__('Failed', 'sms-mobile-api'),
    'wc-shipped'    => esc_html__('Shipped', 'sms-mobile-api'),
    'wc-delivered'  => esc_html__('Delivered', 'sms-mobile-api'),
    'wc-returned'   => esc_html__('Returned', 'sms-mobile-api'),
    'wc-pre-order'  => esc_html__('Pre-Order', 'sms-mobile-api'),
    'wc-invoiced'   => esc_html__('Invoiced', 'sms-mobile-api'),
	
	'wc-checkout-draft'   => esc_html__('wc-checkout-draft', 'sms-mobile-api'),
    'wc-partially-refunded'  => esc_html__('wc-partially-refunded', 'sms-mobile-api'),
    'wc-awaiting-payment'   => esc_html__('wc-awaiting-payment', 'sms-mobile-api'),
	
	
];


    // Valeurs par défaut par langue (modifiable ici)
    $defaults = [
        'fr' => [
            'thank_you_page' => "Votre commande [order_id] a bien été confirmée. Merci pour votre confiance.",
    'wc-pending'    => "Votre commande [order_id] est en attente de paiement. Veuillez finaliser le règlement pour poursuivre le traitement.",
    'wc-processing' => "Votre commande [order_id] est en cours de traitement. Nous préparons vos articles avec soin.",
    'wc-on-hold'    => "Votre commande [order_id] est actuellement en attente. Nous vous informerons dès qu'elle évoluera.",
    'wc-completed'  => "Votre commande [order_id] a été finalisée et envoyée. Merci pour votre achat.",
    'wc-cancelled'  => "Votre commande [order_id] a été annulée. Pour toute question, contactez notre service client.",
    'wc-refunded'   => "Votre commande [order_id] a été remboursée. Vous recevrez le montant sous peu.",
    'wc-failed'     => "Le paiement de votre commande [order_id] a échoué. Veuillez réessayer ou choisir un autre moyen de paiement.",
    'wc-shipped'    => "Votre commande [order_id] a été expédiée. Vous recevrez bientôt vos articles.",
    'wc-delivered'  => "Votre commande [order_id] a été livrée. Nous espérons que tout est conforme à vos attentes.",
    'wc-returned'   => "Votre commande [order_id] a été retournée. Nous traitons votre demande de retour.",
    'wc-pre-order'  => "Votre précommande [order_id] a bien été prise en compte. Vous serez informé dès l’expédition.",
    'wc-invoiced'   => "Votre commande [order_id] a été facturée. Vous trouverez la facture en pièce jointe.",
    'wc-checkout-draft'   => "Un brouillon de commande [order_id] a été créé. Finalisez-le pour valider votre achat.",
    'wc-partially-refunded'  => "Votre commande [order_id] a été partiellement remboursée. Consultez les détails sur votre compte.",
    'wc-awaiting-payment'   => "Votre commande [order_id] est en attente de paiement. Merci de procéder au règlement rapidement.",
			
			
        ],
        'en' => [
              'thank_you_page' => "Your order [order_id] has been confirmed. Thank you for your trust.",
				'wc-pending'    => "Your order [order_id] is awaiting payment. Please complete the payment to proceed with processing.",
				'wc-processing' => "Your order [order_id] is being processed. We are carefully preparing your items.",
				'wc-on-hold'    => "Your order [order_id] is currently on hold. We will notify you as soon as its status changes.",
				'wc-completed'  => "Your order [order_id] has been completed and shipped. Thank you for your purchase.",
				'wc-cancelled'  => "Your order [order_id] has been cancelled. For any questions, please contact our customer service.",
				'wc-refunded'   => "Your order [order_id] has been refunded. You will receive the amount shortly.",
				'wc-failed'     => "The payment for your order [order_id] has failed. Please try again or choose another payment method.",
				'wc-shipped'    => "Your order [order_id] has been shipped. You will receive your items soon.",
				'wc-delivered'  => "Your order [order_id] has been delivered. We hope everything meets your expectations.",
				'wc-returned'   => "Your order [order_id] has been returned. We are processing your return request.",
				'wc-pre-order'  => "Your pre-order [order_id] has been successfully registered. You will be notified when it ships.",
				'wc-invoiced'   => "Your order [order_id] has been invoiced. You will find the invoice attached.",
				'wc-checkout-draft'   => "A draft order [order_id] has been created. Please finalize it to complete your purchase.",
				'wc-partially-refunded'  => "Your order [order_id] has been partially refunded. Check your account for details.",
				'wc-awaiting-payment'   => "Your order [order_id] is awaiting payment. Please proceed with the payment as soon as possible.",

        ],
		  'ar' => [
               'thank_you_page' => "تم تأكيد طلبك [order_id]. شكرًا لثقتك بنا.",
				'wc-pending'    => "طلبك [order_id] قيد الانتظار للدفع. يرجى إتمام الدفع للمتابعة.",
				'wc-processing' => "طلبك [order_id] قيد المعالجة. نقوم بتحضير منتجاتك بعناية.",
				'wc-on-hold'    => "طلبك [order_id] في الانتظار حالياً. سنبلغك عند تحديث حالته.",
				'wc-completed'  => "تم الانتهاء من طلبك [order_id] وإرساله. شكرًا لشرائك.",
				'wc-cancelled'  => "تم إلغاء طلبك [order_id]. لأي استفسار يرجى التواصل مع خدمة العملاء.",
				'wc-refunded'   => "تم رد مبلغ طلبك [order_id]. ستتلقى المبلغ قريباً.",
				'wc-failed'     => "فشل دفع طلبك [order_id]. يرجى المحاولة مرة أخرى أو اختيار طريقة دفع أخرى.",
				'wc-shipped'    => "تم شحن طلبك [order_id]. ستصلك المنتجات قريباً.",
				'wc-delivered'  => "تم تسليم طلبك [order_id]. نأمل أن يكون كل شيء كما توقعت.",
				'wc-returned'   => "تم إرجاع طلبك [order_id]. نحن نقوم بمعالجة طلب الاسترجاع.",
				'wc-pre-order'  => "تم تسجيل طلبك المسبق [order_id] بنجاح. سيتم إعلامك عند الإرسال.",
				'wc-invoiced'   => "تم إصدار فاتورة طلبك [order_id]. ستجد الفاتورة مرفقة.",
				'wc-checkout-draft'   => "تم إنشاء مسودة طلب [order_id]. يرجى إكمالها لإتمام الشراء.",
				'wc-partially-refunded'  => "تم رد جزء من طلبك [order_id]. راجع التفاصيل في حسابك.",
				'wc-awaiting-payment'   => "طلبك [order_id] بانتظار الدفع. يرجى إتمام الدفع في أسرع وقت.",

        ],
		
		
		
		'es' => [
              'thank_you_page' => "Su pedido [order_id] ha sido confirmado. Gracias por su confianza.",
    'wc-pending'    => "Su pedido [order_id] está pendiente de pago. Por favor, complete el pago para continuar con el proceso.",
    'wc-processing' => "Su pedido [order_id] está siendo procesado. Estamos preparando sus artículos con cuidado.",
    'wc-on-hold'    => "Su pedido [order_id] está actualmente en espera. Le avisaremos cuando haya cambios.",
    'wc-completed'  => "Su pedido [order_id] ha sido completado y enviado. Gracias por su compra.",
    'wc-cancelled'  => "Su pedido [order_id] ha sido cancelado. Si tiene alguna pregunta, contacte a nuestro servicio de atención al cliente.",
    'wc-refunded'   => "Su pedido [order_id] ha sido reembolsado. Recibirá el importe pronto.",
    'wc-failed'     => "El pago de su pedido [order_id] ha fallado. Por favor, inténtelo de nuevo o elija otro método de pago.",
    'wc-shipped'    => "Su pedido [order_id] ha sido enviado. Recibirá sus artículos pronto.",
    'wc-delivered'  => "Su pedido [order_id] ha sido entregado. Esperamos que todo esté a su satisfacción.",
    'wc-returned'   => "Su pedido [order_id] ha sido devuelto. Estamos tramitando su solicitud de devolución.",
    'wc-pre-order'  => "Su pedido anticipado [order_id] ha sido recibido. Le avisaremos cuando sea enviado.",
    'wc-invoiced'   => "Su pedido [order_id] ha sido facturado. Encontrará la factura adjunta.",
    'wc-checkout-draft'   => "Se ha creado un borrador de pedido [order_id]. Finalícelo para completar la compra.",
    'wc-partially-refunded'  => "Su pedido [order_id] ha sido reembolsado parcialmente. Consulte los detalles en su cuenta.",
    'wc-awaiting-payment'   => "Su pedido [order_id] está en espera de pago. Por favor, realice el pago lo antes posible.",


        ],
			'de' => [
           'thank_you_page' => "Ihre Bestellung [order_id] wurde bestätigt. Vielen Dank für Ihr Vertrauen.",
    'wc-pending'    => "Ihre Bestellung [order_id] wartet auf Zahlung. Bitte schließen Sie die Zahlung ab, um mit der Bearbeitung fortzufahren.",
    'wc-processing' => "Ihre Bestellung [order_id] wird bearbeitet. Wir bereiten Ihre Artikel sorgfältig vor.",
    'wc-on-hold'    => "Ihre Bestellung [order_id] befindet sich derzeit im Wartestatus. Wir informieren Sie, sobald sich etwas ändert.",
    'wc-completed'  => "Ihre Bestellung [order_id] wurde abgeschlossen und versandt. Vielen Dank für Ihren Einkauf.",
    'wc-cancelled'  => "Ihre Bestellung [order_id] wurde storniert. Bei Fragen wenden Sie sich bitte an unseren Kundenservice.",
    'wc-refunded'   => "Ihre Bestellung [order_id] wurde erstattet. Sie erhalten den Betrag in Kürze.",
    'wc-failed'     => "Die Zahlung für Ihre Bestellung [order_id] ist fehlgeschlagen. Bitte versuchen Sie es erneut oder wählen Sie eine andere Zahlungsmethode.",
    'wc-shipped'    => "Ihre Bestellung [order_id] wurde versandt. Sie erhalten Ihre Artikel in Kürze.",
    'wc-delivered'  => "Ihre Bestellung [order_id] wurde geliefert. Wir hoffen, dass alles zu Ihrer Zufriedenheit ist.",
    'wc-returned'   => "Ihre Bestellung [order_id] wurde zurückgesendet. Wir bearbeiten Ihre Rücksendung.",
    'wc-pre-order'  => "Ihre Vorbestellung [order_id] wurde aufgenommen. Sie werden benachrichtigt, sobald der Versand erfolgt.",
    'wc-invoiced'   => "Ihre Bestellung [order_id] wurde in Rechnung gestellt. Die Rechnung finden Sie im Anhang.",
    'wc-checkout-draft'   => "Ein Bestellentwurf [order_id] wurde erstellt. Bitte schließen Sie den Kauf ab.",
    'wc-partially-refunded'  => "Ihre Bestellung [order_id] wurde teilweise erstattet. Details finden Sie in Ihrem Konto.",
    'wc-awaiting-payment'   => "Ihre Bestellung [order_id] wartet auf Zahlung. Bitte bezahlen Sie zeitnah.",


        ],
		
		'hi' => [
         'thank_you_page' => "आपका ऑर्डर [order_id] सफलतापूर्वक कन्फर्म हो गया है। आपके विश्वास के लिए धन्यवाद।",
    'wc-pending'    => "आपका ऑर्डर [order_id] पेमेंट का इंतजार कर रहा है। कृपया भुगतान पूरा करें ताकि प्रोसेसिंग शुरू हो सके।",
    'wc-processing' => "आपका ऑर्डर [order_id] प्रोसेस हो रहा है। हम आपके प्रोडक्ट्स को तैयार कर रहे हैं।",
    'wc-on-hold'    => "आपका ऑर्डर [order_id] फिलहाल होल्ड पर है। जैसे ही स्थिति बदलेगी, हम आपको सूचित करेंगे।",
    'wc-completed'  => "आपका ऑर्डर [order_id] पूरा हो गया है और भेज दिया गया है। खरीदारी के लिए धन्यवाद।",
    'wc-cancelled'  => "आपका ऑर्डर [order_id] रद्द कर दिया गया है। किसी भी सवाल के लिए कृपया कस्टमर सपोर्ट से संपर्क करें।",
    'wc-refunded'   => "आपका ऑर्डर [order_id] रिफंड कर दिया गया है। राशि जल्द ही आपको मिल जाएगी।",
    'wc-failed'     => "आपके ऑर्डर [order_id] का पेमेंट फेल हो गया है। कृपया दोबारा प्रयास करें या कोई और पेमेंट मोड चुनें।",
    'wc-shipped'    => "आपका ऑर्डर [order_id] शिप कर दिया गया है। आपके प्रोडक्ट्स जल्द ही पहुंच जाएंगे।",
    'wc-delivered'  => "आपका ऑर्डर [order_id] डिलीवर कर दिया गया है। हमें उम्मीद है कि आप संतुष्ट हैं।",
    'wc-returned'   => "आपका ऑर्डर [order_id] रिटर्न हो गया है। हम आपकी रिक्वेस्ट प्रोसेस कर रहे हैं।",
    'wc-pre-order'  => "आपकी प्री-ऑर्डर [order_id] सफलतापूर्वक दर्ज कर ली गई है। शिपमेंट के समय आपको सूचित किया जाएगा।",
    'wc-invoiced'   => "आपका ऑर्डर [order_id] का इनवॉइस जारी कर दिया गया है। इनवॉइस अटैचमेंट में देखें।",
    'wc-checkout-draft'   => "एक ऑर्डर ड्राफ्ट [order_id] बनाया गया है। कृपया ऑर्डर पूरा करें।",
    'wc-partially-refunded'  => "आपका ऑर्डर [order_id] आंशिक रूप से रिफंड किया गया है। विवरण के लिए अपने अकाउंट में देखें।",
    'wc-awaiting-payment'   => "आपका ऑर्डर [order_id] पेमेंट का इंतजार कर रहा है। कृपया जल्दी भुगतान करें।",


        ],
		'it' => [
           'thank_you_page' => "Il tuo ordine [order_id] è stato confermato con successo. Grazie per la tua fiducia.",
    'wc-pending'    => "Il tuo ordine [order_id] è in attesa di pagamento. Completa il pagamento per continuare con l’elaborazione.",
    'wc-processing' => "Il tuo ordine [order_id] è in lavorazione. Stiamo preparando i tuoi articoli con cura.",
    'wc-on-hold'    => "Il tuo ordine [order_id] è attualmente in sospeso. Ti informeremo non appena ci saranno novità.",
    'wc-completed'  => "Il tuo ordine [order_id] è stato completato e spedito. Grazie per il tuo acquisto.",
    'wc-cancelled'  => "Il tuo ordine [order_id] è stato annullato. Per qualsiasi domanda, contatta il nostro servizio clienti.",
    'wc-refunded'   => "Il tuo ordine [order_id] è stato rimborsato. Riceverai l’importo a breve.",
    'wc-failed'     => "Il pagamento per l’ordine [order_id] non è andato a buon fine. Riprova o scegli un altro metodo di pagamento.",
    'wc-shipped'    => "Il tuo ordine [order_id] è stato spedito. Riceverai presto i tuoi articoli.",
    'wc-delivered'  => "Il tuo ordine [order_id] è stato consegnato. Speriamo che tu sia soddisfatto.",
    'wc-returned'   => "Il tuo ordine [order_id] è stato restituito. Stiamo elaborando la tua richiesta di reso.",
    'wc-pre-order'  => "Il tuo pre-ordine [order_id] è stato ricevuto. Ti avviseremo non appena sarà spedito.",
    'wc-invoiced'   => "Il tuo ordine [order_id] è stato fatturato. Troverai la fattura in allegato.",
    'wc-checkout-draft'   => "È stata creata una bozza di ordine [order_id]. Completa l’acquisto per convalidarlo.",
    'wc-partially-refunded'  => "Il tuo ordine [order_id] è stato rimborsato parzialmente. Consulta i dettagli nel tuo account.",
    'wc-awaiting-payment'   => "Il tuo ordine [order_id] è in attesa di pagamento. Effettua il pagamento il prima possibile.",


        ],
		
			'ja' => [
            'thank_you_page' => "ご注文 [order_id] が正常に確認されました。ご利用いただきありがとうございます。",
    'wc-pending'    => "ご注文 [order_id] はお支払い待ちです。お支払いを完了してください。",
    'wc-processing' => "ご注文 [order_id] は処理中です。商品を丁寧に準備しています。",
    'wc-on-hold'    => "ご注文 [order_id] は現在保留中です。進捗があり次第お知らせします。",
    'wc-completed'  => "ご注文 [order_id] は完了し発送されました。ご購入いただきありがとうございます。",
    'wc-cancelled'  => "ご注文 [order_id] はキャンセルされました。ご質問があればカスタマーサービスまでご連絡ください。",
    'wc-refunded'   => "ご注文 [order_id] は返金されました。まもなく返金額をお受け取りいただけます。",
    'wc-failed'     => "ご注文 [order_id] のお支払いに失敗しました。もう一度お試しになるか、別のお支払い方法をお選びください。",
    'wc-shipped'    => "ご注文 [order_id] は発送されました。商品到着までしばらくお待ちください。",
    'wc-delivered'  => "ご注文 [order_id] は配達されました。お気に召しましたら幸いです。",
    'wc-returned'   => "ご注文 [order_id] は返品されました。返金処理を進めております。",
    'wc-pre-order'  => "ご予約注文 [order_id] を承りました。発送時にご連絡いたします。",
    'wc-invoiced'   => "ご注文 [order_id] の請求書が発行されました。請求書は添付ファイルでご確認いただけます。",
    'wc-checkout-draft'   => "注文の下書き [order_id] が作成されました。ご購入を確定してください。",
    'wc-partially-refunded'  => "ご注文 [order_id] の一部が返金されました。詳細はマイアカウントでご確認ください。",
    'wc-awaiting-payment'   => "ご注文 [order_id] はお支払い待ちです。早めにお支払いをお願いいたします。",

        ],
		
				'pt' => [
             'thank_you_page' => "Seu pedido [order_id] foi confirmado com sucesso. Obrigado pela sua confiança.",
    'wc-pending'    => "Seu pedido [order_id] está aguardando pagamento. Por favor, conclua o pagamento para continuar o processamento.",
    'wc-processing' => "Seu pedido [order_id] está sendo processado. Estamos preparando seus itens com cuidado.",
    'wc-on-hold'    => "Seu pedido [order_id] está atualmente em espera. Avisaremos assim que houver uma atualização.",
    'wc-completed'  => "Seu pedido [order_id] foi concluído e enviado. Obrigado pela sua compra.",
    'wc-cancelled'  => "Seu pedido [order_id] foi cancelado. Em caso de dúvidas, entre em contato com nosso suporte.",
    'wc-refunded'   => "Seu pedido [order_id] foi reembolsado. Você receberá o valor em breve.",
    'wc-failed'     => "O pagamento do pedido [order_id] falhou. Por favor, tente novamente ou escolha outro método de pagamento.",
    'wc-shipped'    => "Seu pedido [order_id] foi enviado. Você receberá seus itens em breve.",
    'wc-delivered'  => "Seu pedido [order_id] foi entregue. Esperamos que tudo esteja de acordo com suas expectativas.",
    'wc-returned'   => "Seu pedido [order_id] foi devolvido. Estamos processando sua solicitação de devolução.",
    'wc-pre-order'  => "Seu pedido antecipado [order_id] foi registrado. Você será informado assim que for enviado.",
    'wc-invoiced'   => "Seu pedido [order_id] foi faturado. A fatura está anexada.",
    'wc-checkout-draft'   => "Um rascunho do pedido [order_id] foi criado. Finalize-o para concluir sua compra.",
    'wc-partially-refunded'  => "Seu pedido [order_id] foi parcialmente reembolsado. Veja os detalhes na sua conta.",
    'wc-awaiting-payment'   => "Seu pedido [order_id] está aguardando pagamento. Por favor, faça o pagamento o quanto antes.",


        ],
			'ru' => [
           'thank_you_page' => "您的订单 [order_id] 已成功确认。感谢您的信任。",
    'wc-pending'    => "您的订单 [order_id] 正在等待付款。请尽快完成支付以继续处理。",
    'wc-processing' => "您的订单 [order_id] 正在处理中。我们正在为您精心准备商品。",
    'wc-on-hold'    => "您的订单 [order_id] 目前处于挂起状态。状态有更新时我们会及时通知您。",
    'wc-completed'  => "您的订单 [order_id] 已完成并已发货。感谢您的购买。",
    'wc-cancelled'  => "您的订单 [order_id] 已被取消。如有疑问，请联系客服。",
    'wc-refunded'   => "您的订单 [order_id] 已退款，金额会尽快返回您的账户。",
    'wc-failed'     => "您的订单 [order_id] 支付失败。请重试或选择其他支付方式。",
    'wc-shipped'    => "您的订单 [order_id] 已发货。商品即将送达。",
    'wc-delivered'  => "您的订单 [order_id] 已送达。希望一切符合您的期待。",
    'wc-returned'   => "您的订单 [order_id] 已退货。我们正在处理您的退货请求。",
    'wc-pre-order'  => "您的预购订单 [order_id] 已成功提交。发货后我们会通知您。",
    'wc-invoiced'   => "您的订单 [order_id] 已开发票，发票随附发送。",
    'wc-checkout-draft'   => "已创建订单草稿 [order_id]。请完成支付以确认购买。",
    'wc-partially-refunded'  => "您的订单 [order_id] 部分退款。详情请查看您的账户。",
    'wc-awaiting-payment'   => "您的订单 [order_id] 正在等待付款，请及时支付。",

        ]
        // Tu peux ajouter d'autres langues si besoin
    ];

    $locale = determine_locale(); // WordPress >=5.0, sinon utilise get_locale()
 $lang = strtolower(substr($locale, 0, 2));
    // Boucle sur chaque status
    foreach ($statuses as $key => $label) {
		if($key == "thank_you_page")
		{
			$option_name = "smap_thankyou_sms_message";
		}else{ 
        $option_name = 'smap_message_' . $key;
		}
        if (get_option($option_name) === false) {
            // Valeur par défaut selon la langue, sinon label anglais
            $default_value = ($defaults[$lang][$key]);
			
			if($default_value == "")
			{
				$default_value = isset($defaults['en'][$key]) ? $defaults['en'][$key] : $label;
			}
            add_option($option_name, $default_value);
			
        }
    }
}

// Appelle cette fonction à l'activation du plugin ou lors du chargement d'une page d'admin :
add_action('admin_init', 'smap_sms_mobile_api_ensure_status_options');

function smap_smsgateway_page()
{
	?>
	
	<?php
// Fetch the list of external SMS gateways
$api_url = 'https://api.smsmobileapi.com/external_sms_gateway/list/';
$response = wp_remote_get($api_url);

$gateways = [];

if (!is_wp_error($response)) {
    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body, true);

    if (isset($data['logs']) && is_array($data['logs'])) {
        $gateways = $data['logs'];
    }
}

// Limiter à 4 pour l'affichage résumé
$summary_gateways = array_slice($gateways, 0, 4);

$smap_shop_key = sanitize_text_field(get_option('smap_shop_key'));
$api_key = get_option('smap_api_key');
?>



<div class="wrap">
    <h1><i class="fa-solid fa-plug"></i> <?php esc_html_e('SMS Gateway Configuration', 'sms-mobile-api'); ?></h1>

    <p>
        <?php esc_html_e('By default, our plugin provides a built-in connection to', 'sms-mobile-api'); ?> <strong>SMS Mobile API</strong>,
        <?php esc_html_e('allowing you to send SMS messages directly from your own mobile device — no third-party providers required.', 'sms-mobile-api'); ?><br>
        <?php esc_html_e('But we let you choose your preferred service to send SMS from your store.', 'sms-mobile-api'); ?>
    </p>

    <div style="border-left: 4px solid #2271b1; background: #f0f8ff; padding: 15px 20px; margin: 20px 0;">
        <h3 style="margin-top:0px!important"><?php esc_html_e('✅ If you are using the SMS Mobile API mobile app:', 'sms-mobile-api'); ?></h3>
        <ul>
            <li><strong><?php esc_html_e('No setup required', 'sms-mobile-api'); ?></strong> — <?php esc_html_e('everything is automated.', 'sms-mobile-api'); ?></li>
            <li><?php esc_html_e('Simply enter the', 'sms-mobile-api'); ?> <strong><?php esc_html_e('API Key', 'sms-mobile-api'); ?></strong> <?php esc_html_e('provided by the app into the WooCommerce plugin settings.', 'sms-mobile-api'); ?></li>
            <li><?php esc_html_e('You can instantly send SMS using your own phone number and mobile plan.', 'sms-mobile-api'); ?></li>
        </ul>

        <div style="display: flex; flex-wrap: wrap; gap: 20px;">
           <div style="border-radius: 8px; width: 180px; height: 60px; text-align: center; display: flex; align-items: center; justify-content: center;">
    <a href="https://play.google.com/store/apps/details?id=com.smsmobileapiapp" target="_blank" rel="noopener noreferrer">
        <img src="<?php echo esc_url( plugins_url('assets/BIG_ANDROID.png', __FILE__) ); ?>" alt="<?php echo esc_attr__('Android', 'sms-mobile-api'); ?>" style="max-height: 50px; max-width: 180px;">
    </a>
</div>
<div style="border-radius: 8px; width: 180px; height: 60px; text-align: center; display: flex; align-items: center; justify-content: center;">
    <a href="https://apps.apple.com/us/app/sms-mobile-api/id6667092442" target="_blank" rel="noopener noreferrer">
        <img src="<?php echo esc_url( plugins_url('assets/BIG_APPLE_IOS.png', __FILE__) ); ?>" alt="<?php echo esc_attr__('iOS', 'sms-mobile-api'); ?>" style="max-height: 50px; max-width: 180px;">
    </a>
</div>

        </div>

        <?php
        $url_abonnement =  "https://dashboard.smsmobileapi.com/?autoconnect=yes&key=" . urlencode($api_key) . "&smap_shop_key=" . urlencode($smap_shop_key) . "&to=my-api-key";
        ?>

        <br>
        <form action="<?php echo esc_url($url_abonnement); ?>" method="POST" target="_blank" style="display: inline-block; margin-right: 10px;">
            <button class="button button-primary" style="width:350px">
                ⚙️ <span class="Polaris-Button__Content"><?php esc_html_e('Manage My SMSMobileAPI APP', 'sms-mobile-api'); ?></span>
            </button>
        </form>
    </div>

    <div style="border-left: 4px solid #dba617; background: #fff8e5; padding: 15px 20px; margin: 20px 0;">
        <h3 style="margin-top:0px!important">⚙️ <?php esc_html_e('If you prefer to use an external SMS provider (like', 'sms-mobile-api'); ?>
            <?php foreach ($summary_gateways as $index => $gateway): ?>
                <?php echo esc_html($gateway['company_name']); ?><?php echo ($index < count($summary_gateways) - 1) ? ', ' : ' etc.)'; ?>
            <?php endforeach; ?>
        </h3>
        <ul>
            <li><?php esc_html_e('Go to your', 'sms-mobile-api'); ?> <strong><?php esc_html_e('Dashboard', 'sms-mobile-api'); ?></strong> <?php esc_html_e('and open the', 'sms-mobile-api'); ?> <strong><?php esc_html_e('External SMS Services', 'sms-mobile-api'); ?></strong> <?php esc_html_e('section.', 'sms-mobile-api'); ?></li>
            <li><?php esc_html_e('Create a new connection for your chosen provider.', 'sms-mobile-api'); ?></li>
            <li><?php esc_html_e('Copy the', 'sms-mobile-api'); ?> <strong><?php esc_html_e('API Key generated by SMSMobileAPI', 'sms-mobile-api'); ?></strong> <?php esc_html_e('for that provider and paste it into the WooCommerce', 'sms-mobile-api'); ?> <a href='admin.php?page=sms-notification-plugin'><?php esc_html_e('SMS settings', 'sms-mobile-api'); ?></a>.</li>
        </ul>

        <div style="display: flex; flex-wrap: wrap; gap: 20px;">
            <?php foreach ($gateways as $gateway): ?>
                <div style="border: 1px solid #ddd; border-radius: 8px; width: 200px; height: 60px; text-align: center; background: #fff; display: flex; align-items: center; justify-content: center;">
                    <img src="<?php echo esc_url( plugin_dir_url(__FILE__) . 'assets/gateway/' . $gateway['wp_nom_fichier_image'] ); ?>"  alt="<?php echo esc_attr($gateway['company_name']); ?>" style="max-height: 50px; max-width: 180px;">
                </div>
            <?php endforeach; ?>
        </div>

        <?php
        $url_abonnement =  "https://dashboard.smsmobileapi.com/?autoconnect=yes&key=" . urlencode($api_key) . "&smap_shop_key=" . urlencode($smap_shop_key) . "&to=external-sms-service";
        ?>

        <br>
        <form action="<?php echo esc_url($url_abonnement); ?>" method="POST" target="_blank" style="display: inline-block; margin-right: 10px;">
            <button class="button button-primary" style="width:450px">
                ⚙️ <span class="Polaris-Button__Content"><?php esc_html_e('Open the dashboard to complete the configuration', 'sms-mobile-api'); ?></span>
            </button>
        </form>
    </div>

    <div style="border-left: 4px solid #008a00; background: #eaffea; padding: 15px 20px; margin: 20px 0;">
        <h3 style="margin-top:0px!important">📶 <?php esc_html_e('If you have your own SMS gateway or SIM modem', 'sms-mobile-api'); ?></h3>
        <ul>
            <li><?php esc_html_e('You can connect your own SMS infrastructure easily, use your physical modem or any gateway connected to your SIM cards.', 'sms-mobile-api'); ?></li>
            <li><?php esc_html_e('Configure it in the Dashboard using the', 'sms-mobile-api'); ?> <strong><?php esc_html_e('Connect My Own SMS Gateway', 'sms-mobile-api'); ?></strong> <?php esc_html_e('option and connect it via API.', 'sms-mobile-api'); ?></li>
            <li><?php esc_html_e('Copy the', 'sms-mobile-api'); ?> <strong><?php esc_html_e('API Key generated by SMSMobileAPI', 'sms-mobile-api'); ?></strong> <?php esc_html_e('for your SMS Gateway and paste it into the WooCommerce', 'sms-mobile-api'); ?> <a href='admin.php?page=sms-notification-plugin'><?php esc_html_e('SMS settings', 'sms-mobile-api'); ?></a>.</li>
        </ul>

        <div style="border: 1px solid #ddd; border-radius: 8px; width: 200px; height: 60px; text-align: center; background: #fff; display: flex; align-items: center; justify-content: center;">
            <img src="<?php echo esc_url(plugin_dir_url(__FILE__) . 'assets/getaway_device.png'); ?>" alt="Device" style="max-height: 50px; max-width: 180px;">
        </div>

        <?php
        $url_abonnement =  "https://dashboard.smsmobileapi.com/?autoconnect=yes&key=" . urlencode($api_key) . "&smap_shop_key=" . urlencode($smap_shop_key) . "&to=external-sms-service-my-gateway";
        ?>

        <br>
        <form action="<?php echo esc_url($url_abonnement); ?>" method="POST" target="_blank" style="display: inline-block; margin-right: 10px;">
            <button class="button button-primary" style="width:450px">
                ⚙️ <span class="Polaris-Button__Content"><?php esc_html_e('Open the dashboard to complete the configuration', 'sms-mobile-api'); ?></span>
            </button>
        </form>
    </div>

    <h2><?php esc_html_e('Supported SMS Gateways', 'sms-mobile-api'); ?></h2>
    <ul style="margin-left:20px">
        <li><strong>SMS Mobile API (<?php esc_html_e('Recommended', 'sms-mobile-api'); ?>) ⭐</strong> — <?php esc_html_e('Send SMS directly from your mobile device. Fast, affordable, and easy to set up.', 'sms-mobile-api'); ?></li>
        <?php foreach ($gateways as $gateway): ?>
            <li><strong><?php echo esc_html($gateway['company_name']); ?></strong></li>
        <?php endforeach; ?>
        <li><strong><?php esc_html_e('Custom Gateway', 'sms-mobile-api'); ?></strong> — <?php esc_html_e('Bring your own modem or SMS server with full control.', 'sms-mobile-api'); ?></li>
    </ul>

    <h2><i class="fa-solid fa-sliders"></i> <?php esc_html_e("You're in Control", 'sms-mobile-api'); ?></h2>
    <p><?php esc_html_e("You are free to choose — or switch — your SMS gateway at any time, based on your needs, pricing, or infrastructure.", 'sms-mobile-api'); ?><br>
    <?php esc_html_e("If you need help, check out our documentation or contact our support team. We’re here to assist you in setting up the best SMS solution for your business.", 'sms-mobile-api'); ?></p>

    <h2><?php esc_html_e('Compare SMS Sending Options', 'sms-mobile-api'); ?></h2>
    <p><?php esc_html_e("Here's a comparison between using SMS Mobile API and using an external SMS provider (like Twilio, MessageBird, SMS gateway, etc.):", 'sms-mobile-api'); ?></p>

    <table class="widefat striped">
        <thead>
            <tr>
                <th><?php esc_html_e('Criteria', 'sms-mobile-api'); ?></th>
                <th><?php esc_html_e('SMS Mobile API', 'sms-mobile-api'); ?></th>
                <th><?php esc_html_e('External Provider', 'sms-mobile-api'); ?></th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td><strong><?php esc_html_e('Cost per SMS', 'sms-mobile-api'); ?></strong></td>
                <td><span style="color:green;"><?php esc_html_e('Free (uses your mobile plan)', 'sms-mobile-api'); ?></span></td>
                <td><?php esc_html_e('Charged per SMS (varies by country and provider)', 'sms-mobile-api'); ?></td>
            </tr>
            <tr>
                <td><strong><?php esc_html_e('Service Availability', 'sms-mobile-api'); ?></strong></td>
                <td><?php esc_html_e("Always available (depends only on your phone network)", 'sms-mobile-api'); ?></td>
                <td><?php esc_html_e("Depends on provider’s infrastructure and coverage", 'sms-mobile-api'); ?></td>
            </tr>
            <tr>
                <td><strong><?php esc_html_e('Privacy & Confidentiality', 'sms-mobile-api'); ?></strong></td>
                <td><span style="color:green;"><?php esc_html_e("High – messages sent from your own device", 'sms-mobile-api'); ?></span></td>
                <td><?php esc_html_e("Messages go through third-party servers", 'sms-mobile-api'); ?></td>
            </tr>
            <tr>
                <td><strong><?php esc_html_e('Setup Time', 'sms-mobile-api'); ?></strong></td>
                <td><span style="color:green;"><?php esc_html_e("Instant – just enter your API key", 'sms-mobile-api'); ?></span></td>
                <td><?php esc_html_e("Requires account setup, API configuration, verification, etc.", 'sms-mobile-api'); ?></td>
            </tr>
            <tr>
                <td><strong><?php esc_html_e('Personalization', 'sms-mobile-api'); ?></strong></td>
                <td><?php esc_html_e("Messages come from your real number", 'sms-mobile-api'); ?></td>
                <td><?php esc_html_e("Uses shared or virtual sender ID", 'sms-mobile-api'); ?></td>
            </tr>
            <tr>
                <td><strong><?php esc_html_e('Delivery Transparency', 'sms-mobile-api'); ?></strong></td>
                <td><?php esc_html_e("Full visibility – SMS is sent from your own phone", 'sms-mobile-api'); ?></td>
                <td><?php esc_html_e("Limited – relies on provider reporting", 'sms-mobile-api'); ?></td>
            </tr>
            <tr>
                <td><strong><?php esc_html_e('Scalability', 'sms-mobile-api'); ?></strong></td>
                <td><?php esc_html_e("Ideal for local/personalized messaging", 'sms-mobile-api'); ?></td>
                <td><?php esc_html_e("Better for very high volume, automated global campaigns", 'sms-mobile-api'); ?></td>
            </tr>
            <tr>
                <td><strong><?php esc_html_e('Number Ownership', 'sms-mobile-api'); ?></strong></td>
                <td><span style="color:green;"><?php esc_html_e("You use your real SIM/number", 'sms-mobile-api'); ?></span></td>
                <td><?php esc_html_e("Often uses rented or temporary numbers", 'sms-mobile-api'); ?></td>
            </tr>
        </tbody>
    </table>
</div>




	<?php 
}


// ✅ Content of the Rule Manager Page
function smap_rule_manager_page() {
	?>
	  <style>
        .smap-rules-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 15px;
        }

        .smap-rules-table th, .smap-rules-table td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }

        .smap-rules-table th {
            background-color: #f4f4f4;
            font-weight: bold;
        }

        .smap-actions {
            text-align: right;
        }

        .smap-toggle-status {
            padding: 6px 12px;
            margin-right: 5px;
            border-radius: 5px;
            cursor: pointer;
            font-weight: bold;
            transition: 0.3s;
        }

        .btn-active {
            background-color: red;
            color: white;
        }

        .btn-inactive {
            background-color: green;
            color: white;
        }

        .smap-delete-rule {
            background-color: red;
            color: white;
            padding: 6px 12px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
    </style>
	<?php 
global $wpdb;
$table_name = $wpdb->prefix . 'smap_rules';
$table_name_escaped = esc_sql($table_name);
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
$rules = $wpdb->get_results("SELECT * FROM {$table_name_escaped}");

// Order Status Options
$statuses = [
    'thank_you_page' => esc_html__('New order confirmed by customer', 'sms-mobile-api'),
    'wc-pending'    => esc_html__('Pending payment', 'sms-mobile-api'),
    'wc-processing' => esc_html__('Processing', 'sms-mobile-api'),
    'wc-on-hold'    => esc_html__('On hold', 'sms-mobile-api'),
    'wc-completed'  => esc_html__('Completed', 'sms-mobile-api'),
    'wc-cancelled'  => esc_html__('Cancelled', 'sms-mobile-api'),
    'wc-refunded'   => esc_html__('Refunded', 'sms-mobile-api'),
    'wc-failed'     => esc_html__('Failed', 'sms-mobile-api'),
    'wc-shipped'    => esc_html__('Shipped', 'sms-mobile-api'),
    'wc-delivered'  => esc_html__('Delivered', 'sms-mobile-api'),
    'wc-returned'   => esc_html__('Returned', 'sms-mobile-api'),
    'wc-pre-order'  => esc_html__('Pre-Order', 'sms-mobile-api'),
    'wc-invoiced'   => esc_html__('Invoiced', 'sms-mobile-api'),
];











// Variables available for rule conditions
$variables = [
    '[order_id]' => esc_html__('The unique identifier of the order', 'sms-mobile-api'),
    '[order_status]' => esc_html__('The current status of the order (e.g., processing, completed, refunded)', 'sms-mobile-api'),
    '[order_total]' => esc_html__('The total amount of the order including taxes and shipping', 'sms-mobile-api'),
    '[order_currency]' => esc_html__('The currency in which the order was placed', 'sms-mobile-api'),
    '[order_payment_method]' => esc_html__('The payment method used for the order (e.g., PayPal, Stripe, Bank Transfer)', 'sms-mobile-api'),
    '[order_payment_title]' => esc_html__('The display title of the payment method used', 'sms-mobile-api'),
    '[order_transaction_id]' => esc_html__('The transaction ID associated with the payment', 'sms-mobile-api'),
    '[order_discount_total]' => esc_html__('The total discount applied to the order', 'sms-mobile-api'),
    '[order_discount_tax]' => esc_html__('The tax amount applied to the discount', 'sms-mobile-api'),
    '[order_shipping_total]' => esc_html__('The total shipping cost of the order', 'sms-mobile-api'),
    '[order_shipping_tax]' => esc_html__('The tax amount applied to the shipping cost', 'sms-mobile-api'),
    '[order_tax_total]' => esc_html__('The total tax amount applied to the order', 'sms-mobile-api'),
    '[order_subtotal]' => esc_html__('The subtotal of the order before taxes and shipping', 'sms-mobile-api'),
    '[order_key]' => esc_html__('A unique key assigned to the order for security and tracking purposes', 'sms-mobile-api'),
    '[order_cart_hash]' => esc_html__('A hash representing the contents of the cart when the order was placed', 'sms-mobile-api'),
    '[order_created_via]' => esc_html__('Indicates how the order was created (e.g., store-api, admin, checkout)', 'sms-mobile-api'),
    '[order_ip_address]' => esc_html__('The IP address of the customer when placing the order', 'sms-mobile-api'),
    '[order_user_agent]' => esc_html__('The browser user agent of the customer when placing the order', 'sms-mobile-api'),

    '[order_date_created]' => esc_html__('The date and time when the order was created', 'sms-mobile-api'),
    '[order_date_modified]' => esc_html__('The date and time when the order was last modified', 'sms-mobile-api'),
    '[order_date_paid]' => esc_html__('The date and time when the order was marked as paid', 'sms-mobile-api'),
    '[order_date_completed]' => esc_html__('The date and time when the order was marked as completed', 'sms-mobile-api'),

    '[customer_id]' => esc_html__('The unique identifier of the customer', 'sms-mobile-api'),
    '[customer_email]' => esc_html__('The email address of the customer', 'sms-mobile-api'),
    '[customer_phone]' => esc_html__('The phone number of the customer', 'sms-mobile-api'),

    '[billing_first_name]' => esc_html__('The first name of the customer in the billing address', 'sms-mobile-api'),
    '[billing_last_name]' => esc_html__('The last name of the customer in the billing address', 'sms-mobile-api'),
    '[billing_company]' => esc_html__('The company name in the billing address', 'sms-mobile-api'),
    '[billing_address_1]' => esc_html__('The primary address line in the billing address', 'sms-mobile-api'),
    '[billing_address_2]' => esc_html__('The secondary address line in the billing address', 'sms-mobile-api'),
    '[billing_city]' => esc_html__('The city in the billing address', 'sms-mobile-api'),
    '[billing_state]' => esc_html__('The state or region in the billing address', 'sms-mobile-api'),
    '[billing_postcode]' => esc_html__('The postal/ZIP code in the billing address', 'sms-mobile-api'),
    '[billing_country]' => esc_html__('The country in the billing address', 'sms-mobile-api'),

    '[shipping_first_name]' => esc_html__('The first name of the recipient in the shipping address', 'sms-mobile-api'),
    '[shipping_last_name]' => esc_html__('The last name of the recipient in the shipping address', 'sms-mobile-api'),
    '[shipping_company]' => esc_html__('The company name in the shipping address', 'sms-mobile-api'),
    '[shipping_address_1]' => esc_html__('The primary address line in the shipping address', 'sms-mobile-api'),
    '[shipping_address_2]' => esc_html__('The secondary address line in the shipping address', 'sms-mobile-api'),
    '[shipping_city]' => esc_html__('The city in the shipping address', 'sms-mobile-api'),
    '[shipping_state]' => esc_html__('The state or region in the shipping address', 'sms-mobile-api'),
    '[shipping_postcode]' => esc_html__('The postal/ZIP code in the shipping address', 'sms-mobile-api'),
    '[shipping_country]' => esc_html__('The country in the shipping address', 'sms-mobile-api'),
    '[shipping_phone]' => esc_html__('The phone number associated with the shipping address', 'sms-mobile-api'),

    '[order_items]' => esc_html__('A list of the ordered products with quantity (e.g., "Product A (x2), Product B (x1)")', 'sms-mobile-api'),

    '[shipping_method]' => esc_html__('The shipping method used for the order (e.g., Standard Shipping, Express Delivery)', 'sms-mobile-api'),
    '[shipping_tracking_number]' => esc_html__('The tracking number for the shipped order (if available)', 'sms-mobile-api'),

    '[customer_note]' => esc_html__('Any note provided by the customer during checkout', 'sms-mobile-api'),
    '[transaction_id]' => esc_html__('The transaction ID associated with the payment (same as [order_transaction_id])', 'sms-mobile-api'),
    '[order_notes]' => esc_html__('Any internal order notes added by the store admin or system', 'sms-mobile-api'),
];

// Comparison Operators
$operators = [
    'equal' => esc_html__('Equal to', 'sms-mobile-api'),
    'not_equal' => esc_html__('Not equal to', 'sms-mobile-api'),
    'greater_than' => esc_html__('Greater than', 'sms-mobile-api'),
    'less_than' => esc_html__('Less than', 'sms-mobile-api'),
    'contains' => esc_html__('Contains', 'sms-mobile-api'),
];
?>
	
	
	<div class="wrap">
    <h2><?php esc_html_e('WooCommerce Rule Manager', 'sms-mobile-api'); ?></h2>
    <p><?php esc_html_e('The form below allows you to create 100% personalized rules based on specific order statuses and order details.', 'sms-mobile-api'); ?></p>
    <p><?php esc_html_e('This feature gives you complete freedom when sending messages!', 'sms-mobile-api'); ?></p>
    <p><?php esc_html_e('Take full control of your SMS notifications and tailor them to your business needs. 🚀', 'sms-mobile-api'); ?></p>

    <div class="wrap">
        <h3 style="color:#0073aa; font-weight:bold">
            <i class="fa-solid fa-rectangle-list"></i> <?php esc_html_e('New rule', 'sms-mobile-api'); ?>
        </h3>
        <hr>
        <form id="smap-rule-form">
		  
            <input type="hidden" name="action" value="smap_add_rule">
            <table class="form-table">
                <tr>
                    <th><label for="rule_name"><?php esc_html_e('Rule Name', 'sms-mobile-api'); ?></label></th>
                    <td><input type="text" name="rule_name" required></td>
                </tr>
                <tr>
                    <th><label for="order_status"><?php esc_html_e('When to send the messages?', 'sms-mobile-api'); ?></label></th>
                    <td>
                        <select name="order_status" required>
                            <option value=""><?php esc_html_e('Select status', 'sms-mobile-api'); ?></option>
                            <?php foreach ($statuses as $status => $label): ?>
                                <option value="<?php echo esc_attr($status); ?>">
                                    <?php echo esc_html($label); ?> (<?php echo esc_attr($status); ?>)
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <?php esc_html_e('(Order status)', 'sms-mobile-api'); ?>
                    </td>
                </tr>
                <tr>
                    <th><?php esc_html_e('Conditions to send the message', 'sms-mobile-api'); ?>
                        <p class="description" style="font-size:10px">
                            <b><?php esc_html_e('Warning:', 'sms-mobile-api'); ?></b>
                            <?php esc_html_e('The returned data may vary depending on the WooCommerce version. Please refer to the official WooCommerce documentation to ensure the correct data format.', 'sms-mobile-api'); ?>
                        </p>
                    </th>
                    <td>

                  <div id="conditions-container">
                            <div class="condition-row">
                                <select name="variable[]">
                                    <option value=""><?php esc_html_e('Select variable', 'sms-mobile-api'); ?></option>
                                    <?php foreach ($variables as $var => $desc): ?>
                                        <option value="<?php echo esc_attr($var); ?>">
                                            <?php echo esc_attr($var); ?> : <?php echo esc_html($desc); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <select name="operator[]">
                                    <?php foreach ($operators as $key => $op_label): ?>
                                        <option value="<?php echo esc_attr($key); ?>">
                                            <?php echo esc_html($op_label); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <input type="text" name="comparison_value[]" required>
                                <button type="button" class="remove-condition">❌</button>
                            </div>
                        </div>
                        <button type="button" id="add-condition">➕ <?php esc_html_e('Add Condition', 'sms-mobile-api'); ?></button>
                    </td>
                </tr>
                <tr>
                    <th><label for="rule_status"><?php esc_html_e('Rule Status', 'sms-mobile-api'); ?></label></th>
                    <td>
                        <select name="rule_status">
                            <option value="active"><?php esc_html_e('Active', 'sms-mobile-api'); ?></option>
                            <option value="inactive"><?php esc_html_e('Inactive', 'sms-mobile-api'); ?></option>
                        </select>
                    </td>
                </tr>
                <tr>
                    <th><label for="message"><?php esc_html_e('Message to send', 'sms-mobile-api'); ?></label></th>
                    <td>
                        <textarea name="message" rows="1" style="width:80%" required></textarea>
                    </td>
                </tr>
            </table>
            <button type="submit" class="button button-primary">
			  <?php wp_nonce_field('smap_add_rule', 'smap_nonce'); ?>
                <?php esc_html_e('Save Rule', 'sms-mobile-api'); ?>
            </button>
        </form>

        <br>
        <h3 style="color:#0073aa; font-weight:bold">
            <i class="fa-solid fa-list"></i> <?php esc_html_e('Existing Rules', 'sms-mobile-api'); ?>
        </h3>
        <hr>
        <ul id="smap-rules-list">
            <?php foreach ($rules as $rule): ?>
                <li>
                    <strong><?php echo esc_html($rule->rule_name); ?></strong> (<?php echo esc_html($rule->status); ?>)
                    <button class="smap-delete-rule" data-id="<?php echo esc_attr($rule->id); ?>">
                        <?php esc_html_e('Delete', 'sms-mobile-api'); ?>
                    </button>
                </li>
            <?php endforeach; ?>
        </ul>
    </div>
</div>
    <?php
}

add_action('wp_ajax_smap_add_rule', 'smap_add_rule');
function smap_add_rule() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'smap_rules';

    // Vérification du nonce (sécurité WordPress)
    if (
        empty($_POST['smap_nonce']) ||
        !wp_verify_nonce(
            sanitize_text_field(wp_unslash($_POST['smap_nonce'])),
            'smap_add_rule'
        )
    ) {
        wp_send_json(array('success' => false, 'message' => esc_html__('Security check failed.', 'sms-mobile-api')));
        wp_die();
    }

    // Vérification de la permission de l'utilisateur
    if (!current_user_can('manage_options')) {
        wp_send_json(array('success' => false, 'message' => esc_html__('You are not allowed to perform this action.', 'sms-mobile-api')));
        wp_die();
    }

    // Vérifier et créer la colonne 'conditions' si elle n'existe pas
    // Préparer la requête avec placeholder
    $table_name_escaped = esc_sql($table_name);
    $column_exists = $wpdb->get_results(
        $wpdb->prepare(
            "SHOW COLUMNS FROM {$wpdb->prefix}smap_rules LIKE %s",
            'conditions'
        )
    );

    if (empty($column_exists)) {
        // ALTER TABLE ne peut pas utiliser prepare() pour le nom de table, mais $table_name est sécurisé via $wpdb->prefix
        $wpdb->query("ALTER TABLE {$wpdb->prefix}smap_rules ADD `conditions` LONGTEXT NOT NULL");
    }

 // Déséchapper et assainir les tableaux provenant de $_POST
$variables = isset($_POST['variable']) && is_array($_POST['variable']) 
    ? array_map('sanitize_text_field', wp_unslash($_POST['variable'])) 
    : array();

$operators = isset($_POST['operator']) && is_array($_POST['operator']) 
    ? array_map('sanitize_text_field', wp_unslash($_POST['operator'])) 
    : array();

$comparison_values = isset($_POST['comparison_value']) && is_array($_POST['comparison_value']) 
    ? array_map('sanitize_text_field', wp_unslash($_POST['comparison_value'])) 
    : array();



    $conditions = array();
    foreach ($variables as $index => $variable) {
        $conditions[] = array(
            'variable'         => sanitize_text_field($variable),
            'operator'         => isset($operators[$index]) ? sanitize_text_field($operators[$index]) : '',
            'comparison_value' => isset($comparison_values[$index]) ? sanitize_text_field($comparison_values[$index]) : '',
        );
    }

    $rule_name    = isset($_POST['rule_name']) ? sanitize_text_field(wp_unslash($_POST['rule_name'])) : '';
    $order_status = isset($_POST['order_status']) ? sanitize_text_field(wp_unslash($_POST['order_status'])) : '';
    $message      = isset($_POST['message']) ? sanitize_textarea_field(wp_unslash($_POST['message'])) : '';
    $rule_status  = isset($_POST['rule_status']) ? sanitize_text_field(wp_unslash($_POST['rule_status'])) : '';

    // Insérer dans la base de données avec prepare via $wpdb->insert()
    $inserted = $wpdb->insert(
        $table_name,
        array(
            'rule_name'    => $rule_name,
            'order_status' => $order_status,
            'conditions'   => json_encode($conditions),
            'message'      => $message,
            'status'       => $rule_status,
            'created_at'   => current_time('mysql'),
        ),
        array('%s', '%s', '%s', '%s', '%s', '%s')
    );

    if ($inserted) {
        wp_send_json(array('success' => true, 'message' => esc_html__('Rule added successfully!', 'sms-mobile-api')));
    } else {
        wp_send_json(array('success' => false, 'message' => esc_html__('Failed to add rule.', 'sms-mobile-api')));
    }
}






add_action('wp_ajax_smap_delete_rule', 'smap_delete_rule');
function smap_delete_rule() {
    // Vérification et nettoyage du paramètre rule_id
    $rule_id = isset($_POST['rule_id']) ? intval($_POST['rule_id']) : 0;

    // Récupération, déséchappement et assainissement du nonce
    $nonce = isset($_POST['smap_nonce']) ? sanitize_text_field( wp_unslash( $_POST['smap_nonce'] ) ) : '';

    if ( $rule_id <= 0 || empty($nonce) ) {
        wp_send_json([
            'success' => false,
            'message' => esc_html__('Invalid request.', 'sms-mobile-api'),
        ]);
        wp_die();
    }

    // Vérification du nonce spécifique à la ligne
    $nonce_action = 'smap_delete_rule_' . $rule_id;
    if ( ! wp_verify_nonce( $nonce, $nonce_action ) ) {
        wp_send_json([
            'success' => false,
            'message' => esc_html__('Security check failed.', 'sms-mobile-api'),
        ]);
        wp_die();
    }

    // Vérification des permissions
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_send_json([
            'success' => false,
            'message' => esc_html__('You are not allowed to perform this action.', 'sms-mobile-api'),
        ]);
        wp_die();
    }

    // Suppression de la règle
    global $wpdb;
    $table_name = $wpdb->prefix . 'smap_rules';
    $deleted = $wpdb->delete( $table_name, [ 'id' => $rule_id ], [ '%d' ] );

    if ( $deleted ) {
        wp_send_json([
            'success' => true,
            'message' => esc_html__('Rule deleted successfully.', 'sms-mobile-api'),
        ]);
    } else {
        wp_send_json([
            'success' => false,
            'message' => esc_html__('Failed to delete rule.', 'sms-mobile-api'),
        ]);
    }

    wp_die();
}




add_action('admin_enqueue_scripts', 'smap_enqueue_admin_scripts');
function smap_enqueue_admin_scripts() {
    wp_enqueue_script(
        'smap-rule-manager',
        plugins_url('assets/smap-rule-manager.js', __FILE__),
        ['jquery'],
        '1.2.3', // ↑ Change ce numéro quand tu modifies le JS
        true
    );
    wp_localize_script('smap-rule-manager', 'smap_ajax', [
        'ajax_url' => admin_url('admin-ajax.php')
    ]);
}


add_action('wp_ajax_smap_update_rule_status', 'smap_update_rule_status');
function smap_update_rule_status() {
    // Vérification de la présence des paramètres requis
    if (empty($_POST['rule_id']) || empty($_POST['smap_nonce']) || !isset($_POST['status'])) {
        wp_send_json(['success' => false, 'message' => esc_html__('Missing parameters', 'sms-mobile-api')]);
        wp_die();
    }

    $rule_id = intval($_POST['rule_id']);

    // Vérification du nonce (spécifique à la règle)
  $nonce = isset($_POST['smap_nonce']) ? sanitize_text_field( wp_unslash( $_POST['smap_nonce'] ) ) : '';
$nonce_action = 'smap_update_rule_status_' . $rule_id;
if ( ! wp_verify_nonce( $nonce, $nonce_action ) ) {
        wp_send_json(['success' => false, 'message' => esc_html__('Security check failed.', 'sms-mobile-api')]);
        wp_die();
    }

    // Vérification du droit utilisateur (ajuste selon besoin)
    if (!current_user_can('manage_options')) {
        wp_send_json(['success' => false, 'message' => esc_html__('You are not allowed to perform this action.', 'sms-mobile-api')]);
        wp_die();
    }

    global $wpdb;
    $table_name = $wpdb->prefix . 'smap_rules';

	$current_status = isset($_POST['status']) ? sanitize_text_field( wp_unslash( $_POST['status'] ) ) : '';

    // Basculer le statut
    $new_status = ($current_status === 'active') ? 'inactive' : 'active';

    // Mettre à jour la base de données
    $updated = $wpdb->update(
        $table_name,
        ['status' => $new_status],
        ['id' => $rule_id],
        ['%s'],
        ['%d']
    );

    if ($updated !== false) {
        wp_send_json(['success' => true, 'new_status' => $new_status]);
    } else {
        wp_send_json(['success' => false, 'message' => esc_html__('Database update failed', 'sms-mobile-api')]);
    }
}


add_action('wp_ajax_smap_fetch_rules', 'smap_fetch_rules');
function smap_fetch_rules() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'smap_rules';
    $rules = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}smap_rules ORDER BY created_at DESC");

    ob_start(); // Start output buffering

    if (!empty($rules)) {
        echo '<table class="smap-rules-table">
                <thead>
                    <tr>
                        <th>' . esc_html__('Rule Name', 'sms-mobile-api') . '</th>
                        <th>' . esc_html__('Trigger Status', 'sms-mobile-api') . '</th>
                        <th>' . esc_html__('Conditions', 'sms-mobile-api') . '</th>
                        <th>' . esc_html__('Message', 'sms-mobile-api') . '</th>
                        <th>' . esc_html__('Actions', 'sms-mobile-api') . '</th>
                    </tr>
                </thead>
                <tbody>';

        foreach ($rules as $rule) {
            $isActive = ($rule->status === 'active');
            $buttonText = $isActive ? esc_html__('Deactivate it', 'sms-mobile-api') : esc_html__('Activate it', 'sms-mobile-api');
            $buttonClass = $isActive ? 'btn-active' : 'btn-inactive';

            echo '<tr style="vertical-align:top!important; background-color:#ffffff">';
            echo '<td><strong>' . esc_html($rule->rule_name) . '</strong></td>';
            echo '<td>' . esc_html($rule->order_status) . '</td>';

            // Affichage lisible des conditions
            $conditions = json_decode($rule->conditions, true);
            echo '<td>';
            if (!empty($conditions)) {
                echo '<ul>';
                foreach ($conditions as $condition) {
                    echo '<li><b>' . esc_html($condition['variable']) . '</b> <i>' . esc_html($condition['operator']) . '</i> <b>' . esc_html($condition['comparison_value']) . '</b></li>';
                }
                echo '</ul>';
            } else {
                echo '<i>' . esc_html__('No conditions set', 'sms-mobile-api') . '</i>';
            }
            echo '</td>';

            echo '<td><i>' . esc_html($rule->message) . '</i></td>';

            // Nonces uniques par ligne
            $nonce_status = wp_create_nonce('smap_update_rule_status_' . $rule->id);
            $nonce_delete = wp_create_nonce('smap_delete_rule_' . $rule->id);

            // Actions : boutons avec nonces
            echo '<td class="smap-actions">
                <button class="smap-toggle-status ' . esc_attr($buttonClass) . '" 
                    data-id="' . esc_attr($rule->id) . '" 
                    data-status="' . esc_attr($rule->status) . '"
                    data-nonce="' . esc_attr($nonce_status) . '">' . esc_html($buttonText) . '</button>
                <button class="smap-delete-rule" 
                    data-id="' . esc_attr($rule->id) . '" 
                    data-nonce="' . esc_attr($nonce_delete) . '">❌ ' . esc_html__('Delete', 'sms-mobile-api') . '</button>
            </td>';

            echo '</tr>';
        }

        echo '</tbody></table>';
    } else {
        echo '<p>' . esc_html__('No rules found.', 'sms-mobile-api') . '</p>';
    }

    $html = ob_get_clean(); // Get the buffered content and clean buffer

    wp_send_json(['success' => true, 'html' => $html]);
}






//rule end ********************************




// Fonction pour vérifier l'accessibilité de l'URL et envoyer la requête
function smap_check_and_send_api_request() {
	
	
	 if (!is_admin()) {
        return;
    }
	
	
    $nonce = wp_create_nonce('api_nonce_key');
    
    $site_url = get_bloginfo('url');
    $admin_email = get_option('admin_email');
    $wp_version = get_bloginfo('version');
	
    
    $country = get_option('woocommerce_default_country');
    if (empty($country)) {
        $locale = get_locale();
        $country = strtoupper(explode('_', $locale)[1]);
    }

    $smap_shop_key = get_option('smap_shop_key');
    if (!$smap_shop_key) {
        $smap_shop_key = smap_generate_unique_shop_key(); // Génère une clé si elle n'existe pas
    }

    $api_url = add_query_arg(
        array(
            'langue'       => 'fr',
            'boutique'     => esc_url($site_url),
            'email'        => sanitize_email($admin_email),
            'version_wp'   => esc_attr($wp_version),
            'country'      => esc_attr($country),
            'nonce'        => esc_attr($nonce),
            'smap_shop_key'=> esc_attr($smap_shop_key),
			'plugin_version' => '2.0.17',
			'apikey' => esc_attr(get_option('smap_api_key'))
        ),
        'https://api.smsmobileapi.com/woocommerce/checkuser/'
    );
    
    $response = wp_remote_get($api_url, array(
        'timeout'   => 10,
        'sslverify' => false // Activer la vérification SSL pour sécuriser la communication
    ));

if ( is_wp_error( $response ) ) {
    if ( defined('WP_DEBUG') && WP_DEBUG ) {
        $logger = wc_get_logger();
        $logger->error('API is KO: ' . $response->get_error_message(), ['source' => 'sms-mobile-api']);
    }
    return;
}

    $response_code = wp_remote_retrieve_response_code($response);
    if ($response_code === 200) {
      
    } else {
		
    }
	
	
}
add_action('admin_init', 'smap_check_and_send_api_request');

// Fonction pour afficher la page d'explication du plugin
function smap_get_api_key_page() {
    ?>
    <div class="wrap">
       
        <?php
		  // Récupère la langue active de WordPress, ex: 'fr_FR'
    $locale = get_locale();
    // Extrait juste le code langue (fr, en, etc.)
    $lang = substr($locale, 0, 2);
        $file_path = plugin_dir_path(__FILE__) . 'docs/how-to-use-' . $lang . '.html';
        if (file_exists($file_path)) {
            include $file_path;
        } else {
               $file_path = plugin_dir_path(__FILE__) . 'docs/how-to-use.html';
			if (file_exists($file_path)) {
				include $file_path;
			} else {
				echo '<p>Error: Could not find the documentation file.</p>';
			}
		
		
        }
        ?>
    </div>
    <?php
}

add_action('wp_ajax_smap_hide_first_explain', function () {
    update_option('smap_show_first_explain', 1);
    wp_die();
});

if ( is_admin() && isset($_GET['page']) && $_GET['page'] == 'sms-notification-plugin' && !get_option('smap_show_first_explain') ) : 


?>
<div id="smap-explain-modal" class="smap-modal-overlay">
    <div class="smap-modal-content">
        <h2><?php echo esc_html_e('Send SMS & WhatsApp notifications<br>directly from your own number! 🚀', 'sms-mobile-api'); ?></h2>

        <?php echo esc_html__('With this plugin, your messages come from your phone<br>—perfect if you have an unlimited SMS plan.<br><br>Replies go straight to your mobile, keeping you connected effortlessly.', 'sms-mobile-api'); ?>
        <br><br>
        🎯 <?php echo esc_html__('Get started by setting up your API key and message preferences!', 'sms-mobile-api'); ?>
        <br><br>
        <button id="smap-start-now" class="button button-primary"><?php echo esc_html__('Start now', 'sms-mobile-api'); ?></button>
    </div>
</div>
    <style>
        .smap-modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 9999;
        }
        .smap-modal-content {
            background: #fff;
            padding: 20px;
            text-align: center;
            border-radius: 10px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
            width: 50%;
            max-width: 500px;
        }
        .smap-modal-content h2 {
            margin-top: 0;
        }
    </style>
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            document.getElementById('smap-start-now').addEventListener('click', function () {
                fetch(ajaxurl, {
                    method: 'POST',
                    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                    body: 'action=smap_hide_first_explain'
                }).then(() => {
                    document.getElementById('smap-explain-modal').style.display = 'none';
                });
            });
        });
    </script>
<?php
endif;





// Fonction pour afficher la page de paramètres
function smap_settings_page() {
	
	
 
	
	
	
    if (isset($_POST['smap_test_api'])) {
        smap_test_api_call();
    }

    if (isset($_POST['submit'])) {
      if (
    !isset($_POST['smap_nonce']) ||
    !wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['smap_nonce'] ) ), 'smap_save_settings' )
) {
    wp_die('Security check failed');
}
        if (isset($_POST['smap_api_key'])) {
            $api_key = sanitize_text_field(wp_unslash($_POST['smap_api_key']));
        }

        if (isset($_POST['smap_test_phone'])) {
            $phone_number = sanitize_text_field(wp_unslash($_POST['smap_test_phone']));
        }

        if (isset($_POST['smap_thankyou_sms_message'])) {
            $thankyou_sms_message = sanitize_text_field(wp_unslash($_POST['smap_thankyou_sms_message']));
        }

        update_option('smap_api_key', $api_key);
        update_option('smap_test_phone', $phone_number);
        update_option('smap_order_confirmation_sms', isset($_POST['smap_order_confirmation_sms']) ? 1 : 0);
        update_option('smap_order_status_change_sms', isset($_POST['smap_order_status_change_sms']) ? 1 : 0);
        update_option('smap_thankyou_sms_message', $thankyou_sms_message);
		
		update_option('smap_sendsms', isset($_POST['smap_sendsms']) ? 1 : 0);
		update_option('smap_sendwa', isset($_POST['smap_sendwa']) ? 1 : 0);

           $statuses = ['wc-pending', 'wc-processing', 'wc-on-hold', 'wc-completed', 'wc-cancelled', 'wc-refunded', 'wc-failed','wc-checkout-draft','wc-shipped','wc-delivered','wc-partially-refunded','wc-returned','wc-awaiting-payment','wc-pre-order','wc-invoiced'];

        foreach ($statuses as $status) {
            if (isset($_POST['smap_message_' . $status])) {
                update_option('smap_message_' . $status, sanitize_text_field(wp_unslash($_POST['smap_message_' . $status])));
            }
			
			 // Save checkbox state (enabled/disabled)
        update_option('smap_message_enable_' . $status, isset($_POST['smap_message_enable_' . $status]) ? 1 : 0);



        }
    }

    $api_key = esc_attr(get_option('smap_api_key'));
    $phone_number = esc_attr(get_option('smap_test_phone'));
    $thankyou_sms_message = esc_html(get_option('smap_thankyou_sms_message', 'Your order has been confirmed. Thank you for your purchase! [order_id]'));


	
	
$statuses = [
    'wc-pending'    => esc_html__('Pending payment (natively available)', 'sms-mobile-api'),
    'wc-processing' => esc_html__('Processing (natively available)', 'sms-mobile-api'),
    'wc-on-hold'    => esc_html__('On hold (natively available)', 'sms-mobile-api'),
    'wc-completed'  => esc_html__('Completed (natively available)', 'sms-mobile-api'),
    'wc-cancelled'  => esc_html__('Cancelled (natively available)', 'sms-mobile-api'),
    'wc-refunded'   => esc_html__('Refunded (natively available)', 'sms-mobile-api'),
    'wc-failed'     => esc_html__('Failed (natively available)', 'sms-mobile-api'),
    'wc-checkout-draft' => esc_html__('Checkout Draft (natively available)', 'sms-mobile-api'),

    // Custom statuses
    'wc-shipped'    => esc_html__('Shipped (Available depending on your other plugins)', 'sms-mobile-api'),
    'wc-delivered'  => esc_html__('Delivered (Available depending on your other plugins)', 'sms-mobile-api'),
    'wc-partially-refunded' => esc_html__('Partially Refunded (Available depending on your other plugins)', 'sms-mobile-api'),
    'wc-returned'   => esc_html__('Returned (Available depending on your other plugins)', 'sms-mobile-api'),
    'wc-awaiting-payment' => esc_html__('Awaiting Payment (Available depending on your other plugins)', 'sms-mobile-api'),
    'wc-pre-order'  => esc_html__('Pre-Order (Available depending on your other plugins)', 'sms-mobile-api'),
    'wc-invoiced'   => esc_html__('Invoiced (Available depending on your other plugins)', 'sms-mobile-api'),
];


    ?>
<!-- Inclusion de jQuery depuis le CDN Google -->

<div class="wrap" style="padding:0px!important">
<!-- Iframe affichant le contenu souhaité -->
<iframe 
    id="refresh-iframe" 
    src="<?php echo esc_url( 'https://dashboard.smsmobileapi.com/submit_check_mobile_status.php?fromsource=woocommerce&api_key=' . rawurlencode($api_key) ); ?>" 
    style="width:100%; height:70px; font-family:calibri;" 
    frameborder="0" 
    scrolling="no"
></iframe></div>
<script>
    // Recharger l'iframe toutes les 60 secondes (60000 ms)
    setInterval(function() {
        var iframe = document.getElementById('refresh-iframe');
        // Pour forcer le rechargement, on réaffecte la même URL
        iframe.src = iframe.src;
    }, 60000);
</script>

    <div class="wrap">


				<div style="text-align: right;">
					<form method="post" action="">
							<?php wp_nonce_field('smap_save_settings', 'smap_nonce'); ?>
							<input type="hidden" id="smap_api_key_hidden" name="smap_api_key" value="<?php echo esc_attr($api_key); ?>" />
							<input type="hidden" id="smap_test_phone_hidden" name="smap_test_phone" value="<?php echo esc_attr($phone_number); ?>" />
							(<?php echo esc_html__('Version', 'sms-mobile-api'); ?> : 2.0.17)
							<input type="submit" name="smap_test_api" id="smap_test_api" class="button button-primary"
						   value="<?php echo esc_html__('Test API', 'sms-mobile-api'); ?>" disabled />
					</form>
				</div>

        <form method="post" action="" onsubmit="return validateForm();">
            <?php wp_nonce_field('smap_save_settings', 'smap_nonce'); ?>
          



                <img src="<?php echo esc_url(plugin_dir_url(__FILE__) . 'assets/logo.png'); ?>" style="width:300px; margin-bottom:10px; margin-top:-40px">
       
			
			
				<br>		
			
		<?php echo wp_kses_post('Starting today, you can send notification messages to your customers directly from your phone using your own number.', 'sms-mobile-api'); ?><br>
        <?php echo wp_kses_post('This feature is free by <b>SMS</b> or <b>WhatsApp</b> sent since it utilizes your existing mobile plan.', 'sms-mobile-api'); ?><br>
        <?php echo esc_html__('Your customers can respond directly to these messages, making communication seamless and personal, all from the convenience of your own phone.', 'sms-mobile-api'); ?>

           <h2><i class="fa-solid fa-comments"></i> <?php esc_html_e('Choose Notification Method', 'sms-mobile-api'); ?></h2>
		   
 <hr>
        <input type="checkbox" id="smap_sendsms" <?php checked(1, get_option('smap_sendsms'), true); ?> name="smap_sendsms" value="1">
        <?php echo wp_kses_post('Send an <b>SMS</b> for each notification', 'sms-mobile-api'); ?> <br>
        <input type="checkbox" id="smap_sendwa" <?php checked(1, get_option('smap_sendwa'), true); ?> name="smap_sendwa" value="1">
        <?php echo wp_kses_post('Send a <b>WhatsApp</b> for each notification', 'sms-mobile-api'); ?>
        <b> => <?php echo esc_html__('Go to the [WhatsApp Config] menu to set up the configuration.', 'sms-mobile-api'); ?></b>
        <?php submit_button(__('Save Changes', 'sms-mobile-api'), 'primary', 'submit'); ?>

        <h2><i class="fa-solid fa-gears"></i> <?php esc_html_e('API Configuration', 'sms-mobile-api'); ?></h2>
        <hr>
	
		
			<?php esc_html_e('You can send SMS from SMSmobileAPI, but also from an external service like Twilio, MessageBird, etc.', 'sms-mobile-api'); ?>	<br>
	<?php esc_html_e('You can also send SMS from your own SMS Gateway if you have one with your own SIM cards.', 'sms-mobile-api'); ?><br>
	
	<a href="admin.php?page=smap_smsgateway"><?php esc_html_e('Click here to set up your SMS Gateway and start sending SMS from your own mobile or external service', 'sms-mobile-api'); ?></a>
	
	
	
        <table class="form-table">
            <tr valign="top">
                <th scope="row"><?php esc_html_e('API Key', 'sms-mobile-api'); ?></th>
                <td>
                    <input type="text" id="smap_api_key" name="smap_api_key"
                           value="<?php echo esc_attr($api_key); ?>" style="width:60%; margin-bottom:0px!important" oninput="updateHiddenFields();" />
                    <?php if (empty($api_key)) { ?>
                        <br>
                    <a href="<?php echo esc_url(admin_url('admin.php?page=smsmobileapi_quickstart')); ?>"
   class="button button-secondary"
   style="margin-top:10px; background-color:#00aa63; color:#ffffff; border-style:none; border-radius:10px; font-weight:bold">
    <i class="fa-solid fa-key"></i> <?php esc_html_e('Quickstart Wizard', 'sms-mobile-api'); ?>
</a>
                        <a href="https://smsmobileapi.com/connect/?from_woommerce_get_apikey=yes" target="_blank"
                           class="button button-secondary"
                           style="margin-top:10px; margin-left:20px; background-color:#118df0; color:#ffffff; border-style:none; border-radius:10px; font-weight:bold">
                            <i class="fa-solid fa-key"></i> <?php esc_html_e('I already have an API key', 'sms-mobile-api'); ?>
                        </a>
                    <?php } ?>
                    <br>
                    <?php if (empty($phone_number)) { ?>
                        <span id="api_key_warning" style="color:red;">
                            <?php esc_html_e('Please save a phone number to test the API', 'sms-mobile-api'); ?>
                        </span>
                    <?php } ?>
                </td>
            </tr>

            <tr valign="top">
                <th scope="row"><?php esc_html_e('Test with a Phone Number', 'sms-mobile-api'); ?></th>
                <td>
                    <input type="text" id="smap_test_phone" name="smap_test_phone"
                           value="<?php echo esc_attr($phone_number); ?>" oninput="updateHiddenFields();"
                           style="width:150px"/>
                </td>
            </tr>
        </table>
        <?php submit_button(__('Save Changes', 'sms-mobile-api'), 'primary', 'submit'); ?>
<a name="sms-message-options">&nbsp;</a>
        <h2 id="sms-message-options"><i class="fa-regular fa-comment-dots"></i> <?php esc_html_e('Message & Options', 'sms-mobile-api'); ?></h2>
        <hr>
		<?php 
		
		echo  wp_kses_post('Choose when a message should be sent to your customer (check or uncheck the options), and define the message that will be sent automatically using the available placeholders.<br>You are free to customize the messages to be sent.<br>The placeholders are available at the bottom of the page.', 'sms-mobile-api') ?>
     <br>    <br> <table class="form-table">
            <tr valign="top">
                <th scope="row">
                    <?php esc_html_e('Thank You Page SMS Message', 'sms-mobile-api'); ?>
                    <p class="description"></p>
                </th>
                <td>
                    <label>
                        <input type="checkbox" name="smap_order_confirmation_sms" value="1"
                            <?php checked(1, get_option('smap_order_confirmation_sms'), true); ?> />
                        <?php esc_html_e('When the customer confirms their order', 'sms-mobile-api'); ?>
                    </label>
                    <input style="width:100%!important" type="text" name="smap_thankyou_sms_message"
                           value="<?php echo esc_attr($thankyou_sms_message); ?>" />
                    <br>
                    <i class="fa-solid fa-heart"></i>
                    <?php esc_html_e('Customize your SMS 100% with your own rules.', 'sms-mobile-api'); ?>
                    <a href="admin.php?page=smap_rule_manager">
                        <?php esc_html_e('Click here to create your rules', 'sms-mobile-api'); ?>
                    </a>
                </td>
            </tr>

            <tr valign="top">
                <th scope="row"><?php esc_html_e('Send SMS on Order Status Change', 'sms-mobile-api'); ?></th>
                <td>
                    <input type="checkbox" name="smap_order_status_change_sms" value="1"
                        <?php checked(1, get_option('smap_order_status_change_sms'), true); ?> />
                    (<?php esc_html_e('Enable or disable all messages below', 'sms-mobile-api'); ?>)
                </td>
            </tr>

            <tr valign="top">
                <th scope="row">
                    <?php esc_html_e('Messages for Order Statuses', 'sms-mobile-api'); ?>
                    <br>
                    <a href="#tip"><?php esc_html_e('Utilize placeholders to personalize your messages.', 'sms-mobile-api'); ?></a>
                </th>
                <td>
                    <?php foreach ($statuses as $status => $label) : ?>
                        <label>
                            <input type="checkbox" name="smap_message_enable_<?php echo esc_attr($status); ?>"
                                value="1" <?php checked(get_option('smap_message_enable_' . $status, 1)); ?> />
                            <?php echo esc_html($label); ?>:
                        </label>
                        <div style="display: flex; align-items: center; gap: 10px;">
						
						<?php 
						// translators: %s: The new status label for the order.
							$smap_default_message = esc_html__('The status of your order is now %s. Thank you for your trust. [order_id]', 'sms-mobile-api');

						?>
                            <input style="width:100%!important" type="text" name="smap_message_<?php echo esc_attr($status); ?>"
                                value="<?php echo esc_attr(get_option('smap_message_' . $status, sprintf($smap_default_message, $label))); ?>" />
                        </div>
                        <br/>
                    <?php endforeach; ?>
                    <i class="fa-solid fa-heart"></i>
                    <?php esc_html_e('Customize your SMS 100% with your own rules.', 'sms-mobile-api'); ?>
                    <a href="admin.php?page=smap_rule_manager">
                        <?php esc_html_e('Click here to create your rules', 'sms-mobile-api'); ?>
                    </a>
                </td>
            </tr>
        </table>
        <?php submit_button(__('Save Changes', 'sms-mobile-api'), 'primary', 'submit'); ?>

        <h2>
            <a name="tip" style="color:#0073aa">
                <i class="fa-solid fa-circle-info"></i>
                <?php esc_html_e('Tips and good to know', 'sms-mobile-api'); ?>
            </a>
        </h2>
        <hr>
        <b><?php esc_html_e('Tips :', 'sms-mobile-api'); ?></b><br><br>
        - <?php echo wp_kses_post('Use <b>\\n</b> to define a line break in your messages.', 'sms-mobile-api'); ?><br><br>

        <b><?php esc_html_e('Placeholder to insert in your message for full customization :', 'sms-mobile-api'); ?></b><br>
        <br>
        <font color="#2271b1"><?php esc_html_e("Use any [meta_key] from the order's post_meta :", 'sms-mobile-api'); ?></font><br>
      <?php 
echo wp_kses_post( 
    'This feature allows you to dynamically insert any order-related data into SMS or WhatsApp messages by using placeholders based on meta_key values from the order’s post_meta.<br>
      It supports both default WooCommerce fields and custom fields added by third-party plugins.', 'sms-mobile-api');
?>
        <br>
        <div style="margin-left:30px">
            <?php esc_html_e('Example:', 'sms-mobile-api'); ?><br>
            <?php esc_html_e('If an order contains from post_meta table:', 'sms-mobile-api'); ?><br>
            META_KEY : <font color=blue>_tracking_number</font> → ABC123456<br>
            META_KEY : <font color=blue>_custom_note</font> → Urgent order, fast shipping!<br>
            <?php esc_html_e('A message template like:', 'sms-mobile-api'); ?><br>
            <i>
                <?php esc_html_e('Your order [order_id] has been shipped! Tracking:', 'sms-mobile-api'); ?>
                <font color=blue>[_tracking_number]</font>.
                <?php esc_html_e('Note:', 'sms-mobile-api'); ?>
                <font color=blue>[_custom_note]</font>
            </i>
        </div>

        <br><br>
        <font color="#2271b1"><?php esc_html_e('Use the placeholder provided by WooCommerce by default :', 'sms-mobile-api'); ?></font> <br>
        <p class="description">
            <b><?php esc_html_e('For example :', 'sms-mobile-api'); ?></b>
            <?php esc_html_e('Hello', 'sms-mobile-api'); ?> <font color=blue>[billing_first_name]</font>,
            <?php esc_html_e('thanks for your order ! Here your transaction id :', 'sms-mobile-api'); ?>
            <font color=blue>[transaction_id]</font>
            <?php esc_html_e('for a total of', 'sms-mobile-api'); ?>
            <font color=blue>[order_total]</font> <font color=blue>[order_currency]</font>
        </p>
      <br><br>
<b>[order_id]</b> : <?php echo esc_html__('The unique identifier of the order.', 'sms-mobile-api'); ?> <br>
<b>[order_status]</b> : <?php echo esc_html__('The current status of the order (e.g., processing, completed, refunded).', 'sms-mobile-api'); ?> <br>
<b>[order_total]</b> : <?php echo esc_html__('The total amount of the order including taxes and shipping.', 'sms-mobile-api'); ?> <br>
<b>[order_currency]</b> : <?php echo esc_html__('The currency in which the order was placed.', 'sms-mobile-api'); ?> <br>
<b>[order_payment_method]</b> : <?php echo esc_html__('The payment method used for the order (e.g., PayPal, Stripe, Bank Transfer).', 'sms-mobile-api'); ?> <br>
<b>[order_payment_title]</b> : <?php echo esc_html__('The display title of the payment method used.', 'sms-mobile-api'); ?> <br>
<b>[order_transaction_id]</b> : <?php echo esc_html__('The transaction ID associated with the payment.', 'sms-mobile-api'); ?> <br>
<b>[order_discount_total]</b> : <?php echo esc_html__('The total discount applied to the order.', 'sms-mobile-api'); ?> <br>
<b>[order_discount_tax]</b> : <?php echo esc_html__('The tax amount applied to the discount.', 'sms-mobile-api'); ?> <br>
<b>[order_shipping_total]</b> : <?php echo esc_html__('The total shipping cost of the order.', 'sms-mobile-api'); ?> <br>
<b>[order_shipping_tax]</b> : <?php echo esc_html__('The tax amount applied to the shipping cost.', 'sms-mobile-api'); ?> <br>
<b>[order_tax_total]</b> : <?php echo esc_html__('The total tax amount applied to the order.', 'sms-mobile-api'); ?> <br>
<b>[order_subtotal]</b> : <?php echo esc_html__('The subtotal of the order before taxes and shipping.', 'sms-mobile-api'); ?> <br>
<b>[order_key]</b> : <?php echo esc_html__('A unique key assigned to the order for security and tracking purposes.', 'sms-mobile-api'); ?> <br>
<b>[order_cart_hash]</b> : <?php echo esc_html__('A hash representing the contents of the cart when the order was placed.', 'sms-mobile-api'); ?> <br>
<b>[order_created_via]</b> : <?php echo esc_html__('Indicates how the order was created (e.g., store-api, admin, checkout).', 'sms-mobile-api'); ?> <br>
<b>[order_ip_address]</b> : <?php echo esc_html__('The IP address of the customer when placing the order.', 'sms-mobile-api'); ?> <br>
<b>[order_user_agent]</b> : <?php echo esc_html__('The browser user agent of the customer when placing the order.', 'sms-mobile-api'); ?> <br>
<br>
<b>[order_date_created]</b> : <?php echo esc_html__('The date and time when the order was created.', 'sms-mobile-api'); ?> <br>
<b>[order_date_modified]</b> : <?php echo esc_html__('The date and time when the order was last modified.', 'sms-mobile-api'); ?> <br>
<b>[order_date_paid]</b> : <?php echo esc_html__('The date and time when the order was marked as paid.', 'sms-mobile-api'); ?> <br>
<b>[order_date_completed]</b> : <?php echo esc_html__('The date and time when the order was marked as completed.', 'sms-mobile-api'); ?> <br>
<br>
<b>[customer_id]</b> : <?php echo esc_html__('The unique identifier of the customer.', 'sms-mobile-api'); ?> <br>
<b>[customer_email]</b> : <?php echo esc_html__('The email address of the customer.', 'sms-mobile-api'); ?> <br>
<b>[customer_phone]</b> : <?php echo esc_html__('The phone number of the customer.', 'sms-mobile-api'); ?> <br>
<br>
<b>[billing_first_name]</b> : <?php echo esc_html__('The first name of the customer in the billing address.', 'sms-mobile-api'); ?> <br>
<b>[billing_last_name]</b> : <?php echo esc_html__('The last name of the customer in the billing address.', 'sms-mobile-api'); ?> <br>
<b>[billing_company]</b> : <?php echo esc_html__('The company name in the billing address.', 'sms-mobile-api'); ?> <br>
<b>[billing_address_1]</b> : <?php echo esc_html__('The primary address line in the billing address.', 'sms-mobile-api'); ?> <br>
<b>[billing_address_2]</b> : <?php echo esc_html__('The secondary address line in the billing address.', 'sms-mobile-api'); ?> <br>
<b>[billing_city]</b> : <?php echo esc_html__('The city in the billing address.', 'sms-mobile-api'); ?> <br>
<b>[billing_state]</b> : <?php echo esc_html__('The state or region in the billing address.', 'sms-mobile-api'); ?> <br>
<b>[billing_postcode]</b> : <?php echo esc_html__('The postal/ZIP code in the billing address.', 'sms-mobile-api'); ?> <br>
<b>[billing_country]</b> : <?php echo esc_html__('The country in the billing address.', 'sms-mobile-api'); ?> <br>
<br>
<b>[shipping_first_name]</b> : <?php echo esc_html__('The first name of the recipient in the shipping address.', 'sms-mobile-api'); ?> <br>
<b>[shipping_last_name]</b> : <?php echo esc_html__('The last name of the recipient in the shipping address.', 'sms-mobile-api'); ?> <br>
<b>[shipping_company]</b> : <?php echo esc_html__('The company name in the shipping address.', 'sms-mobile-api'); ?> <br>
<b>[shipping_address_1]</b> : <?php echo esc_html__('The primary address line in the shipping address.', 'sms-mobile-api'); ?> <br>
<b>[shipping_address_2]</b> : <?php echo esc_html__('The secondary address line in the shipping address.', 'sms-mobile-api'); ?> <br>
<b>[shipping_city]</b> : <?php echo esc_html__('The city in the shipping address.', 'sms-mobile-api'); ?> <br>
<b>[shipping_state]</b> : <?php echo esc_html__('The state or region in the shipping address.', 'sms-mobile-api'); ?> <br>
<b>[shipping_postcode]</b> : <?php echo esc_html__('The postal/ZIP code in the shipping address.', 'sms-mobile-api'); ?> <br>
<b>[shipping_country]</b> : <?php echo esc_html__('The country in the shipping address.', 'sms-mobile-api'); ?> <br>
<b>[shipping_phone]</b> : <?php echo esc_html__('The phone number associated with the shipping address.', 'sms-mobile-api'); ?> <br>
<br>
<b>[order_items]</b> : <?php echo esc_html__('A list of the ordered products with quantity (e.g., "Product A (x2), Product B (x1)").', 'sms-mobile-api'); ?> <br>
<b>[shipping_method]</b> : <?php echo esc_html__('The shipping method used for the order (e.g., Standard Shipping, Express Delivery).', 'sms-mobile-api'); ?> <br>
<b>[shipping_tracking_number]</b> : <?php echo esc_html__('The tracking number for the shipped order (if available).', 'sms-mobile-api'); ?> <br>
<br>
<b>[customer_note]</b> : <?php echo esc_html__('Any note provided by the customer during checkout.', 'sms-mobile-api'); ?> <br>
<b>[transaction_id]</b> : <?php echo esc_html__('The transaction ID associated with the payment (same as [order_transaction_id]).', 'sms-mobile-api'); ?> <br>
<b>[order_notes]</b> : <?php echo esc_html__('Any internal order notes added by the store admin or system.', 'sms-mobile-api'); ?> <br>


          
        </form>
    </div>
    <?php
}

// Page pour afficher les logs à partir de la base de données

function smap_whatsApp_config_page()
{
	    $smap_shop_key = sanitize_text_field(get_option('smap_shop_key'));
		?>
		
	<h3><?php echo esc_html__('WhatsApp Config', 'sms-mobile-api'); ?></h3>
<?php echo esc_html__('It is imperative to first configure the communication between your WhatsApp account and SMSMobileAPI to enable the WooCommerce plugin to send WhatsApp messages.', 'sms-mobile-api'); ?>
<br>
<?php echo esc_html__('The WooCommerce plugin interacts with the SMSMobileAPI service, which in turn communicates with your WhatsApp account.', 'sms-mobile-api'); ?>
<br><br>
<?php echo esc_html__('This setup requires configuration through your secure SMSMobileAPI dashboard.', 'sms-mobile-api'); ?><br>
<?php echo esc_html__('Log in now to configure the connection with WhatsApp.', 'sms-mobile-api'); ?>
<br>
<b><?php echo esc_html__('For security reasons, authentication must be performed through the SMSMobileAPI dashboard.', 'sms-mobile-api'); ?></b>
<br><br>
<?php echo esc_html__('I already have an SMSMobileAPI account', 'sms-mobile-api'); ?><br>
<form action="https://smsmobileapi.com/connect" method="POST" target="_blank" style="display: inline-block; margin-right: 10px;">
    <button class="button button-primary">
        <span class="Polaris-Text--root Polaris-Text--bodySm Polaris-Text--medium">
            <div style="display: flex; align-items: center;">
                <?php echo esc_html__('Log in to SMSMobileAPI dashboard', 'sms-mobile-api'); ?>
            </div>
        </span>
    </button>
</form>
<br><br>
<?php echo esc_html__("I don't have an SMSMobileAPI account yet", 'sms-mobile-api'); ?><br>
<form action="https://smsmobileapi.com/signup/?source_page=wa/" method="POST" target="_blank">
    <button class="button button-primary">
        <span class="Polaris-Text--root Polaris-Text--bodySm Polaris-Text--medium">
            <div style="display: flex; align-items: center;">
                <?php echo esc_html__('Create a free account', 'sms-mobile-api'); ?>
            </div>
        </span>
    </button>
</form>


		<?php 
	
}
function smap_support()
{
	
  ?>
<div class="wrap">
    <h1><?php esc_html_e('Support Request', 'sms-mobile-api'); ?></h1>
    <p><?php esc_html_e('If you have any issue, send a request to our support team.', 'sms-mobile-api'); ?></p>
    <?php if (esc_attr(get_option('smap_api_key')) == "") { ?>
        <b><span style="color:red;"><?php esc_html_e('You must have an account and a registered API key to submit a request online.', 'sms-mobile-api'); ?></span></b>
        <br>
        <?php esc_html_e("If you don't have a SMSMobileAPI account yet, create one for free now.", 'sms-mobile-api'); ?>
        <br>
        <?php esc_html_e('Or go to the <a href="admin.php?page=sms-notification-plugin">Settings</a> menu to enter your API key.', 'sms-mobile-api'); ?>
        <br>
        <a href="https://smsmobileapi.com/get-api-key-for-woocommerce/" target="_blank" class="button button-secondary" style="margin-top:10px; background-color:#00aa63; color:#ffffff; border-style:none; border-radius:10px; font-weight:bold">
            <i class="fa-solid fa-key"></i> <?php esc_html_e('Click here to get a free API key', 'sms-mobile-api'); ?>
        </a>
    <?php } else { ?>
        <?php esc_html_e('No need to include your contact information; we already have all the details through your API key.', 'sms-mobile-api'); ?>
    <?php } ?>

    <form id="smap-support-form">
        <table class="form-table">
            <input type="hidden" id="smap_apikey" name="apikey" value="<?php echo esc_attr(get_option('smap_api_key')); ?>" readonly style="width: 100%;">
            <tr>
                <th>
                    <label for="smap_request"><?php esc_html_e('Your Request', 'sms-mobile-api'); ?>:</label><br><br>
                    <textarea id="smap_request" name="request" rows="5" required style="width: 100%;"></textarea>
                    <br><br>
                    <button type="submit" class="button button-primary" <?php if (esc_attr(get_option('smap_api_key')) == "") { ?> disabled <?php } ?>>
                        <?php esc_html_e('Send Request', 'sms-mobile-api'); ?>
                    </button>
                    <div id="smap-response" style="margin-top: 15px;"></div>
                </th>
            </tr>
        </table>
    </form>
</div>

<?php
$smap_i18n = [
    'sending_request' => esc_html__('Sending request...', 'sms-mobile-api'),
    'success_message' => esc_html__('Your message has been successfully sent! <br>You will receive a response as soon as possible.', 'sms-mobile-api'),
    'error_prefix'    => esc_html__('Error:', 'sms-mobile-api'),
    'response_prefix' => esc_html__('Response:', 'sms-mobile-api'),
];
?>
<script>

</script>


<script>

jQuery(document).ready(function($) {
    $('#smap-support-form').submit(function(e) {
		
		var smap_i18n = {
    sending_request: "<?php echo esc_js($smap_i18n['sending_request']); ?>",
    success_message: "<?php echo esc_js($smap_i18n['success_message']); ?>",
    error_prefix: "<?php echo esc_js($smap_i18n['error_prefix']); ?>",
    response_prefix: "<?php echo esc_js($smap_i18n['response_prefix']); ?>"
};


        e.preventDefault();

        let formData = {
            apikey: $('#smap_apikey').val(),
            request: $('#smap_request').val()
        };

        $.ajax({
            url: 'https://api.smsmobileapi.com/admin/support/sendrequest/',
            type: 'POST',
            data: formData,
            dataType: 'json',
            beforeSend: function() {
                $('#smap-response').html('<p style="color: blue;">' + smap_i18n.sending_request + '</p>');
            },
            success: function(response) {
                if (response.success) {
                    $('#smap-response').html('<p style="color: green;">' + smap_i18n.success_message + '</p>');
                    $('#smap-support-form')[0].reset();
                } else {
                    $('#smap-response').html('<p style="color: red;">' + response.message + '</p>');
                }
            },
            error: function(xhr, status, error) {
                console.error("AJAX Error: ", xhr.responseText);
                $('#smap-response').html(
                    '<p style="color: red;">' + smap_i18n.error_prefix + ' ' + xhr.status + ' - ' + xhr.statusText + '</p>' +
                    '<p>' + smap_i18n.response_prefix + ' ' + xhr.responseText + '</p>'
                );
            }
        });
    });
});
</script>

    <?php

}
function smap_logs_wa_page()
{
	$smap_shop_key = sanitize_text_field(get_option('smap_shop_key'));
$api_url = esc_url_raw('https://api.smsmobileapi.com/woocommerce/log/list/?smap_shop_key=' . urlencode($smap_shop_key) . '&list=wa');

$response = wp_remote_get($api_url, array(
    'timeout' => 10,
    'sslverify' => false // SSL verification disabled (should be true in production)
));

$logs = json_decode(wp_remote_retrieve_body($response), true);

if (json_last_error() !== JSON_ERROR_NONE) {
    echo '<div class="notice notice-error"><p><strong>' . esc_html__('Error:', 'sms-mobile-api') . '</strong> ' . esc_html__('Invalid response format from the API.', 'sms-mobile-api') . '</p></div>';
    return;
}
?>
<div class="wrap">
    <h1><?php esc_html_e('WhatsApp Logs', 'sms-mobile-api'); ?></h1>
    <p><?php esc_html_e('By default, the last 90 logs are displayed.', 'sms-mobile-api'); ?></p>
    <p>
        <?php esc_html_e('This log displays the communication between your store and the SMSMobileAPI. It helps you verify that your store is correctly triggering the API to send messages.', 'sms-mobile-api'); ?>
        <br>
        <?php esc_html_e('However, even if the API call is successful, it is important to always check that your mobile device or your connected WhatsApp account is actually sending the message. The API only initiates the request — the final delivery depends on your phone\'s availability and network status.', 'sms-mobile-api'); ?>
    </p>
    <table class="wp-list-table widefat fixed striped">
        <thead>
            <tr>
                <th scope="col" style="width:20%;"><?php esc_html_e('Log Time', 'sms-mobile-api'); ?></th>
                <th scope="col" style="width:50%;"><?php esc_html_e('Action & WhatsApp Sent', 'sms-mobile-api'); ?></th>
                <th scope="col" style="width:15%;"><?php esc_html_e('Order ID', 'sms-mobile-api'); ?></th>
                <th scope="col" style="width:15%;"><?php esc_html_e('User ID', 'sms-mobile-api'); ?></th>
            </tr>
        </thead>
        <tbody>
            <?php
            if (!empty($logs['logs'])) {
                foreach ($logs['logs'] as $log) {
                    $log_time = trim($log['log_time']);
                    $action = trim($log['action']);
                    $order_id = trim($log['order_id']);
                    $ser_id = trim($log['ser_id']);
                    $message = trim($log['message']);
                    $statut_error = $log['statut_error'];

                    // Color row
                    $row_style = '';
                    if ($statut_error === 'ok') {
                        $row_style = 'background-color:#d5fdd5;';
                    } elseif (!empty($statut_error)) {
                        $row_style = 'background-color:#fdd5d5;';
                    }

                    // Error display
                    if (!empty($statut_error) && $statut_error !== 'ok') {
                        $log_time .= ' [' . esc_html($statut_error) . ']';
                    }

                    $cell_style = 'style="border-bottom:1px solid #ccc;padding:8px;"';

                    echo '<tr style="' . esc_attr($row_style) . '">';
                    echo '<td ' . esc_attr($cell_style) . '>' . esc_html($log_time) . '</td>';
                    echo '<td ' . esc_attr($cell_style) . '><b>' . esc_html($action) . '</b><br>' . esc_html($message) . '</td>';
                    echo '<td ' . esc_attr($cell_style) . '>' . esc_html($order_id) . '</td>';
                    echo '<td ' . esc_attr($cell_style). '>' . esc_html($ser_id) . '</td>';
                    echo '</tr>';
                }
            } else {
                echo '<tr><td colspan="4">' . esc_html__('No logs found for this shop key.', 'sms-mobile-api') . '</td></tr>';
            }
            ?>
        </tbody>
    </table>
</div>
<?php 
}

function smap_subscriptions_page()
{
	
$smap_shop_key = sanitize_text_field(get_option('smap_shop_key'));
$api_key = get_option('smap_api_key');

$url_abonnement =  "https://dashboard.smsmobileapi.com/?autoconnect=yes&key=" . urlencode($api_key) . "&smap_shop_key=" . urlencode($smap_shop_key) . "&to=sub";
?>
<h3><?php esc_html_e('Subscription', 'sms-mobile-api'); ?></h3>
<br>
<form action="<?php echo esc_url($url_abonnement); ?>" method="POST" target="_blank" style="display: inline-block; margin-right: 10px;">
    <button class="button button-primary">
        <span class="Polaris-Button__Content"><?php esc_html_e('Manage my subscription', 'sms-mobile-api'); ?></span>
    </button>
</form>
<br><br>
<?php esc_html_e('Why is the API connection paid while the WooCommerce Plugin is free?', 'sms-mobile-api'); ?>
<br><br>
<?php esc_html_e('We’re proud to offer our WooCommerce Plugin completely free of charge, along with free technical support.', 'sms-mobile-api'); ?><br>
<?php esc_html_e('Our goal is to make it as easy as possible for you to manage your online store without worrying about extra costs.', 'sms-mobile-api'); ?>
<br><br>
<?php esc_html_e('However, the only paid aspect of our service is the API connection that enables communication between WooCommerce and your mobile phone.', 'sms-mobile-api'); ?><br>
<?php esc_html_e('Developing, maintaining, and evolving this API requires significant resources, both in terms of hardware and human expertise.', 'sms-mobile-api'); ?>
<br><br>
<?php esc_html_e('Additionally, we take your data privacy very seriously. None of your data is sold to third parties or exploited in any way.', 'sms-mobile-api'); ?><br>
<?php esc_html_e('All information is securely handled and used solely for the purpose of ensuring seamless communication between your WooCommerce store and your mobile device.', 'sms-mobile-api'); ?>
<br><br>
<?php esc_html_e('It\'s important to highlight that while we charge for the API connection, we do not charge anything for sending SMS notifications, as these are sent using your own mobile subscription.', 'sms-mobile-api'); ?>
<br><br>
<?php esc_html_e('In summary, the WooCommerce Plugin itself, along with our support services, is free.', 'sms-mobile-api'); ?><br>
<br>
<?php esc_html_e('The cost for the API connection helps us continue to provide a reliable and robust service that bridges your WooCommerce store with your mobile device, ensuring that your operations run smoothly while keeping your data secure and private.', 'sms-mobile-api'); ?>
<br><br>
<?php esc_html_e('No matter if you send 200 SMS or 200,000 SMS, the cost remains the same through our API.', 'sms-mobile-api'); ?>

<?php 
}
function smap_logs_page() {
    $smap_shop_key = sanitize_text_field(get_option('smap_shop_key'));

    $api_url = esc_url_raw('https://api.smsmobileapi.com/woocommerce/log/list/?smap_shop_key=' . urlencode($smap_shop_key).'&list=sms');

    $response = wp_remote_get($api_url, array(
        'timeout' => 10,
        'sslverify' => false // Vérification SSL activée pour des raisons de sécurité
    ));

    $logs = json_decode(wp_remote_retrieve_body($response), true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        echo '<div class="notice notice-error"><p><strong>Error:</strong> Invalid response format from the API.</p></div>';
        return;
    }

    ?><div class="wrap">
    <h1><?php esc_html_e('SMS Logs', 'sms-mobile-api'); ?></h1>
    <p><?php esc_html_e('By default, the last 90 logs are displayed.', 'sms-mobile-api'); ?></p>
    <p>
        <?php esc_html_e('This log displays the communication between your store and the SMSMobileAPI.', 'sms-mobile-api'); ?><br>
        <?php esc_html_e('It helps you verify that your store is correctly triggering the API to send messages.', 'sms-mobile-api'); ?><br>
        <?php esc_html_e('However, even if the API call is successful, it is important to always check that your mobile device or your connected WhatsApp account is actually sending the message. The API only initiates the request — the final delivery depends on your phone\'s availability and network status.', 'sms-mobile-api'); ?>
    </p>

    <table class="wp-list-table widefat fixed striped">
        <thead>
            <tr>
                <th scope="col" style="width:20%;"><?php esc_html_e('Log Time', 'sms-mobile-api'); ?></th>
                <th scope="col" style="width:50%;"><?php esc_html_e('Action & SMS Sent', 'sms-mobile-api'); ?></th>
                <th scope="col" style="width:15%;"><?php esc_html_e('Order ID', 'sms-mobile-api'); ?></th>
                <th scope="col" style="width:15%;"><?php esc_html_e('User ID', 'sms-mobile-api'); ?></th>
            </tr>
        </thead>
        <tbody>
            <?php
            if (!empty($logs['logs'])) {
                foreach ($logs['logs'] as $log) {
                    $log_time = trim($log['log_time']);
                    $action = trim($log['action']);
                    $order_id = trim($log['order_id']);
                    $ser_id = trim($log['ser_id']);
                    $message  = trim($log['message']);
                    $statut_error = $log['statut_error'];

                    // Row color
                    $row_style = '';
                    if ($statut_error === 'ok') {
                        $row_style = 'background-color:#d5fdd5;';
                    } elseif (!empty($statut_error)) {
                        $row_style = 'background-color:#fdd5d5;';
                    }

                    // Error info after time
                    if (!empty($statut_error) && $statut_error !== 'ok') {
                        $log_time .= ' [' . esc_html($statut_error) . ']';
                    }
                    $cell_style = 'style="border-bottom:1px solid #ccc;padding:8px;"';

                    echo '<tr style="' . esc_attr($row_style) . '">';
                    echo '<td ' . esc_attr($cell_style) . '>' . esc_html($log_time) . '</td>';
                    echo '<td ' . esc_attr($cell_style) . '><b>' . esc_html($action) . '</b><br>' . esc_html($message) . '</td>';
                    echo '<td ' . esc_attr($cell_style) . '>' . esc_html($order_id) . '</td>';
                    echo '<td ' . esc_attr($cell_style) . '>' . esc_html($ser_id) . '</td>';
                    echo '</tr>';
                }
            } else {
                echo '<tr><td colspan="4">' . esc_html__('No logs found for this shop key.', 'sms-mobile-api') . '</td></tr>';
            }
            ?>
        </tbody>
    </table>
</div>

    <?php
}

function smap_register_settings() {
register_setting(
    'smap_settings_group',
    'smap_api_key',
    array(
        'type'              => 'string',
        'sanitize_callback' => 'sanitize_text_field',
    )
);

register_setting(
    'smap_settings_group',
    'smap_test_phone',
    array(
        'type'              => 'string',
        'sanitize_callback' => 'sanitize_text_field',
    )
);

register_setting(
    'smap_settings_group',
    'smap_order_confirmation_sms',
    array(
        'type'              => 'string',
        'sanitize_callback' => 'sanitize_textarea_field',
    )
);

register_setting(
    'smap_settings_group',
    'smap_order_status_change_sms',
    array(
        'type'              => 'string',
        'sanitize_callback' => 'sanitize_textarea_field',
    )
);

register_setting(
    'smap_settings_group',
    'smap_thankyou_sms_message',
    array(
        'type'              => 'string',
        'sanitize_callback' => 'sanitize_textarea_field',
    )
);

register_setting(
    'smap_settings_group',
    'smap_sendsms',
    array(
        'type'              => 'string',
        'sanitize_callback' => 'sanitize_text_field',
    )
);

register_setting(
    'smap_settings_group',
    'smap_sendwa',
    array(
        'type'              => 'string',
        'sanitize_callback' => 'sanitize_text_field',
    )
);

	


    $statuses = [
		'wc-pending', 'wc-processing', 'wc-on-hold', 'wc-completed', 'wc-cancelled',
		'wc-refunded', 'wc-failed', 'wc-checkout-draft', 'wc-shipped', 'wc-delivered',
		'wc-partially-refunded', 'wc-returned', 'wc-awaiting-payment', 'wc-pre-order', 'wc-invoiced'
	];

	foreach ($statuses as $status) {
		register_setting(
			'smap_settings_group',
			'smap_message_' . $status,
			array(
				'type'              => 'string',
				'sanitize_callback' => 'sanitize_textarea_field',
			)
		);
	}
}
add_action('admin_init', 'smap_register_settings');

// Fonction pour tester l'API
function smap_test_api_call() {
    $phone_number = get_option('smap_test_phone');
    $api_key = get_option('smap_api_key');
    $message = "Test SMS API from WooCommerce Plugin SMS-MOBILE-API";


$smap_sendsms = get_option('smap_sendsms');
$smap_sendwa = get_option('smap_sendwa');


    if (empty($phone_number)) {
        echo '<div class="notice notice-error"><p>Please enter a phone number for testing.</p></div>';
        smap_insert_log_entry("API TEST : Test SMS failed: missing phone number", 0, 0,$smap_sendsms,$smap_sendwa);
        return;
    }






	
	
	$url = "https://api.smsmobileapi.com/sendsms/?recipients=" . urlencode($phone_number) . "&message=" . urlencode($message) . "&apikey=" . urlencode($api_key) . "&from=woocommerce&sendsms=" . $smap_sendsms . "&sendwa=" . $smap_sendwa;

		$response = wp_remote_post($url, array(
			'method'    => 'POST',
			'headers'   => array('Content-Type' => 'application/x-www-form-urlencoded'),
			'timeout'   => 10,
			'sslverify' => false,
		));

		// Gestion des erreurs WordPress
		if (is_wp_error($response)) {
			$error_message = $response->get_error_message();
			smap_insert_log_entry("WP_Error during test Message: $error_message", 0, 0, $smap_sendsms, $smap_sendwa, '', array(), sanitize_text_field($message), "WP_Error");
			return;
		}

		// Analyse du code HTTP
		$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 during test Message", 0, 0, $smap_sendsms, $smap_sendwa, $response_body, array(), sanitize_text_field($message), "HTTP error");
			return;
		}

		// Vérification du contenu de la réponse
		if (stripos($response_body, '"error":1') !== false || stripos($response_body, 'sent":"0"') !== false) {
			smap_insert_log_entry("API Error during test Message: $response_body", 0, 0, $smap_sendsms, $smap_sendwa, $response_body, array(), sanitize_text_field($message), "API Error");
			return;
		}

// Succès
smap_insert_log_entry("Test Message successfully sent to $phone_number", 0, 0, $smap_sendsms, $smap_sendwa, $response_body, array(), sanitize_text_field($message), "ok");

	
	
	
	
if($smap_sendsms == "1")
{
   // translators: %s: The destination phone number for the test SMS.
$success_msg_sms_text = esc_html__('Test SMS sent to %s', 'sms-mobile-api');
$success_msg_sms = sprintf($success_msg_sms_text, esc_html($phone_number));
    echo '<div class="notice notice-success"><p>' . esc_html($success_msg_sms) . '</p></div>';
    ?>
    <script>alert('<?php echo esc_js($success_msg_sms); ?>');</script>
    <?php 
}
if($smap_sendwa == "1")
{
	   // translators: %s: The destination phone number for the test WA.	
    $success_msg_wa_text = esc_html__('Test WhatsApp Message sent to %s', 'sms-mobile-api');
	$success_msg_wa = sprintf($success_msg_wa_text, esc_html($phone_number));
    echo '<div class="notice notice-success"><p>' . esc_html($success_msg_wa) . '</p></div>';
    ?>
    <script>alert('<?php echo esc_js($success_msg_wa); ?>');</script>
    <?php 
}


}
?>
