<?php
if (! defined('ABSPATH') ) { exit; // Exit if accessed directly
}
// // Register the script first.
function my_enqueue()
{
    $translation_array = array( 'rt_adminurl' => admin_url(), 'rt_url' => get_site_url(), 'rt_urlajax' =>  (get_site_url() . '/wp-admin/admin-ajax.php') , 'a_value' => '10' );
     // wp_enqueue_script( 'ajax-script', SCC_URL . 'assets/js/scc_scripts.php', array('jquery') );
    wp_localize_script('jquery', 'rt_vars', $translation_array);
}
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
add_action('admin_enqueue_scripts', 'my_enqueue');

// // // The script can be enqueued now or later.
// wp_enqueue_script( 'rt_handle' );
add_action('wp_ajax_sccSaveField', 'scc_saveField');
add_action('wp_ajax_sccSaveSettings', 'scc_saveSettings');
add_action('wp_ajax_sscSaveCoupon', 'sscSaveCoupon');
add_action('wp_ajax_sccDeleteCoupon', 'sccDeleteCoupon');
add_action('wp_ajax_nopriv_sscCheckCoupon', 'sscCheckCoupon');
add_action('wp_ajax_sscCheckCoupon', 'sscCheckCoupon');
add_action('wp_ajax_sccSaveEmailSettings', 'scc_saveEmailSettings');
add_action('wp_ajax_sccSaveDel', 'scc_DelForm');
add_action('wp_ajax_loadExample', 'scc_LoadExample');
add_action('wp_ajax_sccSendEmail', 'scc_SendEmail');
add_action('wp_ajax_sccSavePDF', 'scc_SavePDF');
add_action('wp_ajax_sccSendPDF', 'scc_SendPDF');
add_action('wp_ajax_sccAddWooCommerce', 'scc_AddWooCommerce');

add_action('wp_ajax_nopriv_sccSendEmail', 'scc_SendEmail');
add_action('wp_ajax_nopriv_sccSavePDF', 'scc_SavePDF');
add_action('wp_ajax_sccChangeDatabaseToUtf8', 'scc_ChangeDatabaseToUtf8');
add_action('wp_ajax_nopriv_sccChangeDatabaseToUtf8', 'scc_ChangeDatabaseToUtf8');
add_action('wp_ajax_sccDownloadBackup', 'sccDownloadBackup');
add_action('wp_ajax_sscUploadSccBackup', 'sscUploadSccBackup');
add_action('wp_ajax_sccPDFFont', 'sccPDFFont');
add_action('wp_ajax_sccPDFSettings', 'sccPDFSettings');
add_action('wp_ajax_pdf_php', 'generatePdfFileAndGetPath');
add_action('wp_ajax_preGeneratedQuoteDownload', 'preGeneratedQuoteDownload');

add_action('wp_ajax_nopriv_sccAddWooCommerce', 'scc_AddWooCommerce');
add_action('wp_ajax_nopriv_sccSendPDF', 'scc_SendPDF');

add_action('wp_ajax_sccSaveRecaptchaKeys', 'sccSaveRecaptchaKeys');
add_action('wp_ajax_scc_feedback_manage', 'sccFeedbackManage');
add_action('wp_ajax_scc_set_stripe_key', 'sccSetStripeKey');
add_action('wp_ajax_duplicationOfCalculator', 'sccCalculatorDuplication', 1);
add_action('wp_ajax_sccQuoteSubmission', 'processSCCQuoteSubmission');
add_action('wp_ajax_nopriv_sccQuoteSubmission', 'processSCCQuoteSubmission');
add_action('wp_ajax_scc_handle_dropdown_logo', 'sccManageDropdownLogo');

add_action('wp_ajax_scc_delete_all', 'sccDeleteAll');

add_action('wp_ajax_scc_do_webhooks', 'sccDoWebhook');
add_action('wp_ajax_nopriv_scc_do_webhooks', 'sccDoWebhook');


function sccPDFSettings() {
    $pdf_font =  sanitize_text_field(stripslashes($_POST['pdfSettings']['sccPDFFont']));
    $pdf_datefmt =  sanitize_text_field(stripslashes($_POST['pdfSettings']['sccPDFDateFmt']));
    // echo $pdf_font;
    update_option('sccPDFFont',$pdf_font);
    update_option('scc_pdf_datefmt',$pdf_datefmt);
}

function sscUploadSccBackup()
{

    $json_data = json_decode(file_get_contents($_FILES["file"]["tmp_name"]), true);

    if(gettype($json_data) != null) {
        global $wpdb;

        $formName =  $wpdb->esc_like(str_replace("|percent|", "%", htmlspecialchars($json_data['scc_form']['formname'] . ' restored')), ENT_NOQUOTES);
        $formName = trim($formName, '"');

        $formStored = $wpdb->esc_like((str_replace("|percent|", "%", json_encode($json_data['scc_form']['formstored'], JSON_UNESCAPED_UNICODE))));
      
        $formTranslate = $wpdb->esc_like((str_replace("|percent|", "%", json_encode($json_data['scc_form']['formtranslate'], JSON_UNESCAPED_UNICODE))));

        $form_parameters = $wpdb->esc_like((str_replace("|percent|", "%", json_encode($json_data['scc_form_parameters']['parameters'], JSON_UNESCAPED_UNICODE))));


        $query = $wpdb->prepare("INSERT INTO {$wpdb->prefix}scc_forms (id,formname,description,ajaxform,formstored, formtranslate) VALUES (NULL, %s, '', '', %s, %s);", $formName, $formStored, $formTranslate);
        $wpdb->query($query);
        $id = $wpdb->insert_id;
        $query = $wpdb->prepare("INSERT INTO `{$wpdb->prefix}scc_form_parameters` (id,form_id,parameters) VALUES (NULL, %d, %s);", $id, $form_parameters);
        $wpdb->query($query);

    }


}

function sccDownloadBackup()
{
    global $wpdb;

    if(isset($_POST['id']) && is_numeric($_POST['id']) && $_POST['id'] > 0) {
        $id_ = filter_input(INPUT_POST, 'id');
        $scc_form = $wpdb->get_results($wpdb->prepare("SELECT id, formname,description,formstored,formtranslate  FROM {$wpdb->prefix}scc_forms where id = %d", array($id_)));
        $scc_form_parameters = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}scc_form_parameters where form_id = %d ", array($id_)));

        $data_response = [];
        $scc_form[0]->formstored = (array) json_decode(stripslashes(stripslashes($scc_form[0]->formstored)));
        $scc_form[0]->formtranslate = (array) json_decode(stripslashes(stripslashes($scc_form[0]->formtranslate)));
        $scc_calc_params = (array) json_decode(stripslashes(stripslashes($scc_form_parameters[0]->parameters)));
        // if parameters return null, try less stripslashing
        if (empty($scc_calc_params)) {
            $scc_calc_params = (array) json_decode(stripslashes($scc_form_parameters[0]->parameters));
        }
        $scc_form_parameters[0]->parameters = $scc_calc_params;

        $data_response['scc_form'] = $scc_form[0];
        $data_response['scc_form_parameters'] = $scc_form_parameters[0];

        // echo json_encode($data_response, JSON_UNESCAPED_UNICODE);
        wp_send_json((array) $data_response);

    }else{
        echo 'error';
    }
}

function scc_ChangeDatabaseToUtf8()
{

      global $wpdb;

      $collation1 = $wpdb->get_results("SELECT TABLE_SCHEMA , TABLE_NAME , TABLE_COLLATION FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME ='{$wpdb->prefix}scc_forms';");

      $table1Ok = false;

    foreach($collation1[0] as $key=>$value){
        if($value == 'utf8mb4_unicode_ci') {
            $table1Ok = true;
        }
    }
      $collation2 = $wpdb->get_results("SELECT TABLE_SCHEMA , TABLE_NAME , TABLE_COLLATION FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME ='{$wpdb->prefix}scc_form_parameters';");

      $table2Ok = false;

    foreach($collation2[0] as $key=>$value){
        if($value == 'utf8mb4_unicode_ci') {
            $table2Ok = true;
        }
    }
    if($table1Ok == false || $table2Ok == false) {

        $wpdb->query("ALTER TABLE {$wpdb->prefix}scc_forms CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;");
        // $wpdb->query($query);
        if($wpdb->last_error !== '') :
            echo $wpdb->print_error();
            $wpdb->print_error();
        endif;
        $wpdb->query("ALTER TABLE {$wpdb->prefix}scc_form_parameters CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;");
        //  $wpdb->query($query);
        if($wpdb->last_error !== '') :
          
            echo $wpdb->print_error();
        endif;
    }
}

