<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
// Ajouter une nouvelle colonne pour "Send SMS"
function smap_add_sms_column($columns) {
    $columns['send_sms'] = 'Send SMS / Whatsapp';
    return $columns;
}
add_filter('manage_users_columns', 'smap_add_sms_column');

// Contenu de la colonne "Send SMS"
function smap_show_send_sms_column($value, $column_name, $user_id) {
	
$smap_sendsms = get_option('smap_sendsms');
$smap_sendwa = get_option('smap_sendwa');


    if ($column_name == 'send_sms') {
        // Échappement des attributs
        $nonce = wp_create_nonce('smap_send_sms');
        return '<button class="button button-primary smap-send-sms-button" data-user-id="' . esc_attr($user_id) . '" 
		data-phone-number="' . esc_attr(get_user_meta($user_id, 'billing_phone', true)) . '"
		data-nonce="' . esc_attr($nonce) . '"
		data-smap_sendsms="' . esc_attr($smap_sendsms) . '"
		data-smap_sendwa="' . esc_attr($smap_sendwa) . '"
		
		
		>Send SMS / Whatsapp</button>';
    }
    return $value;
}
add_action('manage_users_custom_column', 'smap_show_send_sms_column', 10, 3);

// Ajouter les scripts nécessaires pour le popup
function smap_enqueue_sms_scripts() {
    $version = '2.0.17'; // Ajouter la version des scripts pour éviter les problèmes de cache
    wp_enqueue_script('jquery');
    wp_enqueue_script('smap-sms-script', plugin_dir_url(__FILE__) . 'smap-sms-script.js', array('jquery'), $version, true);
    wp_enqueue_style('smap-sms-style', plugin_dir_url(__FILE__) . 'smap-sms-style.css', array(), $version);
}
add_action('admin_enqueue_scripts', 'smap_enqueue_sms_scripts');

// Fonction pour envoyer le SMS via AJAX
function smap_send_sms_to_user() {
    // Vérification des capacités de l'utilisateur
    if (!current_user_can('manage_woocommerce')) {
        wp_send_json_error('Permission denied');
    }

    // Vérification du nonce pour la sécurité
    if (
    !isset($_POST['smap_nonce']) ||
    !wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['smap_nonce'] ) ), 'smap_send_sms' )
) {
    wp_send_json_error('Nonce verification failed');
    wp_die();
}
    // Validation et sanitisation des données
    if (!isset($_POST['user_id']) || !isset($_POST['message'])) {
        wp_send_json_error('Missing user_id or message');
    }

    $user_id = intval($_POST['user_id']);
    $message = sanitize_text_field(wp_unslash($_POST['message']));
    $phone_number = sanitize_text_field(get_user_meta($user_id, 'billing_phone', true));

    // Vérification de l'existence du numéro de téléphone
    if (empty($phone_number)) {
        wp_send_json_error('No phone number found');
    }


if (!empty($_POST['smap_sendsms'])) {
    $smap_sendsms = sanitize_text_field(wp_unslash($_POST['smap_sendsms']));
} else {
    $smap_sendsms = '';
}

if (isset($_POST['smap_sendwa'])) {
    $smap_sendwa = sanitize_text_field(wp_unslash($_POST['smap_sendwa']));
} else {
    $smap_sendwa = '';
}
    // Récupération de l'API key depuis les options et validation
    $api_key = sanitize_text_field(get_option('smap_api_key'));
    $url = esc_url_raw("https://api.smsmobileapi.com/sendsms/");

  // Préparation de la requête avec validation et sanitisation
$body = array(
    'recipients' => sanitize_text_field($phone_number),
    'message'    => sanitize_text_field($message),
    'apikey'     => sanitize_text_field($api_key),
    'from'       => 'woocommerce',
    'sendsms'    => $smap_sendsms,
    'sendwa'     => $smap_sendwa
);

// Envoi de la requête
$response = wp_remote_post($url, array(
    'method'    => 'POST',
    'body'      => $body,
    'timeout'   => 10,
    'sslverify' => false,
));

// Analyse de la réponse
if (is_wp_error($response)) {
    $error_message = $response->get_error_message();
    SMAP_insert_log_entry("WP_Error while sending SMS to $phone_number for user ID $user_id. Error: $error_message", 0, $user_id, $smap_sendsms, $smap_sendwa,'','',sanitize_text_field($message),"WP_Error");
    wp_send_json_error('Failed to send SMS (connection error)');
} else {
    $response_code = wp_remote_retrieve_response_code($response);
    $response_body = wp_remote_retrieve_body($response);

    if ($response_code !== 200) {
        SMAP_insert_log_entry("HTTP error $response_code while sending SMS to $phone_number for user ID $user_id", 0, $user_id, $smap_sendsms, $smap_sendwa, $response_body,"",sanitize_text_field($message),"HTTP error");
        wp_send_json_error("Failed to send SMS (HTTP $response_code)");
    }

    // Analyse du contenu JSON (si l’API retourne du JSON)
    $json = json_decode($response_body, true);

    if (
        (isset($json['error']) && $json['error'] == 1) ||
        (isset($json['sent']) && $json['sent'] == "0")
    ) {
        SMAP_insert_log_entry("API Error while sending SMS to $phone_number for user ID $user_id. Response: $response_body", 0, $user_id, $smap_sendsms, $smap_sendwa, $response_body,"",sanitize_text_field($message),"API Error");
        wp_send_json_error('Failed to send SMS (API error)');
    }

    // ✅ Succès
    SMAP_insert_log_entry("SMS sent successfully to $phone_number for user ID $user_id (From users listing)", 0, $user_id, $smap_sendsms, $smap_sendwa, $response_body,"",sanitize_text_field($message),"ok");
    wp_send_json_success('SMS sent successfully');
}

}
add_action('wp_ajax_smap_send_sms_to_user', 'smap_send_sms_to_user');
?>
