// 1. Fetch the list of unique conversations from crm_communications
add_action('wp_ajax_cc_get_sms_threads', 'cc_get_sms_threads_callback');
function cc_get_sms_threads_callback() {
    global $wpdb;
    $comm_table = $wpdb->prefix . 'crm_communications'; // Corrected table name
    $client_table = $wpdb->prefix . 'crm_clients';
    $current_user_id = get_current_user_id();

    // President/Admin sees all; Advisors see only their clients
    $where = "";
    if (current_user_can('crm_advisor') && !current_user_can('manage_options')) {
        $where = $wpdb->prepare(" WHERE c.advisor_id = %d", $current_user_id);
    }

    $threads = $wpdb->get_results("
        SELECT m.content, m.created_at, c.id as client_id, c.first_name, c.last_name, c.mobile_number 
        FROM $comm_table m
        JOIN $client_table c ON m.client_id = c.id
        INNER JOIN (SELECT MAX(id) as id FROM $comm_table WHERE comm_type = 'sms' GROUP BY client_id) m2 ON m.id = m2.id
        $where
        ORDER BY m.created_at DESC LIMIT 30
    ");

    if (empty($threads)) { wp_send_json_success('<div style="padding:20px; text-align:center; color:#999;">No conversations yet.</div>'); }

    $html = '';
    foreach ($threads as $t) {
        $name = $t->first_name . ' ' . $t->last_name;
        $html .= '<div class="sms-thread-item" data-phone="'.esc_attr($t->mobile_number).'" data-id="'.esc_attr($t->client_id).'" style="padding:15px; border-bottom:1px solid #eee; cursor:pointer;">';
        $html .= '<strong style="display:block; color:#2271b1;">'.esc_html($name).'</strong>';
        $html .= '<small style="color:#666; display:block; white-space:nowrap; overflow:hidden; text-overflow:ellipsis;">'.esc_html($t->content).'</small>';
        $html .= '</div>';
    }
    wp_send_json_success($html);
}

// 2. Fetch history using client_id instead of phone number
add_action('wp_ajax_cc_get_sms_history', 'cc_get_sms_history_callback');
function cc_get_sms_history_callback() {
    global $wpdb;
    $client_id = intval($_POST['client_id']);
    $comm_table = $wpdb->prefix . 'crm_communications';

    $messages = $wpdb->get_results($wpdb->prepare(
        "SELECT * FROM $comm_table WHERE client_id = %d AND comm_type = 'sms' ORDER BY created_at ASC",
        $client_id
    ));

    $html = '';
    foreach ($messages as $m) {
        $is_sent = ($m->direction === 'outbound');
        $bg = $is_sent ? '#2271b1; color:#fff; align-self:flex-end;' : '#fff; color:#333; align-self:flex-start;';
        $html .= '<div style="max-width:75%; padding:10px 15px; border-radius:10px; margin-bottom:5px; box-shadow:0 1px 2px rgba(0,0,0,0.1); '.$bg.'">';
        $html .= esc_html($m->content);
        $html .= '<div style="font-size:9px; opacity:0.7; margin-top:5px; text-align:right;">'.date('M j, g:i a', strtotime($m->created_at)).'</div>';
        $html .= '</div>';
    }
    wp_send_json_success($html);
}/* File not found */