function scc_DelForm()
{
    global $wpdb;
    if (!isset($_POST['id'])) { echo "ERROR - value does not exist"; return; 
    }
    $id = (int)$_POST['id'];
    if ($id == 0) { echo "ERROR - value is 0"; return; 
    }
    $query = $wpdb->prepare("DELETE FROM {$wpdb->prefix}scc_forms WHERE id = %d LIMIT 1", $id);
    $wpdb->query($query);

}
function scc_LoadExample()
{
    global $wpdb;
    $data_example = $_POST['data_example'];
    if ($data_example == 0) {
        $query = "INSERT INTO {$wpdb->prefix}scc_forms (id,formname,description,ajaxform,formstored) VALUES (NULL, 'Venue Rental Template', '', '','[{\"name\":\"Venue Rental\", \"desc\":\" Are you looking to book a venue for a corporate event, wedding, or birthday party? Please use our form below to get an accurate and instant quote.\", \"section\":\"0\", \"value\":[ { \"subsection\":\"0\", \"Nooptions\":[ { \"element\":\"0\", \"type\":\"selectoption\", \"value\":[ { \"No\":\"0\", \"title\":\"Please choose a room\", \"name\":\"The Minor Hall\", \"value1\":\"1500\", \"value2\":\"This rooms holds up to 100 guests and it\'s great for smaller events or birthday parties.\", \"mandatory\":\"yes\" }, { \"No\":1, \"title\":\"Please choose a room\", \"name\":\"The Grand Plaza\", \"value1\":\"2500\", \"value2\":\"This contemporary style room holds up to 300 guests. Includes a video projector screen.\", \"mandatory\":\"yes\" } ], \"length\":2 } ], \"minmax\":[ ], \"step\":0, \"defaultValue\":0 }, { \"subsection\":1, \"Nooptions\":[ ], \"minmax\":[ { \"No\":0, \"title\":\"How many hours?\", \"name\":\"1\", \"value1\":\"8\", \"value2\":\"100\" } ], \"step\":\"1\", \"defaultValue\":\"1\" } ] }, { \"name\":\"Additional Services\", \"desc\":\" Please choose any additional products or services you may need.\", \"section\":1, \"value\":[ { \"subsection\":0, \"Nooptions\":[ { \"element\":0, \"type\":\"switchoption\", \"value\":[ { \"No\":0, \"title\":0, \"name\":\"Wireless microphone\", \"value1\":\"110\", \"value2\":\"6\" }, { \"No\":1, \"title\":0, \"name\":\"Video projector\", \"value1\":\"300\", \"value2\":\"6\" } ], \"length\":2 } ], \"minmax\":[ ], \"step\":0, \"defaultValue\":0 }, { \"subsection\":1, \"Nooptions\":[ { \"element\":0, \"type\":\"comment_option\", \"value\":[ { \"No\":0, \"title\":\"Additional comments?\", \"value1\":\"3\", \"value2\":\"\", \"mandatory\":\"no\" } ], \"length\":1 } ], \"minmax\":[ ], \"step\":0, \"defaultValue\":0 }]}]');";
        $wpdb->query($query);
        $id = $wpdb->insert_id;
        $query = "INSERT INTO `{$wpdb->prefix}scc_form_parameters` (id,form_id,parameters) VALUES (NULL,'.$id.','{   \"fontType\":\"432\", \"colorPicker\":\"#000\", \"servicepricefontsize\":\"16px\", \"objectColorPicker\":\"#000\", \"objectServicepricefontsize\":\"50px\", \"titleFontType\":\"432\", \"titleColorPicker\":\"#000\", \"titleServicepricefontsize\":\"30px\", \"objectsendquote\":\"\", \"objectdetailedlist\":\"\", \"objectsaveicon\":\"\", \"objectscctax\":\"\", \"objectscccoupon\":\"\", \"objecttaxrate\":\"\", \"objectscccurrencylabel\":\"\", \"objectscctitlelabel\":\"\", \"objectscctotalprice\":\"\", \"objecttotalpricestyle\":\"Style for Total Price Bar\", \"objecttotalword\":\"\", \"objectdetailedlistword\":\"\", \"objectsendquoteword\":\"\", \"currency_style\":\"0\", \"paypal_checked\":\"false\", \"paypal_email\":\"\", \"paypal_shopping_cart_name\":\"\", \"paypal_currency\":\"\" }');";
        $wpdb->query($query);
    }elseif ($data_example == 1) {
        $query = "INSERT INTO {$wpdb->prefix}scc_forms (id,formname,description,ajaxform,formstored) VALUES (NULL, 'Website Designer Template', '', '', '[{\"name\":\"Essentials\",\"desc\":\" Please fill out the essentials below.\",\"section\":0,\"value\":[{\"subsection\":0,\"Nooptions\":[{\"element\":0,\"type\":\"selectoption\",\"value\":[{\"No\":0,\"title\":\"Website platform\",\"name\":\"WordPress\",\"value1\":\"1000\",\"value2\":\" Base fee for a WordPress website starts at $1,000\"},{\"No\":1,\"title\":\"Website platform\",\"name\":\"Shopify\",\"value1\":\"800\",\"value2\":\"  Base fee for a WordPress website starts at $800\"},{\"No\":2,\"title\":\"Website platform\",\"name\":\"HTML\",\"value1\":\"2000\",\"value2\":\"   Base fee for a WordPress website starts at $2,000\"}],\"length\":3}],\"minmax\":[],\"step\":0,\"defaultValue\":0},{\"subsection\":1,\"Nooptions\":[],\"minmax\":[{\"No\":0,\"title\":\"How many pages\",\"name\":\"0\",\"value1\":\"15\",\"value2\":\"100\"}],\"step\":\"1\",\"defaultValue\":\"5\"}]},{\"name\":\"Additional Features\",\"desc\":\" \",\"section\":1,\"value\":[{\"subsection\":0,\"Nooptions\":[{\"element\":0,\"type\":\"switchoption\",\"value\":[{\"No\":0,\"title\":0,\"name\":\"Contact Form\",\"value1\":\"100\",\"value2\":\"1\"},{\"No\":1,\"title\":0,\"name\":\"Sliders/Banners\",\"value1\":\"100\",\"value2\":\"1\"},{\"No\":2,\"title\":0,\"name\":\"Scheduling/Booking System\",\"value1\":\"100\",\"value2\":\"1\"},{\"No\":3,\"title\":0,\"name\":\"Mailing List\",\"value1\":\"100\",\"value2\":\"1\"},{\"No\":4,\"title\":0,\"name\":\"Mobile Responsive\",\"value1\":\"100\",\"value2\":\"1\"},{\"No\":5,\"title\":0,\"name\":\"Shopping Cart/E-Commerce\",\"value1\":\"100\",\"value2\":\"1\"},{\"No\":6,\"title\":0,\"name\":\"Social Media Feeds\",\"value1\":\"100\",\"value2\":\"1\"}],\"length\":7}],\"minmax\":[],\"step\":0,\"defaultValue\":0}]},{\"name\":\"Addition work\",\"desc\":\" \",\"section\":2,\"value\":[{\"subsection\":0,\"Nooptions\":[{\"element\":0,\"type\":\"switchoption\",\"value\":[{\"No\":0,\"title\":0,\"name\":\"Logo Design\",\"value1\":\"400\",\"value2\":\"2\"},{\"No\":1,\"title\":0,\"name\":\"Business Card Design\",\"value1\":\"200\",\"value2\":\"2\"}],\"length\":2}],\"minmax\":[],\"step\":0,\"defaultValue\":0},{\"subsection\":1,\"Nooptions\":[],\"minmax\":[{\"No\":0,\"title\":\"SEO (How many Keywords?)\",\"name\":\"0\",\"value1\":\"5\",\"value2\":\"100\"}],\"step\":\"1\",\"defaultValue\":\"0\"}]}]');";
        $wpdb->query($query);
        $id = $wpdb->insert_id;
        $query = "INSERT INTO `{$wpdb->prefix}scc_form_parameters` (id,form_id,parameters) VALUES (NULL,'.$id.','{\"fontType\":\"432\",\"colorPicker\":\"#000\",\"servicepricefontsize\":\"16px\",\"objectColorPicker\":\"#2374dd\",\"objectServicepricefontsize\":\"50px\",\"titleFontType\":\"98\",\"titleColorPicker\":\"#2374dd\",\"titleServicepricefontsize\":\"30px\"}');";
        $wpdb->query($query);
    }
    elseif ($data_example == 2) {
        $query = "INSERT INTO {$wpdb->prefix}scc_forms (id,formname,description,ajaxform,formstored) VALUES (NULL, 'Wedding Photographer Template', '', '', '[{\"name\":\"Base package\",\"desc\":\" Below is a list of collections that you can choose a base. You may add any a-la-carte features later.\",\"section\":0,\"value\":[{\"subsection\":0,\"Nooptions\":[{\"element\":0,\"type\":\"selectoption\",\"value\":[{\"No\":0,\"title\":\"Choose a base package\",\"name\":\"Hearty\",\"value1\":\"4800\",\"value2\":\"  All Day Coverage + Online Gallery + Timeline Assistance\"},{\"No\":1,\"title\":\"Choose a base package\",\"name\":\"Keepsake\",\"value1\":\"3800\",\"value2\":\" 8 Hours Coverage + Online Gallery + Timeline Assistance\"}],\"length\":2}],\"minmax\":[],\"step\":0,\"defaultValue\":0}]},{\"name\":\"A-La-Carte Options\",\"desc\":\" Please add on any additions features you may want \",\"section\":1,\"value\":[{\"subsection\":0,\"Nooptions\":[{\"element\":0,\"type\":\"switchoption\",\"value\":[{\"No\":0,\"title\":0,\"name\":\"Engagement Session\",\"value1\":\"600\",\"value2\":\"4\"},{\"No\":1,\"title\":0,\"name\":\"Engagement Photo Guestbook\",\"value1\":\"350\",\"value2\":\"4\"}],\"length\":2}],\"minmax\":[],\"step\":0,\"defaultValue\":0}]},{\"name\":\"Extra hours\",\"desc\":\" Do you need any additional hours?\",\"section\":2,\"value\":[{\"subsection\":0,\"Nooptions\":[],\"minmax\":[{\"No\":0,\"title\":\"Amount of hours\",\"name\":\"0\",\"value1\":\"10\",\"value2\":\"100\"}],\"step\":\"1\",\"defaultValue\":\"0\"}]}]');";
        $wpdb->query($query);
        $id = $wpdb->insert_id;
        $query = "INSERT INTO `{$wpdb->prefix}scc_form_parameters` (id,form_id,parameters) VALUES (NULL,'.$id.','{\"fontType\":\"0\",\"colorPicker\":\"#ed7498\",\"servicepricefontsize\":\"16px\",\"objectColorPicker\":\"#ed094d\",\"objectServicepricefontsize\":\"50px\",\"titleFontType\":\"159\",\"titleColorPicker\":\"#ed094d\",\"titleServicepricefontsize\":\"38px\"}');";
        $wpdb->query($query);
    }
    elseif ($data_example == 3) {
        $query = "INSERT INTO {$wpdb->prefix}scc_forms (id,formname,description,ajaxform,formstored) VALUES (NULL, 'Car Rental Template', '', '', '[{\"name\":\"Vehicle type\",\"desc\":\"Please select your vehicle type. \",\"section\":0,\"value\":[{\"subsection\":0,\"Nooptions\":[{\"element\":0,\"type\":\"selectoption\",\"value\":[{\"No\":0,\"title\":\"Vehicle\",\"name\":\"Hyundai i10\",\"value1\":\"27\",\"value2\":\" \"},{\"No\":1,\"title\":\"Vehicle\",\"name\":\"Hyundai Accent\",\"value1\":\"29\",\"value2\":\" Compact car\"},{\"No\":2,\"title\":\"Vehicle\",\"name\":\"Hyundai Azera \",\"value1\":\"36\",\"value2\":\" \"}],\"length\":3},{\"element\":1,\"type\":\"selectoption\",\"value\":[{\"No\":0,\"title\":\"Insurance level\",\"name\":\"PDW (Partial Damage Waiver)\",\"value1\":\"2\",\"value2\":\" $2 per day\"},{\"No\":1,\"title\":\"Insurance level\",\"name\":\"LDW (Loss Damage Waiver)\",\"value1\":\"3\",\"value2\":\"  $3 per day\"}],\"length\":2}],\"minmax\":[{\"No\":0,\"title\":\"Days rented\",\"name\":\"0\",\"value1\":\"30\",\"value2\":\"0\"}],\"step\":\"1\",\"defaultValue\":\"1\"}]},{\"name\":\"Extras\",\"desc\":\" You must select at least one option\",\"section\":1,\"value\":[{\"subsection\":0,\"Nooptions\":[{\"element\":0,\"type\":\"switchoption\",\"value\":[{\"No\":0,\"title\":0,\"name\":\"Baby seat\",\"value1\":\"20\",\"value2\":\"3\"},{\"No\":1,\"title\":0,\"name\":\"Extra driver\",\"value1\":\"15\",\"value2\":\"3\"}],\"length\":2}],\"minmax\":[],\"step\":0,\"defaultValue\":0}]}]');";
        $wpdb->query($query);
        $id = $wpdb->insert_id;
        $query = "INSERT INTO `{$wpdb->prefix}scc_form_parameters` (id,form_id,parameters) VALUES (NULL,'.$id.','{\"fontType\":\"0\",\"colorPicker\":\"#000\",\"servicepricefontsize\":\"16px\",\"objectColorPicker\":\"#000\",\"objectServicepricefontsize\":\"50px\",\"titleFontType\":\"0\",\"titleColorPicker\":\"#000\",\"titleServicepricefontsize\":\"30px\"}');";
        $wpdb->query($query);
    }
    elseif ($data_example == 4) {
        $query = "INSERT INTO `{$wpdb->prefix}scc_forms` (id,formname,description,ajaxform,formstored) VALUES (NULL, 'T-shirt Printing Template', '', '', '[{\"name\":\"Custom T-Shirt Printing\",\"desc\":\"Please fill out the form below to get an accurate price for custom screen printing. \",\"section\":0,\"value\":[{\"subsection\":0,\"Nooptions\":[{\"element\":0,\"type\":\"selectoption\",\"value\":[{\"No\":0,\"title\":\"Shirt type\",\"name\":\"Tee\",\"value1\":\"0\",\"value2\":\"No extra cost for tees \"},{\"No\":1,\"title\":\"Shirt type\",\"name\":\"Soft tee\",\"value1\":\"1\",\"value2\":\"An extra dollar per shirt for soft tees \"},{\"No\":2,\"title\":\"Shirt type\",\"name\":\"Racerback\",\"value1\":\"1\",\"value2\":\" An extra dollar per shirt for racerbacks\"}],\"length\":3},{\"element\":1,\"type\":\"selectoption\",\"value\":[{\"No\":0,\"title\":\"Logo location\",\"name\":\"1 Logo on White Material\",\"value1\":\"0\",\"value2\":\"Included in price \"}],\"length\":1}],\"minmax\":[{\"No\":0,\"title\":\"Shirt quantity\",\"name\":\"0\",\"value1\":\"1\",\"value2\":\"28\"},{\"No\":1,\"title\":\"Shirt quantity\",\"name\":\"2\",\"value1\":\"3\",\"value2\":\"25\"},{\"No\":2,\"title\":\"Shirt quantity\",\"name\":\"4\",\"value1\":\"5\",\"value2\":\"21\"},{\"No\":3,\"title\":\"Shirt quantity\",\"name\":\"6\",\"value1\":\"7\",\"value2\":\"19\"}],\"step\":\"1\",\"defaultValue\":\"1\"}]},{\"name\":\"Graphic Design\",\"desc\":\" Do you need any graphics created for this shirt printing project?\",\"section\":1,\"value\":[{\"subsection\":0,\"Nooptions\":[{\"element\":0,\"type\":\"switchoption\",\"value\":[{\"No\":0,\"title\":0,\"name\":\"Front only design\",\"value1\":\"100\",\"value2\":\"1\"},{\"No\":1,\"title\":0,\"name\":\"Front and back design\",\"value1\":\"175\",\"value2\":\"1\"}],\"length\":2}],\"minmax\":[],\"step\":0,\"defaultValue\":0}]}]');";
        $wpdb->query($query);
        $id = $wpdb->insert_id;
        $query = "INSERT INTO `{$wpdb->prefix}scc_form_parameters` (id,form_id,parameters) VALUES (NULL,'.$id.','{\"fontType\":\"447\",\"colorPicker\":\"#565656\",\"servicepricefontsize\":\"16px\",\"objectColorPicker\":\"#3695c4\",\"objectServicepricefontsize\":\"50px\",\"titleFontType\":\"390\",\"titleColorPicker\":\"#3695c4\",\"titleServicepricefontsize\":\"30px\"}');";
        $wpdb->query($query);
    }
    elseif ($data_example == 5) {
        $json_data = json_decode(file_get_contents(dirname(__FILE__) . '/assets/templates/5.json'), true);

        if(gettype($json_data) != NULL){
          global $wpdb;

          $formName =  $wpdb->esc_like(str_replace("|percent|", "%",htmlspecialchars($json_data['scc_form']['formname'] . ' restored')), ENT_NOQUOTES);
          $formName = trim($formName, '"');

          $formStored = $wpdb->esc_like((str_replace("|percent|", "%",json_encode($json_data['scc_form']['formstored'], JSON_UNESCAPED_UNICODE))));
          
          $formTranslate = $wpdb->esc_like((str_replace("|percent|", "%",json_encode($json_data['scc_form']['formtranslate'], JSON_UNESCAPED_UNICODE))));

          $form_parameters = $wpdb->esc_like((str_replace("|percent|", "%",json_encode($json_data['scc_form_parameters']['parameters'], JSON_UNESCAPED_UNICODE))));


          $query = $wpdb->prepare("INSERT INTO {$wpdb->prefix}scc_forms (id,formname,description,ajaxform,formstored, formtranslate) VALUES (NULL, %s, '', '', %s, %s);", $formName, $formStored, $formTranslate);
          $wpdb->query($query);
          $id = $wpdb->insert_id;
          $query = $wpdb->prepare("INSERT INTO `{$wpdb->prefix}scc_form_parameters` (id,form_id,parameters) VALUES (NULL, %d, %s);", $id, $form_parameters);
          $wpdb->query($query);

        }
        /*
        $query = "INSERT INTO `{$wpdb->prefix}scc_forms` (id,formname,description,ajaxform,formstored) VALUES (NULL, 'Cleaning Company Template', '','', '[{\"name\":\"Cleaning\",\"desc\":\" \",\"section\":0,\"value\":[{\"subsection\":0,\"Nooptions\":[],\"minmax\":[{\"No\":0,\"title\":\"Total area to be cleaned in square feet:\",\"name\":\"1\",\"value1\":\"2000\",\"value2\":\"1\"}],\"step\":\"1200\",\"defaultValue\":\"1200\"},{\"subsection\":1,\"Nooptions\":[],\"minmax\":[{\"No\":0,\"title\":\"Number of bedrooms:\",\"name\":\"0\",\"value1\":\"8\",\"value2\":\"1\"}],\"step\":\"4\",\"defaultValue\":\"4\"},{\"subsection\":2,\"Nooptions\":[],\"minmax\":[{\"No\":0,\"title\":\"Number of bathrooms:\",\"name\":\"0\",\"value1\":\"5\",\"value2\":\"1\"}],\"step\":\"2\",\"defaultValue\":\"2\"},{\"subsection\":3,\"Nooptions\":[],\"minmax\":[{\"No\":0,\"title\":\"Number of living rooms:\",\"name\":\"0\",\"value1\":\"3\",\"value2\":\"100\"}],\"step\":\"1\",\"defaultValue\":\"100\"},{\"subsection\":4,\"Nooptions\":[{\"element\":0,\"type\":\"selectoption\",\"value\":[{\"No\":0,\"title\":\"Size of your kitchen:\",\"name\":\"Small (0 - 150 ft2)\",\"value1\":\"1\",\"value2\":\"\",\"mandatory\":\"no\"},{\"No\":1,\"title\":\"Size of your kitchen:\",\"name\":\"Medium (151 - 250 ft2)\",\"value1\":\"1\",\"value2\":\"\",\"mandatory\":\"no\"},{\"No\":2,\"title\":\"Size of your kitchen:\",\"name\":\"Large (>250 ft2)\",\"value1\":\"1\",\"value2\":\"\",\"mandatory\":\"no\"}],\"length\":3}],\"minmax\":[],\"step\":0,\"defaultValue\":0},{\"subsection\":5,\"Nooptions\":[{\"element\":0,\"type\":\"selectoption\",\"value\":[{\"No\":0,\"title\":\"Master bathroom includes:\",\"name\":\"Shower only\",\"value1\":\"1\",\"value2\":\"\",\"mandatory\":\"no\"},{\"No\":1,\"title\":\"Master bathroom includes:\",\"name\":\"Tub only\",\"value1\":\"1\",\"value2\":\"\",\"mandatory\":\"no\"},{\"No\":2,\"title\":\"Master bathroom includes:\",\"name\":\"Separate shower and tub\",\"value1\":\"1\",\"value2\":\"\",\"mandatory\":\"no\"},{\"No\":3,\"title\":\"Master bathroom includes:\",\"name\":\"No appliances\",\"value1\":\"1\",\"value2\":\"\",\"mandatory\":\"no\"}],\"length\":4}],\"minmax\":[],\"step\":0,\"defaultValue\":0},{\"subsection\":6,\"Nooptions\":[{\"element\":0,\"type\":\"switchoption\",\"value\":[{\"No\":0,\"title\":0,\"name\":\"Do you have pets?\",\"value1\":\"100\",\"value2\":\"3\"}],\"length\":1}],\"minmax\":[],\"step\":0,\"defaultValue\":0}]},{\"name\":\"Select your service & extras\",\"desc\":\" \",\"section\":1,\"value\":[{\"subsection\":0,\"Nooptions\":[{\"element\":0,\"type\":\"selectoption\",\"value\":[{\"No\":0,\"title\":\"Choose your cleaning supplies:\",\"name\":\"Green cleaning\",\"value1\":\"1\",\"value2\":\"\",\"mandatory\":\"no\"},{\"No\":1,\"title\":\"Choose your cleaning supplies:\",\"name\":\"Company\'s supplies\",\"value1\":\"1\",\"value2\":\"\",\"mandatory\":\"no\"},{\"No\":2,\"title\":\"Choose your cleaning supplies:\",\"name\":\"Client\'s supplies\",\"value1\":\"1\",\"value2\":\"\",\"mandatory\":\"no\"}],\"length\":3}],\"minmax\":[],\"step\":0,\"defaultValue\":0},{\"subsection\":1,\"Nooptions\":[{\"element\":0,\"type\":\"selectoption\",\"value\":[{\"No\":0,\"title\":\"Cleaning frequency:\",\"name\":\"Weekly Service\",\"value1\":\"1\",\"value2\":\"\",\"mandatory\":\"no\"},{\"No\":1,\"title\":\"Cleaning frequency:\",\"name\":\"Bi-Weekly Service\",\"value1\":\"2\",\"value2\":\"\",\"mandatory\":\"no\"},{\"No\":2,\"title\":\"Cleaning frequency:\",\"name\":\"Tri-Weekly Service\",\"value1\":\"3\",\"value2\":\"\",\"mandatory\":\"no\"},{\"No\":3,\"title\":\"Cleaning frequency:\",\"name\":\"Quarter Weekly Service\",\"value1\":\"4\",\"value2\":\"\",\"mandatory\":\"no\"},{\"No\":4,\"title\":\"Cleaning frequency:\",\"name\":\"Monthly Service\",\"value1\":\"0.1\",\"value2\":\"\",\"mandatory\":\"no\"},{\"No\":5,\"title\":\"Cleaning frequency:\",\"name\":\"One Time Service\",\"value1\":\"0.01\",\"value2\":\"\",\"mandatory\":\"no\"}],\"length\":6}],\"minmax\":[],\"step\":0,\"defaultValue\":0},{\"subsection\":2,\"Nooptions\":[{\"element\":0,\"type\":\"switchoption\",\"value\":[{\"No\":0,\"title\":0,\"name\":\"Dining room\",\"value1\":\"100\",\"value2\":\"6\"},{\"No\":1,\"title\":0,\"name\":\"Play room\",\"value1\":\"200\",\"value2\":\"6\"},{\"No\":2,\"title\":0,\"name\":\"Laundry\",\"value1\":\"300\",\"value2\":\"6\"},{\"No\":3,\"title\":0,\"name\":\"Gym\",\"value1\":\"400\",\"value2\":\"6\"},{\"No\":4,\"title\":0,\"name\":\"Garage\",\"value1\":\"500\",\"value2\":\"6\"}],\"length\":5}],\"minmax\":[],\"step\":0,\"defaultValue\":0},{\"subsection\":3,\"Nooptions\":[{\"element\":0,\"type\":\"switchoption\",\"value\":[{\"No\":0,\"title\":0,\"name\":\"Clean inside the refrigerator?\",\"value1\":\"500\",\"value2\":\"3\"}],\"length\":1}],\"minmax\":[],\"step\":0,\"defaultValue\":0}]},{\"name\":\".\",\"desc\":\" Enter your contact details. We will give you a call to finish up.<br /><br /><br />\",\"section\":2,\"value\":[{\"subsection\":0,\"Nooptions\":[{\"element\":0,\"type\":\"comment\_option\",\"value\":[{\"No\":0,\"title\":\"YOUR NAME\",\"value1\":\"1\",\"value2\":\"\",\"mandatory\":\"no\"}],\"length\":1},{\"element\":1,\"type\":\"comment\_option\",\"value\":[{\"No\":0,\"title\":\"YOUR EMAIL\",\"value1\":\"1\",\"value2\":\"\",\"mandatory\":\"no\"}],\"length\":1},{\"element\":2,\"type\":\"comment\_option\",\"value\":[{\"No\":0,\"title\":\"YOUR PHONE\",\"value1\":\"1\",\"value2\":\"\",\"mandatory\":\"no\"}],\"length\":1}],\"minmax\":[],\"step\":0,\"defaultValue\":0},{\"subsection\":1,\"Nooptions\":[{\"element\":0,\"type\":\"comment\_option\",\"value\":[{\"No\":0,\"title\":\"QUESTIONS OR COMMENTS\",\"value1\":\"5\",\"value2\":\"\",\"mandatory\":\"no\"}],\"length\":1}],\"minmax\":[],\"step\":0,\"defaultValue\":0}]}]');";

        $wpdb->query($query);
        $id = $wpdb->insert_id;

        $query = "INSERT INTO `{$wpdb->prefix}scc_form_parameters` (id,form_id,parameters) VALUES (NULL,'.$id.','{\"fontType\":\"500\",\"colorPicker\":\"#303030\",\"servicepricefontsize\":\"14px\",\"objectColorPicker\":\"#56b665\",\"objectServicepricefontsize\":\"50px\",\"titleFontType\":\"322\",\"titleColorPicker\":\"#000\",\"titleServicepricefontsize\":\"24px\",\"objectsendquote\":\"\",\"objectdetailedlist\":\"\",\"objectsaveicon\":\"\",\"objectscctax\":\"\",\"objectscccoupon\":\"\",\"objecttaxrate\":\"\",\"objectscccurrencylabel\":\"\",\"objectscctitlelabel\":\"\",\"objectscctotalprice\":\"\",\"objecttotalpricestyle\":\"scc\_tp\_style3\",\"objecttotalword\":\"\",\"objectdetailedlistword\":\"\",\"objectsendquoteword\":\"\",\"currency\_style\":\"0\",\"paypal\_checked\":\"false\",\"paypal\_email\":\"\",\"paypal\_shopping\_cart\_name\":\"\",\"paypal\_currency\":\"\"}');";
        $wpdb->query($query);
        */
    }
    elseif ($data_example == 6) {
      
        $query = "INSERT INTO `{$wpdb->prefix}scc_forms` (id,formname,description,ajaxform,formstored,formtranslate) VALUES (NULL, 'Funeral Home Template', '', '', '[{\"name\":\"Professional Memorial Services\",\"desc\":\" Please select the professional services needed for the memorial. Prices below reflect the initial 25KM from our location to the burial or location of cremation. Extra charges for any additional kilometres.\",\"section\":\"0\",\"value\":[{\"subsection\":\"0\",\"Nooptions\":[{\"element\":\"0\",\"type\":\"selectoption\",\"value\":[{\"No\":\"0\",\"title\":\"Professional Services for Direct Cremation\",\"name\":\"Core professional service\",\"value1\":\"900\",\"value2\":\"Co-ordinating activities, transporting (initial 25 KM), documentation, transfer vehicle.\",\"mandatory\":\"yes\"}],\"length\":1}],\"minmax\":[],\"step\":0,\"defaultValue\":0}]},{\"name\":\"Casket & Urn Selection\",\"desc\":\" Please select one of three casket & urn options.\",\"section\":1,\"value\":[{\"subsection\":0,\"Nooptions\":[{\"element\":0,\"type\":\"selectoption\",\"value\":[{\"No\":0,\"title\":\"Cremation Container\",\"name\":\"Heavy Corrugated Cardboard, unlined, no handles (maximum weight restriction is 150 lbs)\",\"value1\":\"180\",\"value2\":\"Heavy Corrugated Cardboard, unlined, no handles (maximum weight restriction is 150 lbs)\",\"mandatory\":\"yes\"},{\"No\":1,\"title\":\"Cremation Container\",\"name\":\"Glendale\",\"value1\":\"525\",\"value2\":\"Solid select wood, natural finish, unlined, no handles with a basic white crepe interior by Victoriaville Casket\",\"mandatory\":\"yes\"},{\"No\":2,\"title\":\"Cremation Container\",\"name\":\"Moka\",\"value1\":\"1595\",\"value2\":\"Veneer sided flat top, Moka woodgrain finish, beige crepe interior by Victoriaville Casket\",\"mandatory\":\"yes\"}],\"length\":3},{\"element\":1,\"type\":\"selectoption\",\"value\":[{\"No\":0,\"title\":\"Urn Selection\",\"name\":\"Cardboard Urn\",\"value1\":\"0\",\"value2\":\"Included in the base price.\",\"mandatory\":\"yes\"},{\"No\":1,\"title\":\"Urn Selection\",\"name\":\"Plastic utility Urn\",\"value1\":\"35\",\"value2\":\"\",\"mandatory\":\"yes\"},{\"No\":2,\"title\":\"Urn Selection\",\"name\":\"Standard Plain Urn\",\"value1\":\"295\",\"value2\":\"Solid wood\",\"mandatory\":\"yes\"},{\"No\":3,\"title\":\"Urn Selection\",\"name\":\"Inlaid Style Urn\",\"value1\":\"350\",\"value2\":\"Solid Wood in Oak or Cherry\",\"mandatory\":\"yes\"},{\"No\":4,\"title\":\"Urn Selection\",\"name\":\"Black \\\\/ White Kent Urn Cultured Marble\",\"value1\":\"395\",\"value2\":\"\",\"mandatory\":\"yes\"},{\"No\":5,\"title\":\"Urn Selection\",\"name\":\" Returning Home\",\"value1\":\"425\",\"value2\":\"Brass Urn with Blue Floral Pattern \",\"mandatory\":\"yes\"},{\"No\":6,\"title\":\"Urn Selection\",\"name\":\"Majestic Rose\",\"value1\":\"425\",\"value2\":\"Solid Brass with Gold Rose Stem and Petals\",\"mandatory\":\"yes\"}],\"length\":7}],\"minmax\":[],\"step\":0,\"defaultValue\":0}]},{\"name\":\"Mandatory Disbursements\",\"desc\":\" \",\"section\":3,\"value\":[{\"subsection\":0,\"Nooptions\":[{\"element\":0,\"type\":\"selectoption\",\"value\":[{\"No\":0,\"title\":\"Coroner\'s Fee\",\"name\":\"Coroner\'s Fee\",\"value1\":\"75\",\"value2\":\"This fee is mandatory\",\"mandatory\":\"yes\"}],\"length\":1},{\"element\":1,\"type\":\"selectoption\",\"value\":[{\"No\":0,\"title\":\"Municipal Licensing Fee\",\"name\":\"Municipal Licensing Fee\",\"value1\":\"25\",\"value2\":\"This fee is mandatory\",\"mandatory\":\"yes\"}],\"length\":1}],\"minmax\":[],\"step\":0,\"defaultValue\":0},{\"subsection\":1,\"Nooptions\":[{\"element\":0,\"type\":\"selectoption\",\"value\":[{\"No\":0,\"title\":\"Cremation Fee\",\"name\":\"Cremation Fee (Highfields Park Crematorium)\",\"value1\":\"600\",\"value2\":\"This fee is mandatory\",\"mandatory\":\"yes\"}],\"length\":1}],\"minmax\":[],\"step\":0,\"defaultValue\":0}]},{\"name\":\"Cash disbursements\",\"desc\":\" \",\"section\":4,\"value\":[{\"subsection\":0,\"Nooptions\":[{\"element\":0,\"type\":\"switchoption\",\"value\":[{\"No\":0,\"title\":0,\"name\":\"Monument lettering\",\"value1\":\"800\",\"value2\":\"2\",\"mandatory\":\"\"},{\"No\":1,\"title\":0,\"name\":\"Clergy\",\"value1\":\"250\",\"value2\":\"2\",\"mandatory\":\"\"},{\"No\":2,\"title\":0,\"name\":\"Flowers\",\"value1\":\"300\",\"value2\":\"2\",\"mandatory\":\"\"}],\"length\":3}],\"minmax\":[],\"step\":0,\"defaultValue\":0}]}, {\"name\":\"AfterCare & Estate Supports\",\"desc\":\" Following the death of a loved one, family members are often left with an enormous amount of paperwork that must be completed to maximize government and corporate benefits and guard against identity theft.  In addition, executors and next of kin often need support in understanding the estate process, including probate, banking changes, and impact on estate assets.<br \\\\/><br \\\\/>\",\"section\":2,\"value\":[{\"subsection\":0,\"Nooptions\":[{\"element\":0,\"type\":\"switchoption\",\"value\":[{\"No\":0,\"title\":0,\"name\":\"AfterCare & Estate Supports\",\"value1\":\"300\",\"value2\":\"2\",\"mandatory\":\"\"}],\"length\":1}],\"minmax\":[],\"step\":0,\"defaultValue\":0}]}]', '[{\"key\":\"Total\",\"lang\":\"en\",\"translation\":\"Total\"},{\"key\":\"Description\",\"lang\":\"en\",\"translation\":\"Description\"},{\"key\":\"Unit Price\",\"lang\":\"en\",\"translation\":\"Unit Price\"},{\"key\":\"Quantity\",\"lang\":\"en\",\"translation\":\"Quantity\"},{\"key\":\"Price\",\"lang\":\"en\",\"translation\":\"Price\"},{\"key\":\"SEND\",\"lang\":\"en\",\"translation\":\"SEND\"},{\"key\":\"Total Price\",\"lang\":\"en\",\"translation\":\"Total Price\"},{\"key\":\"Summary\",\"lang\":\"en\",\"translation\":\"Summary\"},{\"key\":\"Email Quote\",\"lang\":\"en\",\"translation\":\"Email Quote\"},{\"key\":\"Detailed List\",\"lang\":\"en\",\"translation\":\"Detailed List\"},{\"key\":\"Choose an option...\",\"lang\":\"en\",\"translation\":\"Choose an option...\"},{\"key\":\"Your Name\",\"lang\":\"en\",\"translation\":\"Your Name\"},{\"key\":\"Your Email\",\"lang\":\"en\",\"translation\":\"Your Email\"},{\"key\":\"Your Phone\",\"lang\":\"en\",\"translation\":\"Your Phone\"},{\"key\":\"Your Phone (Optional)\",\"lang\":\"en\",\"translation\":\"Your Phone (Optional)\"},{\"key\":\"Coupon Code\",\"lang\":\"en\",\"translation\":\"Coupon Code\"}]');";
    
        $wpdb->query($query);
        $id = $wpdb->insert_id;
      
        $query = "INSERT INTO `{$wpdb->prefix}scc_form_parameters` (id,form_id,parameters) VALUES (NULL, '.$id.', '{\"fontType\":\"432\",\"colorPicker\":\"#000\",\"servicepricefontsize\":\"16px\",\"objectColorPicker\":\"#000\",\"objectServicepricefontsize\":\"50px\",\"titleFontType\":\"432\",\"titleColorPicker\":\"#000\",\"titleServicepricefontsize\":\"30px\",\"objectsendquote\":\"\",\"objectdetailedlist\":\"\",\"objectsaveicon\":\"\",\"objectscctax\":\"\",\"objectscccoupon\":\"\",\"objecttaxrate\":\"\",\"objectscccurrencylabel\":\"\",\"objectscctitlelabel\":\"\",\"objectscctotalprice\":\"\",\"objecttotalpricestyle\":\"Style for Total Price Bar\",\"objecttotalword\":\"\",\"objectdetailedlistword\":\"\",\"objectsendquoteword\":\"\",\"objectscctotalpricefloat\":\"\",\"form\\_field\\_style\":\"style\\_1\",\"currency\\_style\":\"0\",\"paypal\\_checked\":\"false\",\"paypal\\_email\":\"\",\"paypal\\_shopping\\_cart\\_name\":\"\",\"paypal\\_currency\":\"\"}');";
        $wpdb->query($query);
        

       

    }

    elseif ($data_example == 7) {
      
        $query = "INSERT INTO `{$wpdb->prefix}scc_forms` (id,formname,description,ajaxform,formstored,formtranslate) VALUES (NULL, 'Content Writing Agency Template', '', '', '[{ \"name\":\"Content Creation & Marketing Packages\", \"desc\":\"<br><h4><b>GENERAL BLOG POSTS ($0.30/Word)</b></h4>500 words min.<br />Topic of your choice (or we pick)<br />Researched Content<br />SEO ready<br />1-2 images per post<br />Authority Links Included<br />Shared on Social Media<br><br.<br /><br /><h4><b>EMAIL/EBOOK CONTENT ($0.35/Word)</b></h4>1,000 words min.<br />Topic of your choice (or we pick)<br />Researched Content<br />SEO ready<br />1-2 images per page<br />Authority Links Included (Optional)<br />Shared on Social Media<br /><br /><h4><b>MARKETING/LP CONTENT ($0.50/Word)</b></h4>250 words min.<br />Topic of your choice (or we pick)<br />Researched Content<br />SEO ready<br />1-2 images per post<br />Authority Links Included<br />Shared on Social Media<br><br><b>Please enter the amount of words that you need for each of the different packages. Choose one of more packages.</b> <br><hr>\", \"section\":\"0\", \"value\":[ { \"subsection\":\"0\", \"Nooptions\":[ { \"element\":\"0\", \"type\":\"number_option\", \"value\":[ { \"No\":\"0\", \"title\":\"GENERAL BLOG POSTS ($0.30/Word)\", \"value1\":\"0.3\", \"mandatory\":\"no\", \"column_dskp\":\"6\", \"column_mobl\":\"6\" } ], \"length\":1 }, { \"element\":1, \"type\":\"number_option\", \"value\":[ { \"No\":0, \"title\":\"EMAIL/EBOOK CONTENT ($0.35/Word)\", \"value1\":\"0.35\", \"mandatory\":\"no\", \"column_dskp\":\"6\", \"column_mobl\":\"6\" } ], \"length\":1 }, { \"element\":2, \"type\":\"number_option\", \"value\":[ { \"No\":0, \"title\":\"MARKETING/LP CONTENT ($0.50/Word)\", \"value1\":\"0.5\", \"mandatory\":\"no\", \"column_dskp\":\"6\", \"column_mobl\":\"6\" } ], \"length\":1 } ], \"minmax\":[ ], \"step\":0, \"defaultValue\":0 } ] }]', '[{\"key\":\"Total\",\"lang\":\"en\",\"translation\":\"Total\"},{\"key\":\"Description\",\"lang\":\"en\",\"translation\":\"Description\"},{\"key\":\"Unit Price\",\"lang\":\"en\",\"translation\":\"Unit Price\"},{\"key\":\"Quantity\",\"lang\":\"en\",\"translation\":\"Quantity\"},{\"key\":\"Price\",\"lang\":\"en\",\"translation\":\"Price\"},{\"key\":\"SEND\",\"lang\":\"en\",\"translation\":\"SEND\"},{\"key\":\"Total Price\",\"lang\":\"en\",\"translation\":\"Total Price\"},{\"key\":\"Summary\",\"lang\":\"en\",\"translation\":\"Summary\"},{\"key\":\"Email Quote\",\"lang\":\"en\",\"translation\":\"Email Quote\"},{\"key\":\"Detailed List\",\"lang\":\"en\",\"translation\":\"Detailed List\"},{\"key\":\"Choose an option...\",\"lang\":\"en\",\"translation\":\"Choose an option...\"},{\"key\":\"Your Name\",\"lang\":\"en\",\"translation\":\"Your Name\"},{\"key\":\"Your Email\",\"lang\":\"en\",\"translation\":\"Your Email\"},{\"key\":\"Your Phone\",\"lang\":\"en\",\"translation\":\"Your Phone\"},{\"key\":\"Your Phone (Optional)\",\"lang\":\"en\",\"translation\":\"Your Phone (Optional)\"},{\"key\":\"Coupon Code\",\"lang\":\"en\",\"translation\":\"Coupon Code\"}]');";
    
        $wpdb->query($query);
        $id = $wpdb->insert_id;
      
        $query = "INSERT INTO `{$wpdb->prefix}scc_form_parameters` (id,form_id,parameters) VALUES (NULL, '.$id.', '{\"fontType\":\"432\",\"colorPicker\":\"#000\",\"servicepricefontsize\":\"16px\",\"objectColorPicker\":\"#000\",\"objectServicepricefontsize\":\"50px\",\"titleFontType\":\"432\",\"titleColorPicker\":\"#000\",\"titleServicepricefontsize\":\"30px\",\"objectsendquote\":\"\",\"objectdetailedlist\":\"\",\"objectsaveicon\":\"\",\"objectscctax\":\"\",\"objectscccoupon\":\"\",\"objecttaxrate\":\"\",\"objectscccurrencylabel\":\"\",\"objectscctitlelabel\":\"\",\"objectscctotalprice\":\"\",\"objecttotalpricestyle\":\"StyleforTotalPriceBar\",\"objecttotalword\":\"\",\"objectdetailedlistword\":\"\",\"objectsendquoteword\":\"\",\"objectscctotalpricefloat\":\"\",\"form_field_style\":\"style_1\",\"currency_style\":\"0\",\"paypal_checked\":\"false\",\"paypal_email\":\"\",\"paypal_shopping_cart_name\":\"\",\"paypal_currency\":\"\"}');";
        $wpdb->query($query);
    }
    //Start of template 8 - Audio Editing & Podcast - User choice #9
    else if ($data_example == 8) {
      
          $json_data = json_decode(file_get_contents(dirname(__FILE__) . '/assets/templates/8.json'), true);

          if(gettype($json_data) != NULL){
            global $wpdb;

            $formName =  $wpdb->esc_like(str_replace("|percent|", "%",htmlspecialchars($json_data['scc_form']['formname'] . ' restored')), ENT_NOQUOTES);
            $formName = trim($formName, '"');

            $formStored = $wpdb->esc_like((str_replace("|percent|", "%",json_encode($json_data['scc_form']['formstored'], JSON_UNESCAPED_UNICODE))));
            
            $formTranslate = $wpdb->esc_like((str_replace("|percent|", "%",json_encode($json_data['scc_form']['formtranslate'], JSON_UNESCAPED_UNICODE))));

            $form_parameters = $wpdb->esc_like((str_replace("|percent|", "%",json_encode($json_data['scc_form_parameters']['parameters'], JSON_UNESCAPED_UNICODE))));


            $query = $wpdb->prepare("INSERT INTO {$wpdb->prefix}scc_forms (id,formname,description,ajaxform,formstored, formtranslate) VALUES (NULL, %s, '', '', %s, %s);", $formName, $formStored, $formTranslate);
            $wpdb->query($query);
            $id = $wpdb->insert_id;
            $query = $wpdb->prepare("INSERT INTO `{$wpdb->prefix}scc_form_parameters` (id,form_id,parameters) VALUES (NULL, %d, %s);", $id, $form_parameters);
            $wpdb->query($query);

          }

    }
    //Start of template 9 - Social Media Manager Template - User choice #10
    else if ($data_example == 9) {
            
            $json_data = json_decode(file_get_contents(dirname(__FILE__) . '/assets/templates/9.json'), true);

            if(gettype($json_data) != NULL){
              global $wpdb;

              $formName =  $wpdb->esc_like(str_replace("|percent|", "%",htmlspecialchars($json_data['scc_form']['formname'] . ' restored')), ENT_NOQUOTES);
              $formName = trim($formName, '"');

              $formStored = $wpdb->esc_like((str_replace("|percent|", "%",json_encode($json_data['scc_form']['formstored'], JSON_UNESCAPED_UNICODE))));
              
              $formTranslate = $wpdb->esc_like((str_replace("|percent|", "%",json_encode($json_data['scc_form']['formtranslate'], JSON_UNESCAPED_UNICODE))));

              $form_parameters = $wpdb->esc_like((str_replace("|percent|", "%",json_encode($json_data['scc_form_parameters']['parameters'], JSON_UNESCAPED_UNICODE))));


              $query = $wpdb->prepare("INSERT INTO {$wpdb->prefix}scc_forms (id,formname,description,ajaxform,formstored, formtranslate) VALUES (NULL, %s, '', '', %s, %s);", $formName, $formStored, $formTranslate);
              $wpdb->query($query);
              $id = $wpdb->insert_id;
              $query = $wpdb->prepare("INSERT INTO `{$wpdb->prefix}scc_form_parameters` (id,form_id,parameters) VALUES (NULL, %d, %s);", $id, $form_parameters);
              $wpdb->query($query);

            }

      }
      
    //Start of template 10 - Student Fees Template - User choice #11
      else if ($data_example == 10) {
            
        $json_data = json_decode(file_get_contents(dirname(__FILE__) . '/assets/templates/10.json'), true);

        if(gettype($json_data) != NULL){
          global $wpdb;

          $formName =  $wpdb->esc_like(str_replace("|percent|", "%",htmlspecialchars($json_data['scc_form']['formname'] . ' restored')), ENT_NOQUOTES);
          $formName = trim($formName, '"');

          $formStored = $wpdb->esc_like((str_replace("|percent|", "%",json_encode($json_data['scc_form']['formstored'], JSON_UNESCAPED_UNICODE))));
          
          $formTranslate = $wpdb->esc_like((str_replace("|percent|", "%",json_encode($json_data['scc_form']['formtranslate'], JSON_UNESCAPED_UNICODE))));

          $form_parameters = $wpdb->esc_like((str_replace("|percent|", "%",json_encode($json_data['scc_form_parameters']['parameters'], JSON_UNESCAPED_UNICODE))));


          $query = $wpdb->prepare("INSERT INTO {$wpdb->prefix}scc_forms (id,formname,description,ajaxform,formstored, formtranslate) VALUES (NULL, %s, '', '', %s, %s);", $formName, $formStored, $formTranslate);
          $wpdb->query($query);
          $id = $wpdb->insert_id;
          $query = $wpdb->prepare("INSERT INTO `{$wpdb->prefix}scc_form_parameters` (id,form_id,parameters) VALUES (NULL, %d, %s);", $id, $form_parameters);
          $wpdb->query($query);

        }

      }
      //end of tempalte 10
    //Start of template 11 - Digital Print & Lamination - User Choice #12
      else if ($data_example == 11) {
            
        $json_data = json_decode(file_get_contents(dirname(__FILE__) . '/assets/templates/11.json'), true);

        if(gettype($json_data) != NULL){
          global $wpdb;

          $formName =  $wpdb->esc_like(str_replace("|percent|", "%",htmlspecialchars($json_data['scc_form']['formname'] . ' restored')), ENT_NOQUOTES);
          $formName = trim($formName, '"');

          $formStored = $wpdb->esc_like((str_replace("|percent|", "%",json_encode($json_data['scc_form']['formstored'], JSON_UNESCAPED_UNICODE))));
          
          $formTranslate = $wpdb->esc_like((str_replace("|percent|", "%",json_encode($json_data['scc_form']['formtranslate'], JSON_UNESCAPED_UNICODE))));

          $form_parameters = $wpdb->esc_like((str_replace("|percent|", "%",json_encode($json_data['scc_form_parameters']['parameters'], JSON_UNESCAPED_UNICODE))));


          $query = $wpdb->prepare("INSERT INTO {$wpdb->prefix}scc_forms (id,formname,description,ajaxform,formstored, formtranslate) VALUES (NULL, %s, '', '', %s, %s);", $formName, $formStored, $formTranslate);
          $wpdb->query($query);
          $id = $wpdb->insert_id;
          $query = $wpdb->prepare("INSERT INTO `{$wpdb->prefix}scc_form_parameters` (id,form_id,parameters) VALUES (NULL, %d, %s);", $id, $form_parameters);
          $wpdb->query($query);

        }

      }
      //end of tempalte 11
      //Start of template 12 - Kitchen Renovations Template - User choice #13
      else if ($data_example == 12) {
            
        $json_data = json_decode(file_get_contents(dirname(__FILE__) . '/assets/templates/12.json'), true);

        if(gettype($json_data) != NULL){
          global $wpdb;

          $formName =  $wpdb->esc_like(str_replace("|percent|", "%",htmlspecialchars($json_data['scc_form']['formname'] . ' restored')), ENT_NOQUOTES);
          $formName = trim($formName, '"');

          $formStored = $wpdb->esc_like((str_replace("|percent|", "%",json_encode($json_data['scc_form']['formstored'], JSON_UNESCAPED_UNICODE))));
          
          $formTranslate = $wpdb->esc_like((str_replace("|percent|", "%",json_encode($json_data['scc_form']['formtranslate'], JSON_UNESCAPED_UNICODE))));

          $form_parameters = $wpdb->esc_like((str_replace("|percent|", "%",json_encode($json_data['scc_form_parameters']['parameters'], JSON_UNESCAPED_UNICODE))));


          $query = $wpdb->prepare("INSERT INTO {$wpdb->prefix}scc_forms (id,formname,description,ajaxform,formstored, formtranslate) VALUES (NULL, %s, '', '', %s, %s);", $formName, $formStored, $formTranslate);
          $wpdb->query($query);
          $id = $wpdb->insert_id;
          $query = $wpdb->prepare("INSERT INTO `{$wpdb->prefix}scc_form_parameters` (id,form_id,parameters) VALUES (NULL, %d, %s);", $id, $form_parameters);
          $wpdb->query($query);

        }

      }
      //end of tempalte 12
      //Start of template 13 - Simple Budget Template - Choice #14
      else if ($data_example == 13) {
            
        $json_data = json_decode(file_get_contents(dirname(__FILE__) . '/assets/templates/13.json'), true);

        if(gettype($json_data) != NULL){
          global $wpdb;

          $formName =  $wpdb->esc_like(str_replace("|percent|", "%",htmlspecialchars($json_data['scc_form']['formname'] . ' restored')), ENT_NOQUOTES);
          $formName = trim($formName, '"');

          $formStored = $wpdb->esc_like((str_replace("|percent|", "%",json_encode($json_data['scc_form']['formstored'], JSON_UNESCAPED_UNICODE))));
          
          $formTranslate = $wpdb->esc_like((str_replace("|percent|", "%",json_encode($json_data['scc_form']['formtranslate'], JSON_UNESCAPED_UNICODE))));

          $form_parameters = $wpdb->esc_like((str_replace("|percent|", "%",json_encode($json_data['scc_form_parameters']['parameters'], JSON_UNESCAPED_UNICODE))));


          $query = $wpdb->prepare("INSERT INTO {$wpdb->prefix}scc_forms (id,formname,description,ajaxform,formstored, formtranslate) VALUES (NULL, %s, '', '', %s, %s);", $formName, $formStored, $formTranslate);
          $wpdb->query($query);
          $id = $wpdb->insert_id;
          $query = $wpdb->prepare("INSERT INTO `{$wpdb->prefix}scc_form_parameters` (id,form_id,parameters) VALUES (NULL, %d, %s);", $id, $form_parameters);
          $wpdb->query($query);

        }

      }
      //end of tempalte 13
      // start of template ID 14 titled "15 - Food Catering Template"
      else if ($data_example == 14) {
            
        $json_data = json_decode(file_get_contents(dirname(__FILE__) . '/assets/templates/14.json'), true);

        if(gettype($json_data) != NULL){
          global $wpdb;

          $formName =  $wpdb->esc_like(str_replace("|percent|", "%",htmlspecialchars($json_data['scc_form']['formname'] . ' restored')), ENT_NOQUOTES);
          $formName = trim($formName, '"');

          $formStored = $wpdb->esc_like((str_replace("|percent|", "%",json_encode($json_data['scc_form']['formstored'], JSON_UNESCAPED_UNICODE))));
          
          $formTranslate = $wpdb->esc_like((str_replace("|percent|", "%",json_encode($json_data['scc_form']['formtranslate'], JSON_UNESCAPED_UNICODE))));

          $form_parameters = $wpdb->esc_like((str_replace("|percent|", "%",json_encode($json_data['scc_form_parameters']['parameters'], JSON_UNESCAPED_UNICODE))));


          $query = $wpdb->prepare("INSERT INTO {$wpdb->prefix}scc_forms (id,formname,description,ajaxform,formstored, formtranslate) VALUES (NULL, %s, '', '', %s, %s);", $formName, $formStored, $formTranslate);
          $wpdb->query($query);
          $id = $wpdb->insert_id;
          $query = $wpdb->prepare("INSERT INTO `{$wpdb->prefix}scc_form_parameters` (id,form_id,parameters) VALUES (NULL, %d, %s);", $id, $form_parameters);
          $wpdb->query($query);

        }

      }
      // end of tempalte 14

     // start of template ID 15 named "16 - Pest Control Service (Template)"
      else if ($data_example == 15) {
        $json_data = json_decode(file_get_contents(dirname(__FILE__) . '/assets/templates/15.json'), true);
        if (gettype($json_data) != null) {
            global $wpdb;
      
            $formName =  $wpdb->esc_like(str_replace("|percent|", "%",htmlspecialchars($json_data['scc_form']['formname'] . ' restored')), ENT_NOQUOTES);
            $formName = trim($formName, '"');
      
            $formStored = $wpdb->esc_like((str_replace("|percent|", "%",json_encode($json_data['scc_form']['formstored'], JSON_UNESCAPED_UNICODE))));
      
            $formTranslate = $wpdb->esc_like((str_replace("|percent|", "%",json_encode($json_data['scc_form']['formtranslate'], JSON_UNESCAPED_UNICODE))));
      
            $form_parameters = $wpdb->esc_like((str_replace("|percent|", "%",json_encode($json_data['scc_form_parameters']['parameters'], JSON_UNESCAPED_UNICODE))));
      
      
            $query = $wpdb->prepare("INSERT INTO {$wpdb->prefix}scc_forms (id,formname,description,ajaxform,formstored, formtranslate) VALUES (NULL, %s, '', '', %s, %s);", $formName, $formStored, $formTranslate);
            $wpdb->query($query);
            $id = $wpdb->insert_id;
            $query = $wpdb->prepare("INSERT INTO `{$wpdb->prefix}scc_form_parameters` (id,form_id,parameters) VALUES (NULL, %d, %s);", $id, $form_parameters);
            $wpdb->query($query);
    
        }
      }
      // end of template ID 15 

    // start of template ID 16 named "17 - Book Publisher Service (Template)"
      else if ($data_example == 16) {
        $json_data = json_decode(file_get_contents(dirname(__FILE__) . '/assets/templates/16.json'), true);
        if (gettype($json_data) != null) {
            global $wpdb;
      
            $formName =  $wpdb->esc_like(str_replace("|percent|", "%",htmlspecialchars($json_data['scc_form']['formname'] . ' restored')), ENT_NOQUOTES);
            $formName = trim($formName, '"');
      
            $formStored = $wpdb->esc_like((str_replace("|percent|", "%",json_encode($json_data['scc_form']['formstored'], JSON_UNESCAPED_UNICODE))));
      
            $formTranslate = $wpdb->esc_like((str_replace("|percent|", "%",json_encode($json_data['scc_form']['formtranslate'], JSON_UNESCAPED_UNICODE))));
      
            $form_parameters = $wpdb->esc_like((str_replace("|percent|", "%",json_encode($json_data['scc_form_parameters']['parameters'], JSON_UNESCAPED_UNICODE))));
      
      
            $query = $wpdb->prepare("INSERT INTO {$wpdb->prefix}scc_forms (id,formname,description,ajaxform,formstored, formtranslate) VALUES (NULL, %s, '', '', %s, %s);", $formName, $formStored, $formTranslate);
            $wpdb->query($query);
            $id = $wpdb->insert_id;
            $query = $wpdb->prepare("INSERT INTO `{$wpdb->prefix}scc_form_parameters` (id,form_id,parameters) VALUES (NULL, %d, %s);", $id, $form_parameters);
            $wpdb->query($query);
    
        }
      }
      // end of template ID 16

    echo $id; exit;
    
}
function sscSaveCoupon()
{

    global $wpdb;
    $id = intval($_POST['id']);
    $name = sanitize_text_field($_POST['name']);
    $code = sanitize_text_field($_POST['code']);
    $startdate = sanitize_text_field($_POST['startdate']);
    $enddate = sanitize_text_field($_POST['enddate']);
    $discountpercentage = floatval($_POST['discountpercentage']);
    $discountvalue = floatval($_POST['discountvalue']);
    $minspend = floatval($_POST['minspend']);
    $maxspend = floatval($_POST['maxspend']);

    if(isset($_POST) && isset($_POST['id']) && $_POST['id']  == 0) {




        $query = "INSERT INTO ".$wpdb->prefix."scc_coupons (id, name,code, startdate, enddate, discountpercentage, discountvalue, minspend, maxspend) VALUES (NULL,'".$name."', '".$code."', str_to_date('".$startdate."', '%m/%d/%Y'), str_to_date('".$enddate."', '%m/%d/%Y'), ".$discountpercentage.", ".$discountvalue.", ".$minspend.", ".$maxspend.")";
        $wpdb->query($query);
        echo $wpdb->$insert_id;

    }elseif(isset($_POST) && isset($_POST['id']) && $_POST['id'] > 0) {
        $query = "UPDATE ".$wpdb->prefix."scc_coupons SET name = '".$name."',code ='".$code."', startdate = str_to_date('".$startdate."', '%m/%d/%Y'), enddate = str_to_date('".$enddate."', '%m/%d/%Y'), discountpercentage =".$discountpercentage.", discountvalue =".$discountvalue.", minspend = ".$minspend.", maxspend =".$maxspend."  WHERE id = ". $id.";";

        $wpdb->query($query);
        echo $query;

    }else{
        echo $id;
    }
    die();
}
function sccDeleteCoupon()
{
    global $wpdb;
    if (!isset($_POST['id'])) { echo "ERROR - value does not exist"; return; 
    }
      $id = (int)$_POST['id'];
    if ($id == 0) { echo "ERROR - value is 0"; return; 
    }
      $query = $wpdb->prepare("DELETE FROM {$wpdb->prefix}scc_coupons WHERE id = %d LIMIT 1", $id);
      $wpdb->query($query);

      die();
}
function sscCheckCoupon()
{

    global $wpdb;
    if(isset($_GET['coupon_code'])) {
        $coupon_code  = sanitize_text_field($_GET['coupon_code']);
        $coupons = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}scc_coupons WHERE code = '".$coupon_code."'  AND CURDATE() between startdate and enddate;");
        if(sizeof($coupons) > 0) {
            echo wp_send_json_success($coupons);
        }else{
            echo wp_send_json_success("false");
        }
    }
    exit;
    die();
}
function scc_saveSettings()
{
    $cs = (int)$_POST['color_scheme'];
    if ($cs == 0) { $cs = 1;
    }
    update_option('scc_color-scheme', $cs);
    update_option('scc_currency', $_POST['currency_code']);
    update_option('scc_currencytext', $_POST['currency_text']);
    update_option('scc_currency_style', $_POST['currency_style']);
    update_option('scc_currency_coversion_mode', $_POST['scc_currency_coversion_mode']);
    update_option('scc_currency_coversion_manual_selection', $_POST['scc_currency_coversion_manual_selection']);
    
}

