<?php
use Smackcoders\FUPESM\FUPESM_Tables;
require_once FUPESMDIR . "Tables.php";

function fupesm_custom_metabox_editor($post_type)
{
    if ($post_type == 'fup_email_template') {
        add_meta_box(
            "custom_editor_meta",
            "Custom Editor",
            "fupesm_render_custom_editor",
            'fup_email_template',
            "normal",
            "high",
            null
        );
        wp_deregister_script('postbox');
    }
}
add_action("add_meta_boxes", "fupesm_custom_metabox_editor");
function fupesm_second_metabox()
{
    add_meta_box(
        "second_metabox_id",
        "Automate",
        "fupesm_auto_status_callback_second",
        'fup_email_template',
        "side",
        "high"
    );
}
add_action("add_meta_boxes", "fupesm_second_metabox");

function fupesm_custom_metabox()
{
    add_meta_box(
        "custom_metabox_id",
        "Custom Metabox",
        "fupesm_custom_metabox_callback",
        'fup_email_template',
        "side",
        "high"
    );
}

function fupesm_auto_status_callback_second($post)
{
    $status = esc_html(get_post_meta($post->ID, 'auto_status', true));

    echo '<div class="postbox-header">';
    echo '<h2>Active</h2>';
    echo '<label class="switch autostatusswitch">
            <input type="checkbox" id="secondMetaboxToggle" name="secondMetaboxToggle" onchange="toggleSecondMetabox()" ' . checked($status, 'on', false) . '>
            <span class="slider round"></span>
          </label>';
    echo '</div>';
}

