<?php
if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

function click_n_chat_update_lead_action_handler() {  

	if (!isset($_POST['security']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['security'])), 'ajax-call-nounce')) {
        wp_send_json_error('invalid nonce');
        wp_die();
    }

	global $wpdb;
	 
	$name = sanitize_textarea_field($_POST['name']);
	$phone = sanitize_textarea_field($_POST['phone']);
	$email = sanitize_textarea_field($_POST['email']);
	
	$click_n_chat_setting_popup = get_option('click_n_chat_setting_popup');
	
	$lid = "";
	if($click_n_chat_setting_popup->chat_logs == "1")
	{
		$table_name = $wpdb->prefix . 'cnc_leads';
		$wpdb->insert(
			$table_name,
			[
				'name' => $name,
				'phone' => $phone,
				'email' => $email
			]
		);
		$lid = $wpdb->insert_id;
	} 	
	$click_n_chat_greetings_message = get_option('click_n_chat_greetings_message');
	wp_send_json([
        'reply' => html_entity_decode($click_n_chat_greetings_message),
		'lid' => $lid
    ]);
}  
add_action('wp_ajax_click_n_chat_update_lead_action', 'click_n_chat_update_lead_action_handler');  
add_action('wp_ajax_nopriv_click_n_chat_update_lead_action', 'click_n_chat_update_lead_action_handler'); // For non-logged in users  