function scc_saveEmailSettings()
{
    $sender = $_POST['sender_name'];
    $email =  $_POST['sender_email'];
    $message = $_POST['message_form'];
    $emailsubject = $_POST['emailsubject_testing'];
    $sccemailfooter = $_POST['sccemailfooter'];
    $scc_email_send_copy = $_POST['scc_email_send_copy'];

    $tags_escaped = ["&lt;customer-name&gt;","&lt;customer-phone&gt;","&lt;customer-email&gt;","&lt;customer-ip-address&gt;","&lt;customer-browser-info&gt;","&lt;device&gt;","&lt;customer-referral&gt;"];
    function tags_decode($a)
    {
        return htmlspecialchars_decode($a);
    }
    $tags_decoded = array_map('tags_decode', $tags_escaped);
    $message = str_replace($tags_escaped, $tags_decoded, $message);
    update_option('scc_email_send_copy', $scc_email_send_copy);
    update_option('scc_emailsender', $email);
    update_option('scc_sendername', $sender);
    update_option('scc_messageform', $message);
    update_option('scc_footerdisclaimer', htmlentities(wp_kses_post($sccemailfooter)));
    update_option('scc_emailsubject', $emailsubject);

    echo get_option('scc_email_send_copy');
    die();
}

function scc_saveField()
{

    global $wpdb;

    $wild = '"';
    $like1 = null;
    $like2 = $wpdb->esc_like(htmlspecialchars($_POST['fieldname']), ENT_QUOTES);
    $like3 = $wpdb->esc_like(''); //$wild . $wpdb->esc_like(json_encode($_POST['fieldform'])) . $wild;
    $like4 = $wpdb->esc_like($_POST['fieldPreview']); //$wild . $wpdb->esc_like($_POST['fieldPreview']) . $wild;
    $like5 = $wpdb->esc_like($_POST['adminsettingsid']); // $wild . $wpdb->esc_like($_POST['adminsettingsid']) . $wild;
    $link9 = $wpdb->esc_like($_POST['dictionary']);

    $calculateSaveCount = get_option('scc-save-count') ? (int) get_option('scc-save-count') + 1 : 1 ;

    update_option('scc-save-count' , $calculateSaveCount);

    /*
    utf8_encode($like2);
    utf8_encode($like3);
    utf8_encode($like4);
    utf8_encode($link9);
    */
     
    if (isset($_POST['adminsettingsid']) && is_numeric($_POST['adminsettingsid'])) {
        //  $query = $wpdb->prepare( "UPDATE {$wpdb->prefix}scc_forms SET formname = %s, ajaxform = %s, formstored = %s, description = %s WHERE id = %d", like_escape($_POST['fieldname']), like_escape($_POST['fieldform']), like_escape($_POST['fieldPreview']),$like4, $_POST['adminsettingsid']);
        //   $query = $wpdb->prepare( "UPDATE {$wpdb->prefix}scc_forms SET description = %s, formname = %s, ajaxform = %s, formstored = %s WHERE id = %d", $like1, $like2, $like3, $like4, $like5);

        $query = $wpdb->prepare("UPDATE {$wpdb->prefix}scc_forms SET description = %s, formname = %s, ajaxform = %s, formstored = %s, formtranslate = %s WHERE id = %d", $like1, $like2, $like3, $like4, $link9, $like5);

        $last_id = $_POST['adminsettingsid'];
        $wpdb->query($query);
        
        $parameters = array();
        $parameters['fontType'] = isset($_POST['fontType']) ? $_POST['fontType'] : '';
        $parameters['inheritFontType'] = isset($_POST['inheritFontType']) ? $_POST['inheritFontType'] : '';
        $parameters['fontTypeVariant'] = isset($_POST['fontTypeVariant']) ? $_POST['fontTypeVariant'] : 'regular';
        $parameters['colorPicker'] = isset($_POST['colorPicker']) ? $_POST['colorPicker'] : '';
        $parameters['servicepricefontsize'] = isset($_POST['servicepricefontsize']) ? $_POST['servicepricefontsize'] : '';

        $parameters['objectColorPicker'] = isset($_POST['objectColorPicker']) ? $_POST['objectColorPicker'] : '';
        $parameters['objectServicepricefontsize'] = isset($_POST['objectServicepricefontsize']) ? $_POST['objectServicepricefontsize'] : '';
        $parameters['titleFontType'] = isset($_POST['title_fontType']) ? $_POST['title_fontType'] : '';
        $parameters['titleFontTypeVariant'] = isset($_POST['title_fontType_variant']) ? $_POST['title_fontType_variant'] : 'regular';
        $parameters['titleColorPicker'] = isset($_POST['title_colorPicker']) ? $_POST['title_colorPicker'] : '';
        $parameters['titleServicepricefontsize'] = isset($_POST['title_servicepricefontsize']) ? $_POST['title_servicepricefontsize'] : '';

        // more settings options starts
        $parameters['toggle_boxshadow_style2'] = isset($_POST['toggle_boxshadow_style2']) ? $_POST['toggle_boxshadow_style2'] : '';
        $parameters['objectsendquote'] = isset($_POST['objectsendquote']) ? $_POST['objectsendquote'] : '';
        $parameters['objectdetailedlist'] = isset($_POST['objectdetailedlist']) ? $_POST['objectdetailedlist'] : '';
        $parameters['objectsaveicon'] = isset($_POST['objectsaveicon']) ? $_POST['objectsaveicon'] : '';
        $parameters['objectDisableUnitCol'] = isset($_POST['objectDisableUnitCol']) ? $_POST['objectDisableUnitCol'] : '';
        $parameters['objectscctax'] = isset($_POST['objectscctax']) ? $_POST['objectscctax'] : '';
        $parameters['objectscccoupon'] = isset($_POST['objectscccoupon']) ? $_POST['objectscccoupon'] : '';
        $parameters['objecttaxrate'] = isset($_POST['objecttaxrate']) ? $_POST['objecttaxrate'] : '';
        $parameters['showTaxBeforeTotal'] = isset($_POST['showTaxBeforeTotal']) ? $_POST['showTaxBeforeTotal'] : 'false';
        $parameters['objectTaxInclusionInPayPal'] = isset($_POST['objectTaxInclusionInPayPal']) && ($_POST['objectTaxInclusionInPayPal'] == "true") ? true : false;
        $parameters['userActionBtnStyle'] = isset($_POST['userActionBtnStyle']) ? $_POST['userActionBtnStyle'] : '';
        $parameters['objectscccurrencylabel'] = isset($_POST['objectscccurrencylabel']) ? $_POST['objectscccurrencylabel'] : '';
        $parameters['objectscctitlelabel'] = isset($_POST['objectscctitlelabel']) ? $_POST['objectscctitlelabel'] : '';
        $parameters['objectscctotalprice'] = isset($_POST['objectscctotalprice']) ? $_POST['objectscctotalprice'] : '';
        $parameters['objecttotalpricestyle'] = isset($_POST['objecttotalpricestyle']) ? $_POST['objecttotalpricestyle'] : '';
        $parameters['objecttotalword'] = isset($_POST['objecttotalword']) ? $_POST['objecttotalword'] : '';
        $parameters['objectdetailedlistword'] = isset($_POST['objectdetailedlistword']) ? $_POST['objectdetailedlistword'] : '';
        $parameters['objectsendquoteword'] = isset($_POST['objectsendquoteword']) ? $_POST['objectsendquoteword'] : '';
        $parameters['objectscctotalpricefloat'] = isset($_POST['objectscctotalpricefloat']) ? $_POST['objectscctotalpricefloat'] : '';
        $parameters['form_field_style'] = isset($_POST['form_field_style']) ? $_POST['form_field_style'] : 'style_1';
        $parameters['scc_cart_btn_action'] = isset($_POST['scc_cart_btn_action']) ? $_POST['scc_cart_btn_action'] : 'open_checkout';
        // more settings options ends

        // currency style starts
        $parameters['currency_style'] = isset($_POST['currency_style']) ? $_POST['currency_style'] : '';
        // currency style ends
        //paypal starts
        $parameters['paypal_checked'] = isset($_POST['paypal_checked']) ? $_POST['paypal_checked'] : '';
        $parameters['paypal_email'] = isset($_POST['paypal_email']) ? $_POST['paypal_email'] : '';
        $parameters['paypal_shopping_cart_name'] = isset($_POST['paypal_shopping_cart_name']) ? $_POST['paypal_shopping_cart_name'] : '';
        $parameters['paypal_currency'] = isset($_POST['paypal_currency']) ? $_POST['paypal_currency'] : '';
        $parameters['paypalSuccessURL'] = isset($_POST['paypalSuccessURL']) ? $_POST['paypalSuccessURL'] : '';
        $parameters['paypalCancelURL'] = isset($_POST['paypalCancelURL']) ? $_POST['paypalCancelURL'] : '';
        //paypal ends


        //wooCommerce starts
        $parameters['woocommerce_checked'] = isset($_POST['woocommerce_checked']) ? $_POST['woocommerce_checked'] : false;
       
        //wooCommerce ends

        //condition object starts
        $parameters['conditionObject'] = isset($_POST['conditionObject']) ? $_POST['conditionObject'] : false;
        // condition object ends

        //stripe starts
        $parameters['isStripeEnabled'] = isset($_POST['isStripeEnabled']) ? $_POST['isStripeEnabled'] : false;
        //stripe ends

        //pre checkput email quote starts
        $parameters['forceEmailQuote'] = isset($_POST['forceEmailQuote']) && $_POST['forceEmailQuote'] == 'true' ? true : false;
        //pre checkput email quote ends
        
        // hover effect starts
        $parameters['isPayBtnHoverEffectEnabled'] = isset($_POST['isPayBtnHoverEffectEnabled']) && $_POST['isPayBtnHoverEffectEnabled'] == 'false' ? false : true;
        // hover effect ends
        $parameters['userActionButtonStyle'] = isset($_POST['userActionButtonStyle']) ? (int) $_POST['userActionButtonStyle'] : 1;
        $parameters['formFieldsArray'] = isset($_POST['formFieldsArray']) ? json_encode(json_decode(stripslashes($_POST['formFieldsArray'])),JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES): array();
        $parameters['webhookSettings'] = isset($_POST['webhookSettings']) ? $_POST['webhookSettings'] : [];
        $parameters['sccMinimumTotal'] = isset($_POST['sccMinimumTotal']) ? $_POST['sccMinimumTotal'] : 0;
        $parameters['sccMinimumTotalAction'] = isset($_POST['sccMinimumTotalAction']) ? $_POST['sccMinimumTotalAction'] : 'show-notice';



        $parameters = json_encode($parameters);
        $like6 = $wpdb->esc_like($parameters);
        //$query = $wpdb->prepare( "UPDATE {$wpdb->prefix}scc_form_parameters SET parameters = %s WHERE form_id = %d LIMIT 1", like_escape($parameters), $_POST['adminsettingsid']);
        $query = $wpdb->prepare("UPDATE {$wpdb->prefix}scc_form_parameters SET parameters = %s WHERE form_id = %d LIMIT 1", $like6, $like5);
        $wpdb->query($query);

    }
    else
    {
        //$query = $wpdb->prepare( "INSERT INTO {$wpdb->prefix}scc_forms (id, formname, ajaxform, formstored,description) VALUES (NULL, %s, %s, %s, %s)", like_escape($_POST['fieldname']), like_escape($_POST['fieldform']), like_escape($_POST['fieldPreview']),$like4);
        // $query = $wpdb->prepare( "INSERT INTO {$wpdb->prefix}scc_forms (id, description, formname, ajaxform, formstored) VALUES (NULL, %s, %s, %s, %s)", $like1, $like2, $like3, $like4);

        $query = $wpdb->prepare("INSERT INTO {$wpdb->prefix}scc_forms (id, description, formname, ajaxform, formstored,formtranslate) VALUES (NULL, %s, %s, %s, %s, %s)", $like1, $like2, $like3, $like4, $link9);

        $wpdb->query($query);
        $last_id = $wpdb->insert_id;

        $parameters = array();
        $parameters['fontType'] = isset($_POST['fontType']) ? $_POST['fontType'] : '';
        $parameters['inheritFontType'] = isset($_POST['inheritFontType']) ? $_POST['inheritFontType'] : '';
        $parameters['colorPicker'] = isset($_POST['colorPicker']) ? $_POST['colorPicker'] : '';
        $parameters['servicepricefontsize'] = isset($_POST['servicepricefontsize']) ? $_POST['servicepricefontsize'] : '';

        $parameters['objectColorPicker'] = isset($_POST['objectColorPicker']) ? $_POST['objectColorPicker'] : '';
        $parameters['objectServicepricefontsize'] = isset($_POST['objectServicepricefontsize']) ? $_POST['objectServicepricefontsize'] : '';
        $parameters['titleFontType'] = isset($_POST['title_fontType']) ? $_POST['title_fontType'] : '';
        $parameters['titleColorPicker'] = isset($_POST['title_colorPicker']) ? $_POST['title_colorPicker'] : '';
        $parameters['titleServicepricefontsize'] = isset($_POST['title_servicepricefontsize']) ? $_POST['title_servicepricefontsize'] : '';

        // more settings options starts
        $parameters['objectsendquote'] = isset($_POST['objectsendquote']) ? $_POST['objectsendquote'] : '';
        $parameters['objectdetailedlist'] = isset($_POST['objectdetailedlist']) ? $_POST['objectdetailedlist'] : '';
        $parameters['objectsaveicon'] = isset($_POST['objectsaveicon']) ? $_POST['objectsaveicon'] : '';
        $parameters['objectscctax'] = isset($_POST['objectscctax']) ? $_POST['objectscctax'] : '';
        $parameters['objectscccoupon'] = isset($_POST['objectscccoupon']) ? $_POST['objectscccoupon'] : '';

        $parameters['objecttaxrate'] = isset($_POST['objecttaxrate']) ? $_POST['objecttaxrate'] : '';
        $parameters['objectscccurrencylabel'] = isset($_POST['objectscccurrencylabel']) ? $_POST['objectscccurrencylabel'] : '';
        $parameters['objectscctitlelabel'] = isset($_POST['objectscctitlelabel']) ? $_POST['objectscctitlelabel'] : '';
        $parameters['objectscctotalprice'] = isset($_POST['objectscctotalprice']) ? $_POST['objectscctotalprice'] : '';
        $parameters['objecttotalpricestyle'] = isset($_POST['objecttotalpricestyle']) ? $_POST['objecttotalpricestyle'] : '';
        $parameters['objecttotalword'] = isset($_POST['objecttotalword']) ? $_POST['objecttotalword'] : '';
        $parameters['objectdetailedlistword'] = isset($_POST['objectdetailedlistword']) ? $_POST['objectdetailedlistword'] : '';
        $parameters['objectsendquoteword'] = isset($_POST['objectsendquoteword']) ? $_POST['objectsendquoteword'] : '';
        $parameters['objectscctotalpricefloat'] = isset($_POST['objectscctotalpricefloat']) ? $_POST['objectscctotalpricefloat'] : '';
        $parameters['form_field_style'] = isset($_POST['form_field_style']) ? $_POST['form_field_style'] : 'style_1';
        // more settings options ends

        // currency style starts
        $parameters['currency_style'] = isset($_POST['currency_style']) ? $_POST['currency_style'] : '';
        // currency style ends

        //paypal starts
        $parameters['paypal_checked'] = isset($_POST['paypal_checked']) ? $_POST['paypal_checked'] : '';
        $parameters['paypal_email'] = isset($_POST['paypal_email']) ? $_POST['paypal_email'] : '';
        $parameters['paypal_shopping_cart_name'] = isset($_POST['paypal_shopping_cart_name']) ? $_POST['paypal_shopping_cart_name'] : '';
        $parameters['paypal_currency'] = isset($_POST['paypal_currency']) ? $_POST['paypal_currency'] : '';
        //paypal ends

        $parameters = json_encode($parameters);
        $like7 = $wpdb->esc_like($parameters);
        //$query = $wpdb->prepare( "INSERT INTO {$wpdb->prefix}scc_form_parameters (id, form_id, parameters) VALUES (NULL, %d, %s)", $last_id, like_escape($parameters));
        $query = $wpdb->prepare("INSERT INTO {$wpdb->prefix}scc_form_parameters (id, form_id, parameters) VALUES (NULL, %d, %s)", $last_id, $like7);
        $wpdb->query($query);
    }
    if (get_option('df-scc-save-count')) {
        $save_count = get_option('df-scc-save-count');
        update_option('df-scc-save-count', ( $save_count + 1 ));
    } else {
        update_option('df-scc-save-count', 0);
    }
    echo $last_id;
    die();
}
function new_mail_from($old)
{
    return get_option('scc_emailsender');;
}