function fupesm_custom_metabox_callback($post)
{
?>



    <!DOCTYPE html>
    <html lang="en">

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

    </head>

    <body>

        <?php $placeholders = [
            "{customer_name}",
            "{order_no}",
            "{order_date}",
            "{blog_name}",
            "{user_name}",
            "{user_email}",
            "{post_title}",
            "{permalink}",
            "{comment_author}",
            "{comment_author_IP}",
            "{comment_author_domain}",
            "{comment_author_url}",
            "{comment_author_email}",
            "{comment_content}",
            "{approve_url}",
            "{trash_url}",
            "{spam_url}",
            "{moderation_url}",
            "{comments_counts}",
            "{login_url}",
            "{password}",
            "{site_url}",
            "{admin_email}",
            "{IPaddress}",
            "{customer_note}",
            "{admin_name}",
            "{first_name}",
            "{resetpassword_url}",
            "{last_name}",
            "{billing_email}",
            "{billing_phone}",
            "{billing_city}",
            "{billing_country}",
            "{billing_state}",
            "{billing_address_one}",
            "{billing_address_two}",
            "{billing_postcode}",
            "{product}",
            "{quantity}",
            "{price}",
            "{subtotal}",
            "{total}",
        ]; ?>


        <details class="card" open>
            <summary class="card-header"> Placeholder </summary>
            <div class="card-body">

                <div class="search-section">
                    <input type="text" id="search-input" name="search_input" placeholder="Search for placeholders...">
                    <hr class="rounded" style="border-top: 0px solid #ffff;">
                    <div id="placeholders-container">
                    </div>
                </div>
            </div>
        </details>
    </body>

    </html>
<?php

}
add_action("add_meta_boxes", "fupesm_custom_metabox");
function fupesm_render_custom_editor($post)
{
    wp_nonce_field('custom_metabox_nonce_action', 'custom_metabox_nonce');
    //added by saran
    $selected_value = get_post_meta($post->ID, "event", true);
    $trigger = get_post_meta($post->ID, "trigger", true);
    $email = get_post_meta($post->ID, "email", true);
    $content = get_post_meta($post->ID, "content", true);
    $subject = get_post_meta($post->ID, "subject", true);

    if (empty($trigger)) {
        $trigger = '0-minutes';
    }
    $values = explode("-", $trigger);
    $number = $values[0];
    $select_opt = $values[1];
    $dropdown_options = [
        "New Order" => "new_order",
        "New User" => "new_user",
        "Processing Order" => "processing_order",
    ];
    $dropdown_options = [
        "New Order" => "new_order",
        "New User" => "new_user",
        "Processing Order" => "processing_order",
        "On-hold" => "on-hold",
        "Completed Order" => "completed_order",
        "Failed Order" => "failed_order",
        "Cancelled Order" => "cancelled_order",
        "Refunded Order" => "refunded_order",
        "Abandonment Order" => "abandonment_order",
        "CF Submission" => "contact_form",
        "WP Form Submission" => "wp_form_pro",
        "Gravity Form" => "gravity_form",
        "Ninja Form" => "ninja_form",
        "Formidable Form" => "formidable_form",
        // "Caldera Form" => "caldera_form",
    ];
    $trigger_options = [
        "minutes" => "minutes",
        "hours" => "hours",
        "days" => "days",
    ];
    $content = get_post_meta($post->ID, "content", true); ?>
    <!DOCTYPE html>
    <html>

    <head>
        <meta name="viewport" content="user-scalable=1.0,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0">
    </head>

    <body>
        <div id="sm-followup-email" class="contentt">
            <form action="" method="POST">
                <input name="art_id" type="hidden">
                <div class="event-trigger">
                    <div class="inline-form">
                        <label for="event_dropdown" class="eventlabel">Event:</label>
                        <select name="event_dropdown" id="event_dropdown" class="custom-dropdown">
                            <?php
                            foreach ($dropdown_options as $value => $label) {
                                echo '<option value="' .
                                    esc_attr($value) .
                                    '" ' .
                                    selected($selected_value, $value, false) .
                                    ">" .
                                    esc_html($label) .
                                    "</option>";
                            }
                            ?>
                        </select>

                    </div>
                    <div class="inline-form">
                        <label>Trigger:</label>
                        <input type="number" name="trigger_number" id="trigger_number" value="<?php echo esc_attr($number); ?>" min="1" readonly />
                        <select name="trigger_dropdown" id="trigger_dropdown">
                            <?php foreach ($trigger_options as $val => $lab) {
                                echo '<option value="' .
                                    esc_attr($val) .
                                    '" ' .
                                    selected($select_opt, $val, false) .
                                    ($val == 0 ? ' selected' : '') .
                                    ">" .
                                    esc_html($lab) .
                                    "</option>";
                            } ?>
                        </select>
                    </div>



                </div>
                <div class="inline-form">
                    <label for="title">Subject:</label>
                    <input id="title" class="custom-input" name="title" type="text" value="<?php echo esc_attr($subject); ?>">
                </div>

                <div id="visual-editor">
                    <!-- <textarea id="editor" name="editor-content"><?php //echo esc_html($content) 
                                                                        ?></textarea> -->
                    <?php
                    $args = array(
                        'textarea_name' => 'editor_content',
                        'textarea_rows' => 10,
                        'editor_class' => 'custom-editor-class',
                    );
                    wp_editor(wp_kses_post($content), 'editor_content_editor', $args);

                    ?>
                </div>
            </form>
        </div>
        <?php
        ?>
        <?php
        //add by saran
        global $wpdb;
        $post_id = isset($post->ID) ? (int) $post->ID : 0;
        $statuscheck = $wpdb->get_var($wpdb->prepare("SELECT post_status FROM {$wpdb->prefix}posts WHERE ID=%d", $post_id));
        if ($statuscheck == 'auto-draft') {
            $post_ids = '';
        } else {
            $post_ids = $post_id;
        }
        ?>

        <div id="test-email" class="inline-forms">
            <label class="testemail-labelxx">Test Email:</label>
            <input id="email" class="test-input" name="email" type="text" oninput="updateValue(this)" value="<?php echo esc_attr($email) ?>" placeholder="Enter valid email address to receive a test mail.">
            &nbsp; <button id="sendbutton" type="button" data-post-id="<?php echo esc_attr($post_ids); ?>" class="button button-primary button-large">Send</button>

        </div>

    </body>

    </html>
<?php
}