function new_mail_from_name($old)
{
    return get_option('scc_sendername');
}

function custom_mails($args)
{
    $sender = get_option('scc_emailsender');
    $bcc_email = sanitize_email($sender);

    if (is_array($args['headers'])) {
        $args['headers'][] = 'Bcc: '.$bcc_email ;
    }
    else
    {
        $args['headers'] .= 'Bcc: '.$bcc_email."\r\n";
    }

    return $args;
}

/**
 * Send Email Quote
 */
function scc_SendEmail()
{

    $user = sanitize_text_field(stripslashes($_POST['user_to']));
    // dump($_FILES);

    if(!empty($_POST['payload'])) {
        if (!empty($_FILES)) {
            $files = array();
            foreach ($_FILES as $key => $value) {
                $name = basename($value["name"]);
                $tmp_name = $value['tmp_name'];
                $storedFile = wp_upload_dir()['path'].'/'.$name;
                if (move_uploaded_file($tmp_name, $storedFile)) array_push($files, $storedFile);;
            }
            // $file = $_FILES['file'];
            // $name = basename($file["name"]);
            // $tmp_name = $file['tmp_name'];
            // // file_put_contents('/tmp/yyy', file_get_contents($tmp_name));
            // $storedFile = wp_upload_dir()['path'].'/'.$name;
            // move_uploaded_file($tmp_name, $storedFile);
        }
    
        function generateRandomString($length = 10)
        {
            return substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length);
        }
        if (!isset($_POST['email_to'])) { echo "ERROR - its empty address"; return; 
        }
        $to = sanitize_text_field($_POST['email_to']);
        $user = sanitize_text_field(stripslashes($_POST['user_to']));
        $title = sanitize_text_field($_POST['title']);
        $title =sanitize_text_field(stripslashes($title));
        
        
      
      
      

        if (!isset($_POST['email_to'])) { echo "ERROR - its empty address"; return; 
        }
        $to = sanitize_text_field($_POST['email_to']);
        $user = sanitize_text_field($_POST['user_to']);
        $title = sanitize_text_field($_POST['title']);
        $title = stripslashes(sanitize_text_field($title));
        $phone = sanitize_text_field($_POST['phone']);
        $ipaddress = sanitize_text_field($_POST['ipaddress']);
        $browserInfo = sanitize_text_field($_POST['browserInfo']);
        $isMobile = isset($_POST['isMobile']) ? sanitize_text_field($_POST['isMobile']) : false;
        $captchaResponse = isset($_POST['captchaResponse']) ? $_POST['captchaResponse'] : false;
        $from =get_option('scc_sendername') ? get_option('scc_sendername'): get_option('admin_email');
        $message = get_option('scc_messageform');
        $isCaptchaEnabled = get_option('scc-captcha-enablement-status');
        $isUnitColumnDisabled = $_POST['disableUnitColumn'] == "true" ? true : false;


        if ($isCaptchaEnabled) {
            if ($captchaResponse) {
                $captchaResponse && $res = (array) scc_g_recaptcha_verify($captchaResponse);
            } else {
                wp_send_json(array(
                    "error" => 'no captcha response'
                ));
                return;
            }
            if (isset($res['success']) && !$res['success'] && !$captchaResponse) {
                wp_send_json(array(
                    "error" => 'failed'
                ));
                return;
            }
        }

        $pdfObject = generatePdfFileAndGetPath($user, $_POST['payload'], $isUnitColumnDisabled);
        file_put_contents($pdfObject->path, base64_decode($pdfObject->file));

        if(preg_replace('/\s/', '', $message) == '' || empty($message)) {
            $body ="Hello ".$user.",\r\n\r\n";

            $body .="Here is the attached quote!";
            $body .="You can purchase Stylish Cost Calculator for your site today! This message is fully customizable.";

            $body .="Thank you, ";
            $body .="Designful INC.";
            $body .="Customer Details";
            $body .="<b>Customer Name:</b> " .$user;
            $body .="<b>Customer Email:</b> ".$to;
            $body .="<b>Phone Number:</b> ".$phone;
            $body .="<b>IP Address:</b> ".$ipaddress;
            $body .="<b>browserInfo:</b> ".$browserInfo;

        }else {
            $body=str_replace("<customer-name>", $user, $message);
            $body=str_replace("<customer-phone>", $phone, $body);
            $body=str_replace("<customer-email>", $to, $body);
            $body=str_replace("<customer-ip-address>", $ipaddress, $body);
            $body=str_replace("<customer-browser-info>", $browserInfo, $body);
            $body=str_replace("<device>", $isMobile == true ? 'Mobile' : 'Desktop', $body);
            $body=str_replace("<sender>", $from, $body);
        }
        add_filter('wp_mail_from', 'new_mail_from');
        add_filter('wp_mail_from_name', 'new_mail_from_name');
        add_filter('wp_mail', 'custom_mails', 10, 1);

        $title=str_replace("<customer-name>", $user, $title);
        $title=str_replace("<customer-phone>", $phone, $title);
        $title=str_replace("<customer-email>", $to, $title);
        $title=str_replace("<customer-ip-address>", $ipaddress, $title);
        $title=str_replace("<customer-browser-info>", $browserInfo, $title);
        $title=str_replace("<device>", $isMobile == true ? 'Mobile' : 'Desktop', $title);
        $title=str_replace("<sender>", $from, $title);

        $headers  = 'MIME-Version: 1.0' . "\r\n";
        $headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n";
        if(get_option('scc_email_send_copy') != "") {
            $headers .= 'Cc: Admin <'. get_option('scc_email_send_copy') .'>';
        }
        $subject = $title ;
        $body = stripslashes($body);
        $status = false;



        $default_subject = "Your Quote Request From ".get_bloginfo( 'url' );
        $email_subject = get_option('scc_emailsubject', $default_subject);
        $email_subject=str_replace("<customer-name>", $user, $email_subject);
        $email_subject=str_replace("<customer-phone>", $phone, $email_subject);
        $email_subject=str_replace("<customer-email>", $to, $email_subject);
        $email_subject=str_replace("<customer-ip-address>", $ipaddress, $email_subject);
        $email_subject=str_replace("<customer-browser-info>", $browserInfo, $email_subject);
        $email_subject=str_replace("<device>", $isMobile == true ? 'Mobile' : 'Desktop', $email_subject);
        $email_subject=str_replace("<sender>", $from, $email_subject);

        $callback = function ( $phpmailer ) use ( $pdfObject ) {
            $filename= date('Y-m-d H:i:s').'.pdf'; 
            $encoding = "base64"; 
            $type = "application/pdf";
            $phpmailer->AddStringAttachment(base64_decode($pdfObject->file), $filename, $encoding, $type);
        };
        if ( !file_exists($pdfObject->path) ) {
            add_action( 'phpmailer_init', $callback );
            // send email
            $status = wp_mail($to, /*$subject */ $email_subject, $body, $headers);
            wp_send_json(array(
                "success" => 'sent via string'
            ));
            wp_die();
        } else {
            if (isset($files)) {
                array_push($files, $pdfObject->path);
            } else {
                $files = array($pdfObject->path);
            }
            $status = wp_mail($to, /*$subject */ $email_subject, $body, $headers, $files);
            if ($status) {
                foreach ($files as $key => $file) {
                    unlink($file);
                }
                wp_send_json(array(
                    "success" => 'sent via file attachment'
                ));
            } else {
                wp_send_json(array(
                    "file" => 'sent via file attachment failed'
                ));
            }
            wp_die();
        }
    }
}

function scc_SendEmail_2 ($responseData, $title, $ipaddress, $browserInfo, $isMobile, $formFields)
{
    if (!empty($_FILES)) {
        $files = array();
        foreach ($_FILES as $key => $value) {
            $name = basename($value["name"]);
            $tmp_name = $value['tmp_name'];
            $storedFile = wp_upload_dir()['path'].'/'.$name;
            if (move_uploaded_file($tmp_name, $storedFile)) array_push($files, $storedFile);;
        }
    }

    // represent response data and form fields object to a key value format
    $tmpFormFields = [];
    foreach ($formFields as $key => $value) {
        $field_key = array_keys($value)[0];
        $field_value = array_values($value)[0];
        $tmpFormFields[$field_key] = $field_value;
    }
    $formFields = $tmpFormFields;
    $tmpResponseData = [];
    foreach ($responseData as $key => $value) {
        $res_key = $value[0];
        $res_value = $value[1];
        $tmpResponseData[$res_key] = $res_value;
    }
    $responseData = $tmpResponseData;
    $name = $responseData['name'];
    $email = $responseData['email'];
    $phone = isset($responseData['phone']) ? $responseData['phone'] : '';

    $customFields = array_diff(array_keys($responseData), array('name', 'email', 'phone', 'g-recaptcha-response'));

    $customFieldsString = '';
    foreach ($customFields as $key => $value) {
        $customFieldsString .= '<b>'.$formFields[$value]['name'].'</b> '.$responseData[$value].'<br/>';
    }
    

    if (!isset($email)) { echo "ERROR - its empty address"; return; 
    }
    $to = sanitize_text_field($email);
    $user = sanitize_text_field($name);
    $title = sanitize_text_field($title);
    $title = stripslashes(sanitize_text_field($title));
    $phone = sanitize_text_field($phone);
    $ipaddress = sanitize_text_field($ipaddress);
    $browserInfo = sanitize_text_field($browserInfo);
    $isMobile = isset($isMobile) ? sanitize_text_field($isMobile) : false;
    $captchaResponse = isset($_POST['captchaResponse']) ? $_POST['captchaResponse'] : false;
    $from =get_option('scc_sendername') ? get_option('scc_sendername'): get_option('admin_email');
    $message = get_option('scc_messageform');
    $isCaptchaEnabled = get_option('scc-captcha-enablement-status');


    if ($isCaptchaEnabled) {
        if ($captchaResponse) {
            $captchaResponse && $res = (array) scc_g_recaptcha_verify($captchaResponse);
        } else {
            return array(
                "error" => 'no captcha response'
            );
        }
        if (isset($res['success']) && !$res['success'] && !$captchaResponse) {
            return array(
                "error" => 'failed'
            );
        }
    }
    $isUnitColumnDisabled = isset($_POST['disableUnitColumn']) && $_POST['disableUnitColumn'] == "true" ? true : false;

    $pdfObject = generatePdfFileAndGetPath($user, $_POST['quote_data'],$isUnitColumnDisabled,true);
    file_put_contents($pdfObject->path, base64_decode($pdfObject->file));

    if(preg_replace('/\s/', '', $message) == '' || empty($message)) {
        $body ="Hello ".$user.",\r\n\r\n";

        $body .="Here is the attached quote!";
        $body .="You can purchase Stylish Cost Calculator for your site today! This message is fully customizable.";

        $body .="Thank you, ";
        $body .="Designful INC.";
        $body .="Customer Details";
        $body .="<b>Customer Name:</b> " .$user;
        $body .="<b>Customer Email:</b> ".$to;
        $body .="<b>Phone Number:</b> ".$phone;
        $body .=$customFieldsString;
        $body .="<b>IP Address:</b> ".$ipaddress;
        $body .="<b>browserInfo:</b> ".$browserInfo;

    }else {
        $body=str_replace("<customer-name>", $user, $message);
        $body=str_replace("<customer-phone>", $phone, $body);
        $body=str_replace("<customer-email>", $to, $body);
        $body .=$customFieldsString;
        $body=str_replace("<customer-ip-address>", $ipaddress, $body);
        $body=str_replace("<customer-browser-info>", $browserInfo, $body);
        $body=str_replace("<device>", $isMobile == true ? 'Mobile' : 'Desktop', $body);
        $body=str_replace("<sender>", $from, $body);
    }
    add_filter('wp_mail_from', 'new_mail_from');
    add_filter('wp_mail_from_name', 'new_mail_from_name');
    add_filter('wp_mail', 'custom_mails', 10, 1);

    $title=str_replace("<customer-name>", $user, $title);
    $title=str_replace("<customer-phone>", $phone, $title);
    $title=str_replace("<customer-email>", $to, $title);
    $title=str_replace("<customer-ip-address>", $ipaddress, $title);
    $title=str_replace("<customer-browser-info>", $browserInfo, $title);
    $title=str_replace("<device>", $isMobile == true ? 'Mobile' : 'Desktop', $title);
    $title=str_replace("<sender>", $from, $title);

    $headers  = 'MIME-Version: 1.0' . "\r\n";
    $headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n";
    if(get_option('scc_email_send_copy') != "") {
        $headers .= 'Cc: Admin <'. get_option('scc_email_send_copy') .'>';
    }
    $subject = $title ;
    $body = stripslashes($body);
    $status = false;



    $email_subject = get_option('scc_emailsubject');
    $email_subject=str_replace("<customer-name>", $user, $email_subject);
    $email_subject=str_replace("<customer-phone>", $phone, $email_subject);
    $email_subject=str_replace("<customer-email>", $to, $email_subject);
    $email_subject=str_replace("<customer-ip-address>", $ipaddress, $email_subject);
    $email_subject=str_replace("<customer-browser-info>", $browserInfo, $email_subject);
    $email_subject=str_replace("<device>", $isMobile == true ? 'Mobile' : 'Desktop', $email_subject);
    $email_subject=str_replace("<sender>", $from, $email_subject);

    $callback = function ( $phpmailer ) use ( $pdfObject ) {
        $filename= date('Y-m-d H:i:s').'.pdf'; 
        $encoding = "base64"; 
        $type = "application/pdf";
        $phpmailer->AddStringAttachment(base64_decode($pdfObject->file), $filename, $encoding, $type);
    };
    if ( !file_exists($pdfObject->path) ) {
        add_action( 'phpmailer_init', $callback );
        // send email
        $status = wp_mail($to, /*$subject */ $email_subject, $body, $headers);
        return array(
            "success" => 'sent via string'
        );
    } else {
        if (isset($files)) {
            array_push($files, $pdfObject->path);
        } else {
            $files = array($pdfObject->path);
        }
        $status = wp_mail($to, /*$subject */ $email_subject, $body, $headers, $files);
        if ($status) {
            foreach ($files as $key => $file) {
                unlink($file);
            }
            return array(
                "success" => 'sent via file attachment'
            );
        } else {
            return array(
                "error" => 'sent via file attachment failed'
            );
        }
    }
}
function scc_SavePDF()
{
    return "true";
}