add_action("save_post", "fupesm_save_data");
function fupesm_save_data()
{
    if (!isset($_POST['custom_metabox_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['custom_metabox_nonce'])), 'custom_metabox_nonce_action')) {
        return;
    }
    $post_id = isset($_POST['ID']) ? sanitize_text_field(wp_unslash($_POST["ID"])) : '';
    $automation_status = isset($_POST['secondMetaboxToggle']) ? sanitize_text_field(wp_unslash($_POST['secondMetaboxToggle'])) : '';
    $event = isset($_POST["event_dropdown"]) ? sanitize_text_field(wp_unslash($_POST["event_dropdown"])) : '';
    $trigger =
        intval(isset($_POST["trigger_number"]) ? $_POST["trigger_number"] : '') .
        "-" .
        sanitize_text_field(wp_unslash(isset($_POST["trigger_dropdown"]) ? $_POST["trigger_dropdown"] : ''));
    $email = sanitize_text_field(isset($_POST["email"]) ? wp_unslash($_POST["email"]) : '');
    //added by saran
    $content = isset($_POST['editor_content']) ? wp_kses_post(wp_unslash($_POST['editor_content'])) : '';
    $subject = isset($_POST["title"]) ? sanitize_text_field(wp_unslash($_POST["title"])) : '';

    update_post_meta($post_id, "subject", $subject);
    update_post_meta($post_id, "auto_status", $automation_status);
    update_post_meta($post_id, "trigger", $trigger);
    update_post_meta($post_id, "event", $event);
    update_post_meta($post_id, "content", $content);
    update_post_meta($post_id, "email", $email);
    //}
}
function fupesm_get_selected_value()
{
    check_ajax_referer('smack-follow-up-email', 'securekey');
    $data_placehold = array();
    $result = array();
    global $wpdb;
    $selected_values = isset($_POST['selected_event']) ? sanitize_text_field(wp_unslash($_POST['selected_event'])) : '';
    switch ($selected_values) {
        case 'New Order':
            $data_placehold = array('{recorded_sales}', '{payment_method}', '{order_number}', '{transaction_id}', '{billing_first_name}', '{billing_last_name}', '{billing_company}', '{billing_address_1}', '{billing_address_2}', '{billing_city}', '{billing_postcode}', '{billing_state}', '{billing_country}', '{billing_phone}', '{billing_email}', '{shipping_first_name}', '{shipping_last_name}', '{shipping_company}', '{shipping_address_1}', '{shipping_address_2}', '{shipping_city}', '{shipping_postcode}', '{shipping_state}', '{shipping_country}', '{customer_name}', '{order_currency}', '{item_name}', '{item_type}', '{item_variation_id}', '{item_product_id}', '{order_date}', '{order_link}', '{customer_note}', '{order_total}', '{site_name}');
            break;
        case 'Processing Order':
            $data_placehold = array('{recorded_sales}', '{payment_method}', '{order_number}', '{transaction_id}', '{billing_first_name}', '{billing_last_name}', '{billing_company}', '{billing_address_1}', '{billing_address_2}', '{billing_city}', '{billing_postcode}', '{billing_state}', '{billing_country}', '{billing_phone}', '{billing_email}', '{shipping_first_name}', '{shipping_last_name}', '{shipping_company}', '{shipping_address_1}', '{shipping_address_2}', '{shipping_city}', '{shipping_postcode}', '{shipping_state}', '{shipping_country}', '{customer_name}', '{order_currency}', '{item_name}', '{item_type}', '{item_variation_id}', '{item_product_id}', '{order_date}', '{order_link}', '{customer_note}', '{order_total}', '{site_name}');
            break;
        case 'On-hold':
            $data_placehold = array('{recorded_sales}', '{payment_method}', '{order_number}', '{transaction_id}', '{billing_first_name}', '{billing_last_name}', '{billing_company}', '{billing_address_1}', '{billing_address_2}', '{billing_city}', '{billing_postcode}', '{billing_state}', '{billing_country}', '{billing_phone}', '{billing_email}', '{shipping_first_name}', '{shipping_last_name}', '{shipping_company}', '{shipping_address_1}', '{shipping_address_2}', '{shipping_city}', '{shipping_postcode}', '{shipping_state}', '{shipping_country}', '{customer_name}', '{order_currency}', '{item_name}', '{item_type}', '{item_variation_id}', '{item_product_id}', '{order_date}', '{order_link}', '{customer_note}', '{order_total}', '{site_name}');
            break;
        case 'Completed Order':
            $data_placehold = array('{recorded_sales}', '{payment_method}', '{order_number}', '{transaction_id}', '{billing_first_name}', '{billing_last_name}', '{billing_company}', '{billing_address_1}', '{billing_address_2}', '{billing_city}', '{billing_postcode}', '{billing_state}', '{billing_country}', '{billing_phone}', '{billing_email}', '{shipping_first_name}', '{shipping_last_name}', '{shipping_company}', '{shipping_address_1}', '{shipping_address_2}', '{shipping_city}', '{shipping_postcode}', '{shipping_state}', '{shipping_country}', '{customer_name}', '{order_currency}', '{item_name}', '{item_type}', '{item_variation_id}', '{item_product_id}', '{order_date}', '{order_link}', '{customer_note}', '{order_total}', '{site_name}');
            break;
        case 'Failed Order':
            $data_placehold = array('{recorded_sales}', '{payment_method}', '{order_number}', '{transaction_id}', '{billing_first_name}', '{billing_last_name}', '{billing_company}', '{billing_address_1}', '{billing_address_2}', '{billing_city}', '{billing_postcode}', '{billing_state}', '{billing_country}', '{billing_phone}', '{billing_email}', '{shipping_first_name}', '{shipping_last_name}', '{shipping_company}', '{shipping_address_1}', '{shipping_address_2}', '{shipping_city}', '{shipping_postcode}', '{shipping_state}', '{shipping_country}', '{customer_name}', '{order_currency}', '{item_name}', '{item_type}', '{item_variation_id}', '{item_product_id}', '{order_date}', '{order_link}', '{customer_note}', '{order_total}', '{site_name}');
            break;
        case 'Cancelled Order':
            $data_placehold = array('{recorded_sales}', '{payment_method}', '{order_number}', '{transaction_id}', '{billing_first_name}', '{billing_last_name}', '{billing_company}', '{billing_address_1}', '{billing_address_2}', '{billing_city}', '{billing_postcode}', '{billing_state}', '{billing_country}', '{billing_phone}', '{billing_email}', '{shipping_first_name}', '{shipping_last_name}', '{shipping_company}', '{shipping_address_1}', '{shipping_address_2}', '{shipping_city}', '{shipping_postcode}', '{shipping_state}', '{shipping_country}', '{customer_name}', '{order_currency}', '{item_name}', '{item_type}', '{item_variation_id}', '{item_product_id}', '{order_date}', '{order_link}', '{customer_note}', '{order_total}', '{site_name}');
            break;
        case 'Refunded Order':
            $data_placehold = array('{recorded_sales}', '{payment_method}', '{order_number}', '{transaction_id}', '{billing_first_name}', '{billing_last_name}', '{billing_company}', '{billing_address_1}', '{billing_address_2}', '{billing_city}', '{billing_postcode}', '{billing_state}', '{billing_country}', '{billing_phone}', '{billing_email}', '{shipping_first_name}', '{shipping_last_name}', '{shipping_company}', '{shipping_address_1}', '{shipping_address_2}', '{shipping_city}', '{shipping_postcode}', '{shipping_state}', '{shipping_country}', '{customer_name}', '{order_currency}', '{item_name}', '{item_type}', '{item_variation_id}', '{item_product_id}', '{order_date}', '{order_link}', '{customer_note}', '{order_total}', '{site_name}');
            break;
        case 'Abandonment Order':
            $data_placehold = array('{product_name}', '{total_price}', '{cart_id}', '{product_id}', '{customer_name}', '{quantity}', '{variation_id}');
            break;
        case 'New User':
            $data_placehold = array('{user_login}', '{first_name}', '{last_name}', '{nickname}', '{user_email}', '{user_url}', '{user_nicename}', '{user_registered}', '{display_name}', '{role}', '{language}', '{ID}');
            break;
        case 'Gravity Form':
            $gravity_form_table = $wpdb->prefix . 'gf_form_meta';
            $fields = $wpdb->get_results($wpdb->prepare("SELECT display_meta FROM $gravity_form_table"), ARRAY_A);
            foreach ($fields as $fields_val) {
                $gf_fields = json_decode($fields_val['display_meta']);
                $field_data = $gf_fields->fields;
                $field_list = array();
                foreach ($field_data as $fieldkey => $fieldval) {
                    $field_list[] = '{' . $fieldval->label . '}';
                }
                $data_placehold = $field_list;
            }
            break;
        case 'Formidable Form':
            $frm_fields_table = $wpdb->prefix . 'frm_fields';
            $field_lists = $wpdb->get_results($wpdb->prepare("SELECT name FROM $frm_fields_table"), ARRAY_A);
            foreach ($field_lists as $fieldkey => $fieldval) {
                $field_list[] = '{' . $fieldval['name'] . '}';
            }
            $data_placehold = $field_list;
            break;
        case 'WP Form Submission':
            $wpforms_fields_table = $wpdb->prefix . 'posts';
            $field_lists = $wpdb->get_results($wpdb->prepare("SELECT post_content FROM $wpforms_fields_table where post_type='wpforms'"), ARRAY_A);
            foreach ($field_lists as $field_key => $field_value) {
                $fields_data = json_decode($field_value['post_content']);
                $fieldslists = $fields_data->fields;
                foreach ($fieldslists as $fields_key => $fields_val) {
                    $field_list[] =  '{' . $fields_val->label . '}';
                }
            }
            $data_placehold = $field_list;
            break;
        case 'Ninja Form':
            $ninja_field_table = $wpdb->prefix . 'nf3_fields';
            $ninja_field_list = array();
            $ninja_fields = $wpdb->get_results($wpdb->prepare("SELECT id,`key`,label FROM $ninja_field_table"), ARRAY_A);
            foreach ($ninja_fields as $ninja_key => $ninja_val) {
                if ($ninja_val['label'] !== 'Submit') {
                    $field_list[] = '{' . $ninja_val['label'] . '}';
                }
            }
            $data_placehold = $field_list;
            break;
    }
    $result['data_placehold'] = $data_placehold;
    // $test = custom_metabox_callback('',$data_placehold);
    // echo json_encode($result);
    wp_send_json_success(['data_placehold' => $data_placehold]);
    // wp_die();
}
add_action('wp_ajax_fupesm_get_selected_value', 'fupesm_get_selected_value');

add_action('wp_ajax_fupesm_send_test_mail', 'fupesm_send_test_mail');

function fupesm_send_test_mail()
{
    check_ajax_referer('smack-follow-up-email', 'securekey');
    $email = isset($_POST['email']) ? sanitize_email(wp_unslash($_POST['email'])) : '';
    $template_id = isset($_POST['id']) ? intval($_POST['id']) : '';
    global $wpdb;
    $content = get_post_meta($template_id, "content");
    $message = wpautop($content[0]);
    $post_details = get_post($template_id);
    $subjects = get_post_meta($template_id, "subject");
    $subject = $subjects[0];
    $headers[] = "From: Wordpress<wordpress@mysite.com>";
    add_filter("wp_mail_content_type", function ($content_type) {
        return "text/html";
    });
    $event = get_post_meta($template_id,'event',true);
    switch($event){
        case 'New Order':
            global $wpdb;
            $order_status = 'wc-pending'; 
            $orders = wc_get_orders([
                'status' => $order_status,
                'limit'  => -1, // -1 for all orders
            ]);

            $order_ids = wp_list_pluck($orders, 'id');
            if(!empty($order_ids)){
                $order_id = end($order_ids);
                $tables =new FUPESM_Tables;
                $subject = $tables->fupesm_placeholder_function($subject,'',$order_id,'','',$event);
                $message = $tables->fupesm_placeholder_function($message,'',$order_id,'','',$event);
            }
            break;
        case 'Processing Order':
            global $wpdb;
            $order_status = 'wc-processing'; 
            $orders = wc_get_orders([
                'status' => $order_status,
                'limit'  => -1, // -1 for all orders
            ]);

            $order_ids = wp_list_pluck($orders, 'id');
            if(!empty($order_ids)){
                $order_id = end($order_ids);
                $tables =new FUPESM_Tables;
                $subject = $tables->fupesm_placeholder_function($subject,'',$order_id,'','',$event);
                $message = $tables->fupesm_placeholder_function($message,'',$order_id,'','',$event);
            }
        break;
        case 'On-hold':
            global $wpdb;
            $order_status = 'wc-on-hold'; 
            $orders = wc_get_orders([
                'status' => $order_status,
                'limit'  => -1, // -1 for all orders
            ]);

            $order_ids = wp_list_pluck($orders, 'id');
            if(!empty($order_ids)){
                $order_id = end($order_ids);
                $tables =new FUPESM_Tables;
                $subject = $tables->fupesm_placeholder_function($subject,'',$order_id,'','',$event);
                $message = $tables->fupesm_placeholder_function($message,'',$order_id,'','',$event);
            }
        break;
        case 'Completed Order':
            global $wpdb;
            $order_status = 'wc-completed'; 
            $orders = wc_get_orders([
                'status' => $order_status,
                'limit'  => -1, // -1 for all orders
            ]);

            $order_ids = wp_list_pluck($orders, 'id');
            if(!empty($order_ids)){
                $order_id = end($order_ids);
                $tables =new FUPESM_Tables;
                $subject = $tables->fupesm_placeholder_function($subject,'',$order_id,'','',$event);
                $message = $tables->fupesm_placeholder_function($message,'',$order_id,'','',$event);
            }
        break;
        case 'Failed Order':
            global $wpdb;
            $order_status = 'wc-failed'; 
            $orders = wc_get_orders([
                'status' => $order_status,
                'limit'  => -1, // -1 for all orders
            ]);

            $order_ids = wp_list_pluck($orders, 'id');
            if(!empty($order_ids)){
                $order_id = end($order_ids);
                $tables =new FUPESM_Tables;
                $subject = $tables->fupesm_placeholder_function($subject,'',$order_id,'','',$event);
                $message = $tables->fupesm_placeholder_function($message,'',$order_id,'','',$event);
            }
        break;
        case 'Cancelled Order':
            global $wpdb;
            $order_status = 'wc-cancelled'; 
            $orders = wc_get_orders([
                'status' => $order_status,
                'limit'  => -1, // -1 for all orders
            ]);

            $order_ids = wp_list_pluck($orders, 'id');
            if(!empty($order_ids)){
                $order_id = end($order_ids);
                $tables =new FUPESM_Tables;
                $subject = $tables->fupesm_placeholder_function($subject,'',$order_id,'','',$event);
                $message = $tables->fupesm_placeholder_function($message,'',$order_id,'','',$event);
            }
        break;
        case 'Refunded Order':
            global $wpdb;
            $order_status = 'wc-refunded'; 
            $orders = wc_get_orders([
                'status' => $order_status,
                'limit'  => -1, // -1 for all orders
            ]);

            $order_ids = wp_list_pluck($orders, 'id');
            if(!empty($order_ids)){
                $order_id = end($order_ids);
                $tables =new FUPESM_Tables;
                $subject = $tables->fupesm_placeholder_function($subject,'',$order_id,'','',$event);
                $message = $tables->fupesm_placeholder_function($message,'',$order_id,'','',$event);
            }
        break;
        case 'New User':
            global $wpdb;
            $user_id = get_current_user_id();
            if(!empty($user_id)){
                $tables =new FUPESM_Tables;
                $subject = $tables->fupesm_placeholder_function($subject,$user_id,'','','',$event);
                $message = $tables->fupesm_placeholder_function($message,$user_id,'','','',$event);    
            }
        break;
        case 'Gravity Form':
            global $wpdb;
            $gravity_form = $wpdb->get_results("SELECT form_id,entry_id FROM {$wpdb->prefix}gf_entry_meta",ARRAY_A);
            if(!empty($gravity_form)){
                $gravity_data = end($gravity_form);
                $form_id = $gravity_data['form_id'];
                $entry_id = $gravity_data['entry_id'];
                $tables =new FUPESM_Tables;
                $subject = $tables->fupesm_placeholder_function($subject,'','',$form_id,$entry_id,$event);
                $message = $tables->fupesm_placeholder_function($message,'','',$form_id,$entry_id,$event);
            }
        break;
        case 'Formidable Form':
            global $wpdb;
            $form_id = $wpdb->get_var("SELECT form_id FROM {$wpdb->prefix}frm_items");
            $entry_id = $wpdb->get_var("SELECT item_id FROM {$wpdb->prefix}frm_item_meta");
            if(!empty($form_id)){
                $tables =new FUPESM_Tables;
                $subject = $tables->fupesm_placeholder_function($subject,'','',$form_id,$entry_id,$event);
                $message = $tables->fupesm_placeholder_function($message,'','',$form_id,$entry_id,$event);  
            }
        break;
        case 'WP Form Submission':
            global $wpdb;
            $wpforms_data = $wpdb->get_results("SELECT form_id,entry_id FROM {$wpdb->prefix}wpforms_entries");
            if(!empty($wpforms_data)){
                $wpforms = end($gravity_form);
                $form_id = $wpforms['form_id'];
                $entry_id = $wpforms['entry_id'];   
                $tables =new FUPESM_Tables;
                $subject = $tables->fupesm_placeholder_function($subject,'','',$form_id,$entry_id,$event);
                $message = $tables->fupesm_placeholder_function($message,'','',$form_id,$entry_id,$event);  
            }
        break;
        case 'Ninja Form':
            global $wpdb;
            $form_id = $wpdb->get_var($wpdb->prepare("SELECT ID FROM {$wpdb->prefix}posts WHERE post_type=%s",'nf_sub'));
            $entry_id = $wpdb->get_var($wpdb->prepare("SELECT meta_value FROM {$wpdb->prefix}postmeta WHERE post_id=%d and meta_key=%s",$form_id,'_form_id'));
            if(!empty($form_id) && !empty($entry_id)){
                $tables =new FUPESM_Tables;
                $subject = $tables->fupesm_placeholder_function($subject,'','',$form_id,$entry_id,$event);
                $message = $tables->fupesm_placeholder_function($message,'','',$form_id,$entry_id,$event);   
            }
        break;
        case 'Abandonment Order':
            global $wpdb;
            $cart_detail = $wpdb->get_var("SELECT meta_value FROM {$wpdb->prefix}usermeta WHERE meta_key like '%_woocommerce_persistent_cart_%'");
            if(!empty($cart_detail)){
                $cart_data = unserialize($cart_detail);
                $cartdata = $cart_data['cart'];
                foreach($cartdata as $cart_key => $cart_val){
                    $cart_id = $cart_val['key'];
                    $product_id = $cart_val['product_id'];
                    $user_id = get_current_user_id();
                    $tables =new FUPESM_Tables;
                    $subject = $tables->fupesm_placeholder_function($subject,$cart_id,$product_id,$user_id,'',$event);
                    $message = $tables->fupesm_placeholder_function($message,$cart_id,$product_id,$user_id,'',$event);            
                }
            }
        break;
    }
    $date = new \DateTime('now');
    $current_time=$date->format('Y-m-d H:i:s');
    $mail_log_table = $wpdb->prefix . "smack_email_log";
    if (!empty($email)) {
        $mail_id = explode(",", $email);
        foreach ($mail_id as $mailval) {
            $value = wp_mail($mailval, $subject, $message, $headers);
            if ($value == 1) {
                $wpdb->insert($mail_log_table, [
                    "event" => 'Test Mail',
                    "user_email" => $mailval,
                    "date" => $current_time,
                    "status" => "Success",
                ]);
                $status = 1;
            } else {
                $wpdb->insert($mail_log_table, [
                    "event" => 'Test Mail',
                    "user_email" => $mailval,
                    "date" => $current_time,
                    "status" => "Failed",
                ]);
                $status = 0;
            }
        }
        if ($status == 1) {
            wp_send_json_success(['message' => "Your test email was sent successfully."]);
        } else {

            $result = array();
            $result['message'] = 'Failed';
            wp_send_json(array('success' => false, 'data' => $result));
        }
    }
}

function  fupesm_post_autostatus()
{
    check_ajax_referer('smack-follow-up-email', 'securekey');
    $id = isset($_POST['post_id']) ? sanitize_text_field(wp_unslash($_POST['post_id'])) : '';
    $status = isset($_POST['status']) ? sanitize_text_field(wp_unslash($_POST['status'])) : '';
    update_post_meta($id, 'auto_status', $status);
}
add_action('wp_ajax_fupesm_post_autostatus', 'fupesm_post_autostatus');