function scc_SendPDF()
{
    $rawPayload = ($_POST['payload']);
    $isUnitColumnDisabled = $_POST['disableUnitColumn'] == "true" ? true : false;
    echo generatePdfFileAndGetPath(null, $rawPayload, $isUnitColumnDisabled)->file;
    wp_die();
}

function wpo_wcpdf_dompdf_options_custom($options)
{
    $options['isHtml5ParserEnabled'] = true;
    return $options;
}

function pdf_create($html, $filename, $stream=true, $papersize = 'letter', $orientation = 'portrait')
{
    include_once "dompdf/dompdf_config.inc.php";

    $dompdf = new DOMPDF();
    $dompdf->load_html($html);
    $dompdf->set_paper($papersize, $orientation);
    $dompdf->render();

    if ($stream) {
        $options['Attachment'] = 1;
        $options['Accept-Ranges'] = 0;
        $options['compress'] = 1;
        $dompdf->stream($filename.".pdf", $options);
    }
    else
    {
        write_file("$filename.pdf", $dompdf->output());
    }
}

/**
 * Generate PDF file to send email quote
 */
function generatePdfFileAndGetPath( $receiverName, $payload, $isUnitColumnDisabled = false, $isPayloadWithReferer = false )
{
    include_once __DIR__ . '/lib/tcpdf/tcpdf.php';
    $payload =  base64_decode($payload);
    if ($isPayloadWithReferer) {
        $payload = json_decode($payload)->pdf;   
    } else {
        $payload = json_decode($payload);
    }
    // create new PDF document
    $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

    // set document information
    $pdf->SetCreator('Stylish Cost Calculator');
    $pdf->SetAuthor('Stylish Cost Calculator');
    $pdf->setPrintHeader(false);
    if($receiverName) {
        $pdf->SetTitle('Email Quote File');
        $pdf->SetSubject('Email quote file for ' . $receiverName);
    }
    $sscPDFfont = get_option('sccPDFFont') == "regular" ? "dejavusans" : get_option('sccPDFFont');
    $pdf->AddFont('light');
    $pdf->AddFont('dejavusans');   
    $pdf->AddFont('cid0jp');
    $pdf->AddPage('P', 'A4');
    $total = null;
    $emptyString = '&nbsp;';
    $banner_image = get_option('scc_email_banner_image', false);
    $logo_image = get_option('scc_email_logo_image', false);
    // map links to filesystem paths
    $banner_image && $banner_image = str_replace(wp_get_upload_dir()['baseurl'],wp_get_upload_dir()['basedir'],$banner_image);
    $logo_image && $logo_image = str_replace(wp_get_upload_dir()['baseurl'],wp_get_upload_dir()['basedir'],$logo_image);

    /* detecting if image exist on the filesystem and loading from URL if not found */
    if (file_exists($logo_image)) {
        $logo_image = base64_encode(file_get_contents($logo_image));
    } else {
        $logo_image = get_option('scc_email_logo_image', false);
        $response = wp_remote_get($logo_image);
        if (is_wp_error($response) || $response['response']['code'] !== 200 ) {
            $logo_image = null;
        }
        if ( !is_wp_error($response) && $response['response']['code'] == 200 ) {
            $logo_image = base64_encode($response['body']);
        }
    }
    if (file_exists($banner_image)) {
        $banner_image = base64_encode(file_get_contents($banner_image));
    } else {
        $banner_image = get_option('scc_email_banner_image', false);
        $response = wp_remote_get($banner_image);
        if (is_wp_error($response) || $response['response']['code'] !== 200 ) {
            $banner_image = null;
        }
        if ( !is_wp_error($response) && $response['response']['code'] == 200 ) {
            $banner_image = base64_encode($response['body']);
        }
    }

    

    if(!$sscPDFfont) {
        if(get_option('scc_currency') == 'CNY' || get_option('scc_currency') == 'HKD' || get_option('scc_currency') == 'INR' || 
            get_option('scc_currency') == 'JPY' || get_option('scc_currency') == 'BDT' || get_option('scc_currency') == 'RUB' || 
            get_option('scc_currency') == 'KRW' || get_option('scc_currency') == 'TWD' || get_option('scc_currency') == 'VND' ) {
                $sscPDFfont = 'cid0jp';
            }else {
                $sscPDFfont = 'dejavusans';
            }
    }

    if ($isUnitColumnDisabled) {
        $payload->unit = $emptyString;
    }
  
    $data = <<<EOD
<style>
body {
  font-family: {$sscPDFfont} ;
}
  table {
    border:  border: 0px solid white;
  }
  .header {
    background-color: #f1f1f1;
    
  }
  th {
    font-family: {$sscPDFfont};
    font-size: 13px;
    font-weight: 100;
    margin-top: 15px;
    margin-bottom: 15px;
    padding: 10px;
  }
</style>
<body>
EOD;
    if($banner_image) {
        $data.=<<<EOD
    <div style="width:100%;vertical-align: middle; text-align:center;">
   
      <img style="height:100px"  src="@{$banner_image}">
      
    </div>
EOD;
    }
    if($logo_image) {
        $data.=<<<EOD
    <div style="width:100%;vertical-align: middle; text-align:center;">
      <img style="width: 200px;" src="@{$logo_image}">
    </div>
EOD;
    }
    $data.=<<<EOD
<div style="text-align:right">{$payload->date}</div>
<h2 align="center" style="margin-top:10px;font-size:14pt;">{$payload->pdf_title}</h2>
 <table cellpadding="2">
    <thead>
      <tr class="header">

          <th style="text-align:left;font-family: {$sscPDFfont}" colspan="3" >{$payload->description}</th>
          <th style="text-align:right">{$payload->quantity}</th>
          <th style="text-align:right">{$payload->unit}</th>
          <th style="text-align:right">{$payload->price}</th>

      </tr>
    </thead>
    <tbody>
EOD;
    foreach($payload->rows as $row){
        if ($isUnitColumnDisabled) {
            if (isset($row->attr) && isset($row->attr->unit_price)) $row->attr->unit_price = $emptyString;
        }
      
        if(isset($row->type) && $row->type == "element") {
            $data.=<<<EOD
    <tr>
      <td style="text-align:left" colspan="3">{$row->attr->name}</td>
      <td style="text-align:right">{$row->attr->unit}</td>
      <td style="text-align:right">{$row->attr->unit_price}</td>
      <td style="text-align:right">{$row->attr->total_price}</td>
    </tr>
EOD;
        }elseif($row->type == "element_dropdown") {
            $data.=<<<EOD
    <tr>
      <td style="text-align:left" colspan="3">{$row->attr->name}<br/><span style="color:##f1f1f1">{$row->attr->description}</span></td>
      <td style="text-align:right">{$row->attr->unit}</td>
      <td style="text-align:right">{$row->attr->unit_price}</td>
      <td style="text-align:right">{$row->attr->total_price}</td>
    </tr>
EOD;
        }elseif($row->type == "comment"){
            $data.=<<<EOD
        <tr>
          <td style="text-align:left" colspan="3">{$row->attr->title}</td>
          <td style="text-align:left" colspan="3">{$row->attr->comment}</td>
        </tr>
EOD;
         }elseif($row->type == "section_title") {
            $data.=<<<EOD
    <tr>
      <td style="padding-bottom:5px;font-size:14pt;text-align:left;font-family: {$sscPDFfont}" colspan="6"><b><br/>{$row->section_title}</b></td>
    </tr>
EOD;
        } elseif($row->type == "custom_math" && $row->attr->show_detailed_list == "true") {
            $data.=<<<EOD
    <tr>
      <td  style="text-align:left" colspan="5">{$row->attr->name}</td>
      <td  style="text-align:right">{$row->attr->type} {$row->attr->value_with_currency}</td>
      
    </tr>
EOD;
        }

       

    }


    $data.=<<<EOD
  </tbody>
</table>
<table cellpadding="2">
    <tr>
        <td></td>
    </tr>
</table>
<table cellpadding="2">
EOD;
    foreach($payload->rows as $row) {
       if($row->type == "coupon") {
            $data.=<<<EOD
    <tr>
      <td style="text-align:right;font-family: {$sscPDFfont};" colspan="4"><b>{$row->attr->title}</b></td>
      <td style="text-align:right;font-family: {$sscPDFfont};" colspan="2"><b>{$row->attr->discount_price}</b></td>
      <br>
    </tr>
EOD;
        } elseif($row->type == "subtotal_tax") {
            $data.=<<<EOD
    <tr>
      
      <td style="text-align:right" colspan="4">{$row->attr->title}</td>
      <td style="text-align:right" colspan="2">{$row->attr->price}</td>
    </tr>
EOD;
        }
        elseif($row->type == "tax") {
            $data.=<<<EOD
    <tr>
      
      <td style="text-align:right" colspan="4">{$row->attr->title} {$row->attr->title_second_part}</td>
      <td style="text-align:right" colspan="2">{$row->attr->price}</td>
    </tr>
EOD;
        }elseif($row->type == "total") {
            if (!strpos($row->attr->price, '<')) {
                $total = $row->attr->price;
                $conv = '';
            } else {
                $total = substr($row->attr->price, 0, strpos($row->attr->price, '<'));
                $conv = substr($row->attr->price, strpos($row->attr->price, '<'));
            }
            $data.=<<<EOD
    <tr>
      
      <td style="text-align:right" colspan="4"><b>{$row->attr->title}</b></td>
      <td style="text-align:right" colspan="2"><b>{$total}<br/>{$conv}</b></td>
    </tr>
EOD;
        } 
    }
    $data.=<<<EOD
</table >
<div>
    <p style="margin-top:20px; text-align:center; font-size:10pt;">{$payload->footer}</p>
</div>
</body>
EOD;

    $pdf->writeHTML($data);

    $uploadDir = wp_upload_dir();
    $filePath = $uploadDir['path'] . '/'.date('Y-m-d H-i-s').'.pdf';

  
    $pdfStr = $pdf->Output($filePath, 'S');
  
    $res = base64_encode($pdfStr);

    $pdfObject = new stdClass();
    $pdfObject->file = $res;
    $pdfObject->path = $filePath;

    return $pdfObject;
}

function scc_AddWooCommerce()
{
 
    $payload =  json_decode(base64_decode($_POST['payload']));

    do_action('woocommerce_init');
    WC()->cart->empty_cart();
  
  

    foreach($payload->rows as $row){
      
        if(($row->type == "element" ||  $row->type == "element_dropdown") 
            && isset($row->attr->woo_commerce->product_id)
            && (int)$row->attr->woo_commerce->product_id > 0
        ) {
        
              WC()->cart->add_to_cart($row->attr->woo_commerce->product_id, (int)$row->attr->woo_commerce->quantity);

        }
    }
    $cartAddaction = isset($_POST['cartAddAction']) ? $_POST['cartAddAction'] : 'open_checkout';
    $redirectUrl = $cartAddaction == "open_checkout" ? wc_get_checkout_url() : wc_get_cart_url();
    echo $redirectUrl;
    wp_die();
    // return true;
  
}

function scc_g_recaptcha_verify($token) {
    $secretKey = get_option('scc-recaptcha-secret-key');
    $args = array(
        'secret' => $secretKey,
        'response' => $token
    );
    
    $status = wp_remote_post( 'https://www.google.com/recaptcha/api/siteverify', array('body' => $args) );
    if (isset($status['body'])) {
        return json_decode($status['body']);
    }
    return 0;
}

function sccSaveRecaptchaKeys() {
    $data = $_POST['recaptchakeys'];
    $processed = json_decode(stripslashes($data), true);
    $isCaptchaEnabled = in_array(array("name" => 'captcha-enablement-status', "value" => "on"), $processed);
    if ($isCaptchaEnabled) {
        update_option('scc-captcha-enablement-status', true);
    } else {
        update_option('scc-captcha-enablement-status', false);
    }
    foreach ($processed as $key => $value) {
        if ($value['name' === 'captcha-enablement-status']) {
            update_option('scc-captcha-enablement-status', $value['value']);
        }
        if ($value['name'] === "site-key-recaptcha") {
            update_option('scc-recaptcha-site-key', $value['value']);
        }
        if ($value['name'] === "secret-key-recaptcha") {
            update_option('scc-recaptcha-secret-key', $value['value']);
        }
    }
    wp_send_json(
        array(
            "result" => "success"
        )
    );
}

    /**
    * Sets feedback modal invokation to compare against 'spl_save_count' option
    *
    * @return integer
    */
    function scc_feedback_invokation($args) {
      $save_count = get_option('scc-save-count');
      $current_invokation = get_option('scc_feedback_invoke');
      $invoke_at = 0;
      switch ($args) {
          case 'skip':
              $invoke_at = $save_count + 5;
              update_option('scc_feedback_invoke', $invoke_at);
              break;
          case 'yes':
              update_option('scc_feedback_invoke', 'disabled');
              break;
          case 'no':
              update_option('scc_feedback_invoke', 'disabled');
              break;
          default:
              if($current_invokation && $current_invokation != 'disabled') {
                  $invoke_at = $current_invokation;
              } else if ($current_invokation == 'disabled') {
                  $invoke_at = 0;
              } else {
                  $invoke_at = 9;
              };
              break;
      }
      return (int) $invoke_at;
  }

function sccFeedbackManage() {
  $args = isset($_POST['btn-type']) ? $_POST['btn-type'] : false;
        $data = null;
        if ($args) {
            $data = scc_feedback_invokation($args);
        }
        wp_send_json(
            array(
                'ok' => $data
            )
        );
}

function sccSetStripeKey() {
    $opts_store = array();

    $arr_inputs = array('privKey', 'pubKey');

    foreach( $_POST['data'] as $key => $value ) {
        if( in_array( $key, $arr_inputs) )
            $opts_store[$key] = $value;
    }
    
    // dump(wp_parse_args(get_option('scc_stripe_keys'), array('privKey' => null, 'pubKey' => null)));
    $status = update_option('scc_stripe_keys', $opts_store);
    if ($status) {
        wp_send_json(
            array(
                'ok' => 'ok'
            )
        );
    }
}

function sccCalculatorDuplication($a) {
    // TODO take the ID and copy it from the database, process it to a new entry and rename the name 
    $calculatorId = $_POST['id'];
    global $wpdb;
    // get table data from wp_scc_forms
    $formData = $wpdb->get_results($wpdb->prepare("SELECT id, formname,description,formstored,formtranslate  FROM {$wpdb->prefix}scc_forms where id = %d", array($calculatorId)))[0];
    $formData->formname = $formData->formname.' (Copy)';
    // create duplicate row and get the primary key
    $a = $wpdb->insert($wpdb->prefix.'scc_forms', array('formname' => $formData->formname, 'description' => $formData->description, 'ajaxform' => '' , 'formstored' => $formData->formstored, 'formtranslate' => $formData->formtranslate));
    if($a) {
        // get parameters from form_parameters and duplicate it with form id similar to primary key in the previous query
        $b = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}scc_form_parameters where form_id = %d ", array($calculatorId)))[0];
        $wpdb->insert($wpdb->prefix.'scc_form_parameters', array('form_id' => $wpdb->insert_id, 'parameters' => $b->parameters));
        wp_send_json(array(
            'ok' => 'ok'
        ));
        return;
    }
    wp_send_json(array(
        'oops' => 'oops'
    ));
}
function processSCCQuoteSubmission() {
    global $wpdb;
    $responseData = json_decode(stripslashes($_POST['data']));
    $quoteData = base64_decode($_POST['quote_data']);
    $quoteData = json_decode(stripslashes($quoteData)) ? json_decode(stripslashes($quoteData)) : json_decode($quoteData);
    $calculatorId = $_POST['calcId'];
    $processedData = array(
        'calc_id' => $calculatorId,
        'status' => '', 
        'type' => '' , 
        'opened' => false,
        'starred' => false,
        'submit_fields' => wp_json_encode($responseData),
        'quote_data' => wp_json_encode($quoteData),
        'user_ip' => $_SERVER [ 'REMOTE_ADDR' ],
        'browser_ua' => $_SERVER [ 'HTTP_USER_AGENT' ]
    );
    $rawFormFields = stripslashes_deep($wpdb->get_results("SELECT parameters FROM {$wpdb->prefix}scc_form_parameters WHERE {$wpdb->prefix}scc_form_parameters.form_id={$calculatorId};")[0]->parameters);
	$rawFormFields = json_decode($rawFormFields);
    $formFields = json_decode('[{"name":{"name":"Your Name","description":"Type in your name","type":"text","isMandatory":null,"trnKey":"Your Name","deletable":false}},{"email":{"name":"Your Email","description":"Type in your email","type":"email","isMandatory":null,"trnKey":"Your Email","deletable":false}},{"phone":{"name":"Your Phone","description":"phone","type":"phone","isMandatory":null,"trnKey":"Your Phone (Optional)","deletable":false}}]', true);
    if(isset($rawFormFields->formFieldsArray) && count(json_decode($rawFormFields->formFieldsArray))) {
		$formFields = json_decode($rawFormFields->formFieldsArray, true);
    }
    $response = scc_SendEmail_2($responseData , $quoteData->pdf->pdf_title, $processedData['user_ip'],$processedData['browser_ua'], false, $formFields);
    $status = $wpdb->insert($wpdb->prefix.'scc_quote_submissions', $processedData);
    if ($status && !isset($response['error'])) {
        wp_send_json(array(
            'ok' => 'submit successful'
        ));
    }
    if (isset($response['error'])) {
        wp_send_json(array(
            'error' => $response['error']
        ));
    }
}

function preGeneratedQuoteDownload() {
    global $wpdb;
    $quoteId = $_POST['data']['quoteId'];
    $calculatorId = $_POST['data']['calculatorId'];
    $quote = $wpdb->get_results("SELECT quote_data FROM {$wpdb->prefix}scc_quote_submissions WHERE {$wpdb->prefix}scc_quote_submissions.calc_id={$calculatorId} AND {$wpdb->prefix}scc_quote_submissions.id={$quoteId};")[0];
    $quoteObjectHasReferer = isset(json_decode($quote->quote_data, true)['referer']) ? true : false;
    $base64EncodedData = base64_encode($quote->quote_data);
    $b64PDF =  generatePdfFileAndGetPath(null, $base64EncodedData, false,  $quoteObjectHasReferer)->file;
    wp_send_json(
        array(
            "data" => $b64PDF
        )
    );
}


function sccDeleteAll() {
    global $wpdb;
    $wpdb->query("TRUNCATE TABLE `{$wpdb->prefix}scc_forms`");
    $wpdb->query("TRUNCATE TABLE `{$wpdb->prefix}scc_form_parameters`");
    $wpdb->query("TRUNCATE TABLE `{$wpdb->prefix}scc_coupons`");
    $wpdb->query("TRUNCATE TABLE `{$wpdb->prefix}scc_quote_submissions`");
    $wpdb->query("TRUNCATE TABLE `{$wpdb->prefix}scc_shortcodes`");
    
    wp_send_json(array(
        "ok" => "ok"
    ));
}

function sccManageDropdownLogo()
{
    $imageLink = $_POST['data'];
    $imagePathInFs = str_replace(wp_get_upload_dir()['baseurl'],wp_get_upload_dir()['basedir'],$imageLink);
    $method = isset($_POST['method']) ? $_POST['method'] : false;
    
    $image = wp_get_image_editor( $imagePathInFs );
    if (!is_wp_error($image) && !$method) {
        // do resize operation
        $imgFileName = basename($imagePathInFs);
        $imgFileName = str_replace('-150x150', '', $imgFileName);
        $iconSaveDir = wp_get_upload_dir()['basedir'].'/scc-icons';
        $image->resize( 56, 56, true );
        // save the resized image
        $finalPath = $image->save( $iconSaveDir.'/'.$imgFileName );
        wp_send_json(array(
            "link" => wp_get_upload_dir()['baseurl'].'/scc-icons/'.$finalPath['file']
        ));
    }
    if ($method && $method == 'delete') {
        unlink($imagePathInFs);
        wp_send_json(array(
            "link" => SCC_URL.'/assets/images/image.png'
        ));
    }
    if (is_wp_error($image)) {
        wp_send_json(['error' => 'an error encountered']);
    }
}

function sccDoWebhook()
{
    $eventType = $_POST['type'];
    $calcId = $_POST['calcId'];
    global $wpdb;
    $formParams = stripslashes_deep($wpdb->get_results("SELECT parameters FROM {$wpdb->prefix}scc_form_parameters WHERE {$wpdb->prefix}scc_form_parameters.form_id={$calcId};")[0]->parameters);
    $formParams = json_decode($formParams, 1);
    switch ($eventType) {
        case 'detailed_view':
            $webhookEndpoint = json_decode(stripslashes($formParams['webhookSettings']), true)[1]['scc_set_webhook_detail_view']['webhook'];
            $quoteItems = stripslashes($_POST['quoteItems']);
            $quoteItems = json_decode($quoteItems, true, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);

            $quoteItemsKV = array();
            for ($i=0; $i < count($quoteItems); $i++) {
                // resolve the name of the quote form keys, so the 'name' key represents "Your Name" value
                // $quoteFormResolvedKey = $quoteFormKV[$quoteData[$i][0]] ? $quoteFormKV[$quoteData[$i][0]] : $quoteFormData[$i][0];
				$quoteItemsKV+= $quoteItems[$i];
			};
            // add id address of the submitter
            $quoteItemsKV = array_merge($quoteItemsKV, array(
                "user_info" => array(
                    "ip_address" => $_SERVER['REMOTE_ADDR'],
                    "referring_url" => $_SERVER['HTTP_REFERER'],
                    "browser_info" => $_SERVER['HTTP_USER_AGENT']
                ),
                "generated_at" => gmdate('D, d M Y H:i:s', time())
            ));

            $headers = array(
                'user-agent' => 'SCC/' . md5( esc_url( home_url() ) ) . ';',
                'Accept'     => 'application/json',
                'Content-Type' => 'application/json'
            );
    
            $response = wp_remote_post( $webhookEndpoint, array(
                'method'      => 'POST',
                'timeout'     => 5,
                'redirection' => 5,
                'httpversion' => '1.0',
                'blocking'    => false,
                'headers'     => $headers,
                'body'        => json_encode($quoteItemsKV),
                'cookies'     => array()
            ) );
            wp_send_json_success(array("type" => $_POST['type']));
            break;
        case 'quote_send':
            $webhookEndpoint = json_decode(stripslashes($formParams['webhookSettings']), true)[0]['scc_set_webhook_quote']['webhook'];
            
            $quoteItems = json_decode(stripslashes($_POST['data']['quoteItems']), JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
            // $quoteData = array_merge($quoteData, array("user_ip" => $_SERVER['REMOTE_ADDR']));

            $emailQuoteForm = json_decode(stripslashes($_POST['data']['emailQuoteForm']));

            // here, the calculator ID's quote form parameters is fetched and the names are returned 
            include_once __DIR__ . '/admin/Functions/ParamParser.php';
            $paramParser = new SCC\Admin\Functions\ParamParser();
            $quoteFormKV = $paramParser->get_quote_form_keys($formParams);

            // converting mutlidimentional array to simple key value format
            $emailQuoteFormKV = array();
            for ($i=0; $i < count($emailQuoteForm); $i++) {
                // resolve the name of the quote form keys, so the 'name' key represents "Your Name" value
                $quoteFormResolvedKey = $quoteFormKV[$emailQuoteForm[$i][0]] ? $quoteFormKV[$emailQuoteForm[$i][0]] : $emailQuoteForm[$i][0];
				$emailQuoteFormKV+= array($quoteFormResolvedKey => $emailQuoteForm[$i][1]);
			};
            // adding user IP and the time to email quote variable
            $emailQuoteFormKV = array_merge($emailQuoteFormKV, array(
                "user_info" => array(
                    "ip_address" => $_SERVER['REMOTE_ADDR'],
                    "referring_url" => $_SERVER['HTTP_REFERER'],
                    "browser_info" => $_SERVER['HTTP_USER_AGENT']
                ),
                "generated_at" => gmdate('D, d M Y H:i:s', time())
            ));
            // converting mutlidimentional array to simple key value format
            $quoteItemsKV = array();
            for ($i=0; $i < count($quoteItems); $i++) {
                // resolve the name of the quote form keys, so the 'name' key represents "Your Name" value
                // $quoteFormResolvedKey = $quoteFormKV[$quoteData[$i][0]] ? $quoteFormKV[$quoteData[$i][0]] : $quoteFormData[$i][0];
				$quoteItemsKV+= $quoteItems[$i];
			};

            $headers = array(
                'user-agent' => 'SCC/' . md5( esc_url( home_url() ) ) . ';',
                'Accept'     => 'application/json',
                'Content-Type' => 'application/json'
            );
    
            $response = wp_remote_post( $webhookEndpoint, array(
                'method'      => 'POST',
                'timeout'     => 5,
                'redirection' => 5,
                'httpversion' => '1.0',
                'blocking'    => false,
                'headers'     => $headers,
                'body'        => json_encode(array("quote_items" => $quoteItemsKV,"email_quote_data" => $emailQuoteFormKV)),
                'cookies'     => array()
            ) );
            wp_send_json_success(array("type" => $_POST['type']));
            break;
        default:
            wp_send_json_error();
            break;
    }
    // if ($_POST['type'] == 'detailed_view') {
    //     wp_send_json_success(array("type" => $_POST['type']));
    // } else {
    //     wp_send_json_error();
    // }
}
