0% found this document useful (0 votes)
6 views34 pages

Code Changes

The document outlines a PHP class for managing HLM forms in a WordPress environment. It includes functionalities for displaying custom form data, filtering and exporting records, and handling AJAX submissions. The class also defines a shortcode for rendering forms and manages the display of entries in a user-friendly format with pagination and CSV export options.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views34 pages

Code Changes

The document outlines a PHP class for managing HLM forms in a WordPress environment. It includes functionalities for displaying custom form data, filtering and exporting records, and handling AJAX submissions. The class also defines a shortcode for rendering forms and manages the display of entries in a user-friendly format with pagination and CSV export options.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 34

<?

php

/**
* Displaying HLM Custom Form Data
*/
if (! defined('ABSPATH')) {
exit;
}

if (!class_exists('Displaying_HLM_TypeForms_Class')) {
class Displaying_HLM_TypeForms_Class
{
public function __construct(){

add_filter('manage_hlm_forms_posts_columns', array($this,
'add_hlm_forms_columnsCBF'));
add_action('manage_hlm_forms_posts_custom_column', array($this,
'add_hlm_forms_column_contentCBF'), 10, 2);
add_action('admin_menu',
array($this,'init_hlm_forms_entries_submenu_pageCBF'));
add_shortcode('hlm_typeform_wizard', array($this,
'hlm_typeform_wizard_shortcode'));
add_action('wp_enqueue_scripts', array($this,
'hlm_typeform_enqueue_scripts'));
add_action('wp_ajax_hlm_typeform_submit',
array($this,'handle_typeform_hlm_form_submission'));
add_action('wp_ajax_nopriv_hlm_typeform_submit',
array($this,'handle_typeform_hlm_form_submission'));
// Action for both filtering and exporting
add_action('admin_post_filter_or_export_records', array($this,
'handle_filter_or_export_records'));

}
function add_hlm_forms_columnsCBF($columns){
// Make a copy of the original columns array
$new_columns = array();

// Add the columns before the new 'Attorney' column


foreach ($columns as $key => $value) {
if ($key == 'date') {
$new_columns['hlm_forms_shortcode'] = __('Shortcode');
}
$new_columns[$key] = $value;
}

return $new_columns;
}
function add_hlm_forms_column_contentCBF($column, $hlm_cfposts_pid){
if ($column == 'hlm_forms_shortcode') {
echo '[hlm_typeform_wizard form_id="' . $hlm_cfposts_pid . '"]';
}
}
function init_hlm_forms_entries_submenu_pageCBF() {
add_submenu_page(
'edit.php?post_type=hlm_forms',
__('HLM Forms Entries', 'hlm-custom-mods'),
__('HLM Forms Entries', 'hlm-custom-mods'),
'manage_options',
'hlm_forms_entries',
array($this,'hlm_forms_entries_page_callback')
);
}
function hlm_forms_entries_page_callback() {
$startdate = '';
$todate = '';
$email_or_id = '';

// Start output buffering to capture any unintended output


ob_start();

// Check if export button was clicked


if (isset($_POST['export_csv']) && $_POST['export_csv'] == '1') {
// Verify nonce for security
if (!isset($_POST['records_hlmforms_noncefield']) || !
wp_verify_nonce($_POST['records_hlmforms_noncefield'],
'records_hlmforms_nonceaction')) {
wp_die('Security check failed');
}

// Get filter parameters


$startdate = !empty($_POST['start_date']) ?
sanitize_text_field($_POST['start_date']) : '';
$todate = !empty($_POST['end_date']) ?
sanitize_text_field($_POST['end_date']) . ' 23:59:59' : '';
$email_or_id = sanitize_text_field($_POST['email']);

global $wpdb;

// Start building the query


$query_main = "SELECT * FROM hlm_forms WHERE 1=1";

// Add conditions for non-empty variables


$where_conditions = [];
if (!empty($email_or_id)) {
if (is_numeric($email_or_id)) {
// If input is numeric, search by form_id
$where_conditions[] = $wpdb->prepare("hlm_forms.form_id =
%d", $email_or_id);
} else {
// If input is not numeric, search by email
$where_conditions[] = $wpdb->prepare("hlm_forms.email =
%s", $email_or_id);
}
}

// Date range between conditions


if (!empty($startdate) && !empty($todate)) {
$where_conditions[] = $wpdb->prepare("hlm_forms.created_at
BETWEEN %s AND %s", $startdate, $todate);
} elseif (!empty($startdate)) {
// If only start date is provided, filter from that date
onwards
$where_conditions[] = $wpdb->prepare("hlm_forms.created_at >=
%s", $startdate);
}

// Combine conditions if any are present


if (!empty($where_conditions)) {
$query_main .= " AND " . implode(" AND ", $where_conditions);
}

// Complete the query with ordering


$query_main .= " ORDER BY hlm_forms.id DESC";

// Log the query for debugging


error_log($query_main);

// Get results
$results = $wpdb->get_results($query_main);

// Prepare CSV data


$csv_data = [];

// Add CSV headers


$headers = ['Form ID', 'Email', 'Date'];
$csv_data[] = $headers;

// Add entry data


foreach ($results as $result) {
$row = [
$result->form_id,
$result->email,
$result->created_at
];
$csv_data[] = $row;
}

// Clear any previous output


ob_end_clean();
// Generate CSV filename
$date = date('Y-m-d-H-i-s');
$filename = "hlm-forms-export-{$date}.csv";

// Output headers to force download


header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="' . $filename .
'"');

// Create a file handle for PHP to output to


$output = fopen('php://output', 'w');

// Output each row of the CSV


foreach ($csv_data as $row) {
fputcsv($output, $row);
}

// Close the file handle


fclose($output);

// Stop further execution


exit();
} else {
if (isset($_POST['records_hlmforms_noncefield']) &&
wp_verify_nonce($_POST['records_hlmforms_noncefield'],
'records_hlmforms_nonceaction')) {
$startdate = !empty($_POST['start_date']) ?
sanitize_text_field($_POST['start_date']) : '';
$todate = !empty($_POST['end_date']) ?
sanitize_text_field($_POST['end_date']) . ' 23:59:59' : '';
$email_or_id = sanitize_text_field($_POST['email']);
} else {
$startdate = !empty($_GET['start_date']) ?
sanitize_text_field($_GET['start_date']) : '';
$todate = !empty($_GET['end_date']) ?
sanitize_text_field($_GET['end_date']) . ' 23:59:59' : '';
$email_or_id = isset($_GET['email']) ?
sanitize_text_field($_GET['email']) : '';
}
}

global $wpdb;
$page = isset($_GET['pagenumber']) ? intval($_GET['pagenumber']) : 1;
$per_page = 20;
$offset = ($page - 1) * $per_page;

// Start building the query


$query_main = "SELECT * FROM hlm_forms WHERE 1=1";

// Add conditions for non-empty variables


$where_conditions = [];
if (!empty($email_or_id)) {
if (is_numeric($email_or_id)) {
// If input is numeric, search by form_id
$where_conditions[] = $wpdb->prepare("hlm_forms.form_id = %d",
$email_or_id);
} else {
// If input is not numeric, search by email
$where_conditions[] = $wpdb->prepare("hlm_forms.email = %s",
$email_or_id);
}
}

// Date range between conditions


if (!empty($startdate) && !empty($todate)) {
$where_conditions[] = $wpdb->prepare("hlm_forms.created_at BETWEEN
%s AND %s", $startdate, $todate);
} elseif (!empty($startdate)) {
// If only start date is provided, filter from that date onwards
$where_conditions[] = $wpdb->prepare("hlm_forms.created_at >= %s",
$startdate);
}

// Combine conditions if any are present


if (!empty($where_conditions)) {
$query_main .= " AND " . implode(" AND ", $where_conditions);
}

// Query for total count


$total_query = $query_main;

// Complete the query


$limit_query_results = $query_main . "
ORDER BY hlm_forms.id DESC
LIMIT %d OFFSET %d
";
$limit_prepare = $wpdb->prepare($limit_query_results, $per_page,
$offset);
$limit_results = $wpdb->get_results($limit_prepare);
$total_results = $wpdb->get_results($total_query);

$total_count = count($total_results);
$total_pages = ceil($total_count / $per_page);

?>
<style>
.date-filters {
margin-bottom: 20px;
}
.date-filters > label {
margin-right: 20px;
}
.hlm-form-results-table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
}
.hlm-form-results-table th {
background-color: #0073aa;
color: white !important;
font-weight: bold;
border: 1px solid #ddd;
padding: 12px;
text-align: left;
}
.csv-export-form{
display:none;
}
.records_hlmforms_pagination a {
padding: 5px 10px;
margin: 0 2px;
text-decoration: none;
border: 1px solid #ddd;
border-radius: 3px;
background-color: #f5f5f5;
}

.records_hlmforms_pagination a.active {
background-color: #0073aa;
color: white;
}

.tablenav-pages {
display: flex;
align-items: center;
margin-top: 1em;
}

.displaying-num {
margin-right: 10px;
}

.pagination-links {
display: flex;
align-items: center;
}

.pagination-links a {
margin: 0 2px;
padding: 2px 5px;
text-decoration: none;
border: 1px solid #ddd;
background-color: #f9f9f9;
color: #0073aa;
border-radius: 3px;
}

.pagination-links a.disabled {
pointer-events: none;
opacity: 0.5;
}

.paging-input {
margin: 0 5px;
display: inline-flex;
align-items: center;
}

.paging-input input {
width: 40px;
text-align: center;
}

/* The Modal (background) */


.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
padding-top: 60px;
}

/* Modal Content/Box */
.modal-content {
background-color: #fefefe;
margin: 5% auto; /* 15% from the top and centered */
padding: 20px;
border: 1px solid #888;
width: 80%; /* Could be more or less, depending on screen size
*/
max-width: 600px;
box-shadow: 0 5px 15px rgba(0,0,0,.5);
border-radius: 4px;
}

/* The Close Button */


.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}

.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}

/* Entry block styling */


.entry_block {
margin-bottom: 20px; /* Add space between each question-answer
pair */
padding: 10px;
}

/* Styling for the question */


.entry_block > h4 {
font-size: 1.4em;
color: #333;
}

/* Styling for the answer */


.entry_block > div {
font-size: 1.3em;
color: #555;
}
</style>
<h1>HLM Forms Entries</h1>
<div id="detailsModal" class="modal">
<div class="modal-content">
<span class="close">&times;</span>
<div id="modalDetailsContent"></div>
</div>
</div>
<form name="records_hlmforms" method="post" action="<?php echo
admin_url('edit.php?post_type=hlm_forms&page=hlm_forms_entries')?>">
<!-- <form name="records_hlmforms" method="post" action="<?php // echo
admin_url('admin-post.php'); ?>"> -->
<div class="date-filters">
<label for="start-date">Start Date:
<input type="date" id="start-date" name="start_date"
value="<?php echo esc_attr($startdate) ?>"/>
</label>
<label for="end-date">End Date:
<input type="date" id="end-date" name="end_date" value="<?
php echo esc_attr($todate) ?>" />
</label>
<label for="email">Email or ID:
<input type="text" id="email" name="email" value="<?php
echo esc_attr($email_or_id); ?>" />
</label>
<button id="filtered_records_btn" class="button button-primary"
type="submit">Display Filtered Records</button>
<a id="export_csv_btn" class="button button-primary"
name="export_csv" value="1">Export CSV</a>
</div>
<input type="hidden" name="action" value="filter_or_export_records"
/>
<?php wp_nonce_field('records_hlmforms_nonceaction',
'records_hlmforms_noncefield'); ?>
</form>
<form name="records_hlmforms" method="post" action="<?php echo
admin_url('admin-post.php'); ?>" class="csv-export-form">
<div class="date-filters">
<label for="start-date">Start Date:
<input type="date" id="start-date-csv" name="start_date" value="<?php
echo esc_attr($startdate); ?>"/>
</label>
<label for="end-date">End Date:
<input type="date" id="end-date-csv" name="end_date" value="<?php echo
esc_attr($todate); ?>" />
</label>
<label for="email">Email or ID:
<input type="text" id="email-csv" name="email" value="<?php echo
esc_attr($email_or_id); ?>" />
</label>
<button id="export_csv_btn" class="button button-primary" type="submit"
name="export_csv" value="1">Export CSV</button>
</div>
<input type="hidden" name="action" value="filter_or_export_records" />
<?php wp_nonce_field('records_hlmforms_nonceaction',
'records_hlmforms_noncefield'); ?>
</form>
<div id="hlm-form-results">
<table class="hlm-form-results-table wp-list-table widefat fixed
striped table-view-list posts">
<thead>
<tr>
<th>Form ID</th>
<th>Email</th>
<th>View</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<?php
if (!empty($limit_results)) {

foreach ($limit_results as $result) {

$entry_html = '';
$entry_arr = $result->entry;

$form_id = $result->form_id;
$db_email = $result->email;
$created_at = $result->created_at;
$response = json_decode($entry_arr, true);

foreach ($response as $question => $answer) {


$question = str_replace('_', ' ', $question);
if (is_array($answer)) {
$answer = implode(', ', $answer);
}
$entry_html .= '<div class=entry_block><h4>' .
esc_html($question) . '</h4><div><strong>Answer:</strong> ' . esc_html($answer) .
'</div></div><hr />';
}
?>
<tr>
<td><?php echo esc_html($form_id); ?></td>
<td><?php echo esc_html($db_email); ?></td>
<td><a href="#" class="details-link" data-details="<?
php echo esc_attr($entry_html); ?>">Details</a></td>
<td><?php echo esc_html($created_at); ?></td>
</tr>
<?php
} // foreach ($limit_results
} // if (!empty($limit_results))
?>
</tbody>
</table>

<?php if ($total_pages > 1) { ?>


<div class="tablenav bottom">
<div class="alignleft actions bulkactions">
<!-- Bulk action buttons can go here -->
</div>
<div class="tablenav-pages">
<span class="displaying-num"><?php echo $total_count; ?
> items</span>
<span class="pagination-links">
<?php if ($page > 1) { ?>
<a class="first-page" href="<?php echo
admin_url('edit.php?
post_type=hlm_forms&page=hlm_forms_entries&pagenumber=1&start_date=' .
urlencode($startdate) . '&end_date=' . urlencode($todate) . '&email=' .
urlencode($email_or_id)); ?>">&laquo;</a>
<a class="prev-page" href="<?php echo
admin_url('edit.php?post_type=hlm_forms&page=hlm_forms_entries&pagenumber=' .
($page - 1) . '&start_date=' . urlencode($startdate) . '&end_date=' .
urlencode($todate) . '&email=' . urlencode($email_or_id)); ?>">&lsaquo;</a>
<?php } else { ?>
<span class="tablenav-pages-navspan">&laquo;</span>
<span
class="tablenav-pages-navspan">&lsaquo;</span>
<?php } ?>

<span class="paging-input">
&nbsp; <?php echo $page; ?> of &nbsp; <span
class="total-pages"><?php echo $total_pages; ?></span>
</span>

<?php if ($page < $total_pages) { ?>


<a class="next-page" href="<?php echo
admin_url('edit.php?post_type=hlm_forms&page=hlm_forms_entries&pagenumber=' .
($page + 1) . '&start_date=' . urlencode($startdate) . '&end_date=' .
urlencode($todate) . '&email=' . urlencode($email_or_id)); ?>">&rsaquo;</a>
<a class="last-page" href="<?php echo admin_url('edit.php?
post_type=hlm_forms&page=hlm_forms_entries&pagenumber=' . $total_pages .
'&start_date=' . urlencode($startdate) . '&end_date=' . urlencode($todate) .
'&email=' . urlencode($email_or_id)); ?>">&raquo;</a>

<?php } else { ?>


<span
class="tablenav-pages-navspan">&rsaquo;</span>
<span class="tablenav-pages-navspan">&raquo;</span>
<?php } ?>
</span>
</div>
<br class="clear">
</div>
<?php } ?>
</div>
<script>
jQuery(document).ready(function() {
var modal = jQuery('#detailsModal');
var modalContent = jQuery('#modalDetailsContent');
var closeModal = jQuery('.close');

// Add click event to all the links with class "details-link"


jQuery('.details-link').on('click', function(event) {
event.preventDefault();
modalContent.html(jQuery(this).data('details')); // Set
modal content
modal.show(); // Show modal
});

// When the user clicks on <span> (x), close the modal


closeModal.on('click', function() {
modal.hide();
});

// When the user clicks anywhere outside of the modal, close it


jQuery(window).on('click', function(event) {
if (jQuery(event.target).is(modal)) {
modal.hide();
}
});
jQuery('#start-date').on('change', function() {
var start_date = jQuery(this).val();
jQuery('#start-date-csv').val(start_date);
});
jQuery('#end-date').on('change', function() {
var end_date = jQuery(this).val();
jQuery('#end-date-csv').val(end_date);
});
jQuery('#email').on('change', function() {
var email_or_id = jQuery(this).val();
jQuery('#email-csv').val(email_or_id);
});

// Trigger CSV export form submission


jQuery('a#export_csv_btn').on('click', function(e) {
e.preventDefault();
jQuery('button#export_csv_btn').trigger('click');
});
});

</script>
<?php
// End output buffering and flush the contents for the admin page
ob_end_flush();
}
function get_input_name($question) {
$question = trim($question);
$question = strtolower($question);
$input_name = preg_replace('/[^a-z0-9]+/', '_', $question);

return $input_name;
}
function hlm_typeform_wizard_shortcode($atts){
$atts = shortcode_atts(array('form_id' => ''), $atts, 'hlm_forms');
$form_id = $atts['form_id'];
ob_start();
global $post;
$post_id = $post->ID;
$form_id = $form_id ? $form_id : $post_id;
$form_redirect_url = get_field('redirect_url', $form_id);
$counter = 1;
if (have_rows('questionnaire', $form_id)) {
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>
<?php echo get_the_title($form_id); ?>
</title>
</head>
<style>
body {
padding-bottom: 50px;
background: #EEEDEC;
}
/***additional_changes***/
.single-post .for-wizard-outer-container {
padding:0px;
}
.single-post label.hlm-typeform-question{
font-size:26px;
margin-bottom: 10px;
}

.single-post input#hlm-typeform-text {
font-size:22px;
}
.single-post .hlm-typeform-email-field{
font-size: 22px;
}
.single-post span.sign-sect{
margin-bottom: 0px;
margin-top: 25px;
font-size: 22px;
}
a.form-anchor-link {
font-size: 22px;
font-weight: 600;
text-decoration: underline;
}
.single-post .hlm-typeform-left-column {
padding: 25px 15px 25px 40px;
}
.single-post .form-radio-outer-sect, .single-post .form-
checkbox-outer-sect{
flex-wrap: nowrap;
font-size: 22px;
}
textarea{
font-size:22px;
}
.single-post .hlm-typeform-nextBtns, .single-post .hlm-
typeform-nextBtns:hover, .single-post .hlm-typeform-nextBtns:focus, .single-
post .hlm-typeform-nextBtns:active, .single-post .hlm-typeform-
nextBtns:visited, .single-post .hlm-typeform-nextBtns:link{
font-size: 24px;
font-weight: 600;
line-height: 100%;
margin: 25px 0 0;
width: 140.878px;
height: 50.437px;
}

.single-post span.required-text-sect {
font-size:18px;
}

.single-post .hlm-typeform-form-container {
min-height:700px
}
.single-post .form-radio-outer-sect, .form-checkbox-outer-sect{
font-size:26px;
}
/***additional_changes***/
.page-template-hlm-typeform .wpb-content-wrapper{
max-width: 100% !important;
}
.hlm-typeform-email-field{
display: block;
width: 100%;
font-family: inherit;
color: rgb(1, 66, 172);
/* padding-top: 35px !important; */
padding-bottom: var(--spacing-100);
border: none !important;
outline: none;
background-color: transparent !important;
font-size: 30px;
line-height: 30px;
-webkit-text-fill-color: rgb(1, 66, 172);
transition: box-shadow 0.1s ease-out;
box-shadow: rgba(1, 66, 172, 0.3) 0px 1px;
padding: 7px;
}

.hlm-typeform-text-field{
display: block;
width: 100%;
font-family: inherit;
color: rgb(1, 66, 172);
/* padding-top: 35px !important; */
padding-bottom: var(--spacing-100);
border: none !important;
outline: none;
background-color: transparent !important;
font-size: 30px;
line-height: 30px;
-webkit-text-fill-color: rgb(1, 66, 172);
transition: box-shadow 0.1s ease-out;
box-shadow: rgba(1, 66, 172, 0.3) 0px 1px;
}
.form-radio-outer-sect, .form-checkbox-outer-sect {
border-radius: 40px;
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: flex-start;
background: #E3ECF6;
padding: 7px;
width: 85%;
margin-bottom: 15px;
font-style: normal;
font-weight: 400;
font-size: 28px;
line-height: 135%;
color: #0E5FBA;
position:relative;
}
span.form-circle-sect {
width: 40px;
height: 40px;
border-radius: 50px;
background: #FFFFFF;
margin-right: 10px;
display: flex;
justify-content: center;
align-items: center;
font-weight: bold;
color: #0E5FBA;
}
.form-checkbox-outer-sect span.form-circle-sect{
color:#FFFFFF;
}
.hlm-typeform-left-column .form-checkbox-outer-sect .active-
check-sign {
color: #0E5FBA !important;
}
.hlm-typeform-left-column input[type="radio"], .hlm-typeform-
left-column input[type="checkbox"] {
width: 100%;
height: 100%;
position: absolute;
z-index: 9999999;
opacity: 0;
}
.active-answer-sect {
background: #0E5FBA;
color: #FFFFFF;
}
span.required-text-sect {
font-weight: 400;
font-size: 24px;
line-height: 135%;
color: #838383;
}

label.hlm-typeform-question {
font-weight: 750;
font-size: 38px;
line-height: 130%;
color: #000000;
margin-bottom: 40px;
width:100%;
}

span.sign-sect {
font-weight: 400;
font-size: 28px;
line-height: 135%;
letter-spacing: -0.01em;
color: #000000;
margin-bottom: 25px;
}
.for-wizard-outer-container {
padding: 35px 100px;
/* background: #EEEDEC; */
}
.form-logo-sect {
text-align: center;
margin-bottom: 35px;
}
.form-logo-sect img {
width: 250px;
object-fit: cover;
}
textarea {
background: #FFFFFF;
border: 1px solid #C1C1C1;
border-radius: 16px;
padding: 10px;
width: 100%;
font-size: 24px;
}
textarea::placeholder {

font-weight: 400;
font-size: 24px;
line-height: 135%;
/* or 38px */

color: #BABABA;
}
.hlm-typeform-right-column img{
display:none;
}
/* Basic styling */
body {
font-family: Arial, sans-serif;
padding: 20px;
background-color: #f5f5f5;
}

.hlm-typeform-wizard {
background-color: #FFFFFF;
border-radius: 40px;
margin: auto;
box-shadow: 0px 4px 25.7px rgba(156, 155, 151, 0.25);
overflow: hidden;
position:relative;

/* Fixed Progress Bar at the Bottom */


.hlm-typeform-progress-bar-wrapper {
position: fixed;
bottom: 0;
left: 0;
width: 100%;
height: 10px;
background-color: #ddd;
border-radius: 5px;
}

.hlm-typeform-progress-bar {
height: 10px;
background-color: #d92d27;
width: 0%;
}

/* Step Form Styling */


.hlm-typeform-form-container {
position: relative;
display: flex;
flex-direction: row;
min-height: 824px;
overflow: hidden;
}

.hlm-typeform-step {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 100%;
transition: all 0.5s ease;
opacity: 0;
display: flex;
}

.hlm-typeform-step.hlm-typeform-active {
left: 0;
opacity: 1;
}

.hlm-typeform-step.hlm-typeform-previous {
left: -100%;
}

.hlm-typeform-left-column {
width: 50%;
padding: 50px 30px 50px 80px;
display: flex;
align-items: center;
flex-wrap: wrap;
align-content: center;
/* margin-bottom: 150px; */
}

.hlm-typeform-right-column {
width: 50%;
display: flex;
justify-content: center;
align-items: center;
position:relative;
}

.hlm-typeform-right-column img {
max-width: 100%;
height: auto;
border-radius: 10px;
}

.hlm-typeform-btn {
background-color: transparent;
color: #da291c;
padding: 0px;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 40px;
font-weight: bold;
margin-right: 20px;
}

.hlm-typeform-btn[disabled] {
cursor: not-allowed;
opacity: 0.7;
}
.hlm-typeform-btn:hover, .hlm-typeform-btn:focus{
background-color: transparent;
color: #da291c;
}
.hlm-typeform-step-number {
margin-bottom: 10px;
font-weight: bold;
}

.hlm-typeform-error-message {
margin-top: 15px;
color: red;
font-size: 0.9em;
display: none;
margin-bottom: 20px;
}
input.hlm-typeform-error,
textarea.hlm-typeform-error {
border: 1px solid red;
}

#hlm-typeform-mobile-navigation {
width: 90%;
display: none;
justify-content: center;
align-items: center;
position: absolute;
bottom: 75px; /* 90px */
padding: 0 20px;
}

/* Media Query for Tablet and Mobile */


@media (max-width: 767px) {
.form-radio-outer-sect, .form-checkbox-outer-sect {
font-size: 26px !important;
}
span.required-text-sect{
display: none;
}
.form-logo-sect {
margin-bottom: 0;
position: absolute;
top: 20px;
left: 4px;
z-index: 1;
filter: brightness(0) invert(1);
}
.hlm-typeform-nextBtns{
margin:0 !important;
}
.hlm-typeform-wizard {
border-radius: 0;
min-height: 100vh;
}
.form-logo-sect img {
width: auto;
height: 42px;
}
.for-wizard-outer-container {
padding: 0;
}
.hlm-typeform-step {
flex-direction: column-reverse;
}
.hlm-typeform-left-column {
width: unset;
padding: 20px;
}
.hlm-typeform-right-column {
width: 100%;
height: 284px;
}
.hlm-typeform-progress-bar-wrapper {
top: 0;
}
label.hlm-typeform-question {
font-size: 21.5px;
font-style: normal;
font-weight: 750;
line-height: 130%;
}
#hlm-typeform-desktop-navigation,
#hlm-typeform-desktop-next-btn {
display: none;
}
#hlm-typeform-mobile-navigation {
display: flex;
}
.hlm-typeform-step{
height: unset;
}
.hlm-typeform-form-container {
min-height: 100vh;
overflow-y:scroll;
}
span.sign-sect {
font-size: 17px;
font-style: normal;
font-weight: 400;
line-height: 135%;
letter-spacing: -0.17px;
margin-bottom: 8;
}
.required-text-sect {
font-size: 14.5px;
font-style: normal;
font-weight: 400;
line-height: 135%;
}
.hlm-typeform-email-field,
.hlm-typeform-text-field {
font-size: 22px;
font-style: normal;
font-weight: 700;
line-height: 135%;
}
.form-radio-outer-sect, .form-checkbox-outer-sect {
width: 100%;
}
}

/* Media Query for Mobile: less than 430px */


@media (max-width: 420px) {
label.hlm-typeform-question {
font-size: 22px;
}
.hlm-typeform-email-field,
.hlm-typeform-text-field {
font-size: 22px;
}
.form-radio-outer-sect, .form-checkbox-outer-sect {
font-size: 20px !important;
}
.required-text-sect {
font-size: 18px;
}
span.sign-sect {
font-size: 18px;
}
}
/* Media Query for Mobile: less than 410px */
@media (max-width: 390px) {
label.hlm-typeform-question {
font-size: 18px;
}
.hlm-typeform-email-field,
.hlm-typeform-text-field {
font-size: 18px;
}
.form-radio-outer-sect, .form-checkbox-outer-sect {
font-size: 16px !important;
}
.required-text-sect {
font-size: 14px;
}
span.sign-sect {
font-size: 14px;
}
}

#hlm-typeform-loader-overlay {
display: flex;
justify-content: center;
align-items: center;
background-color: #000000;
opacity: 0.75;
width: 100%;
height: 100%;
position: fixed;
top: 0;
left: 0;
z-index: 999999;
color: #ffffff;
flex-direction: column;
font-size: 20px;
}

.hlm-typeform-loader-spinner {
width: 70px;
aspect-ratio: 1;
border-radius: 50%;
border: 8px solid #ffffff;
animation: l20-1 0.8s infinite linear alternate, l20-2 1.6s
infinite linear;
}
@keyframes l20-1{
0% {clip-path: polygon(50% 50%,0 0, 50% 0%, 50%
0%, 50% 0%, 50% 0%, 50% 0% )}
12.5% {clip-path: polygon(50% 50%,0 0, 50% 0%, 100%
0%, 100% 0%, 100% 0%, 100% 0% )}
25% {clip-path: polygon(50% 50%,0 0, 50% 0%, 100%
0%, 100% 100%, 100% 100%, 100% 100% )}
50% {clip-path: polygon(50% 50%,0 0, 50% 0%, 100%
0%, 100% 100%, 50% 100%, 0% 100% )}
62.5% {clip-path: polygon(50% 50%,100% 0, 100% 0%, 100%
0%, 100% 100%, 50% 100%, 0% 100% )}
75% {clip-path: polygon(50% 50%,100% 100%, 100% 100%, 100%
100%, 100% 100%, 50% 100%, 0% 100% )}
100% {clip-path: polygon(50% 50%,50% 100%, 50% 100%, 50%
100%, 50% 100%, 50% 100%, 0% 100% )}
}
@keyframes l20-2{
0% {transform:scaleY(1) rotate(0deg)}
49.99%{transform:scaleY(1) rotate(135deg)}
50% {transform:scaleY(-1) rotate(0deg)}
100% {transform:scaleY(-1) rotate(-135deg)}
}

</style>
<main>
<!-- Loader Overlay -->
<div id="hlm-typeform-loader-overlay" style="display: none;">
<div class="hlm-typeform-loader-spinner"></div>
<p>Please Wait...</p>

</div>
<!-- Form Wizard HTML -->
<div class="for-wizard-outer-container">
<div class="form-logo-sect">
<a href="/"><img decoding="async"
src="https://iheartdogs.com/wp-content/uploads/2023/08/iHeartDogsLogo-300px.png"
alt="iHeartDogs.com" class="wp-image-2706741"></a>
</div>
<div class="hlm-typeform-wizard">
<form method="post" class="hlm-typeform-form" id="hlm-
typeform-form" name="hlm-typeform-form" style="margin-block-end: 0;">
<?php wp_nonce_field('hlm_forms_quest_ans_nonceaction',
'hlm_forms_quest_ans_noncefield'); ?>
<input type="hidden" name="form_id_inputfield"
value="<?php echo esc_attr($form_id); ?>" />
<input type="hidden" name="form_id_redirect_url"
id="form_id_redirect_url" value="<?php echo esc_attr($form_redirect_url); ?>" />

<div class="hlm-typeform-form-container">
<?php
$letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G',
'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
'X', 'Y', 'Z'];
while (have_rows('questionnaire', $form_id ?
$form_id : $post_id)): the_row();
$index = 0;
$question_text = get_sub_field('question');
$image_url = get_sub_field('image');
$information_box =
strtolower(get_sub_field('information_box'));
?>
<div class="hlm-typeform-step <?php echo
get_row_index() == 1 ? 'hlm-typeform-active' : ''; ?>">
<div class="hlm-typeform-left-column" <?php
if(!$image_url){ ?> style="width:75%;margin:0 auto;padding: 0px;min-height:100vh"<?
php } ?>>
<?php if($information_box == 'no'){ ?>
<span class="required-text-sect">This
question is required.*</span>
<?php } ?>
<label class="hlm-typeform-question"><?
php echo esc_html($question_text); ?></label>
<?php if($information_box == 'no'){ ?>
<?php while (have_rows('options')):
the_row();
$label_text =
get_sub_field('label');
$option_type =
strtolower(get_sub_field('option_type'));
if ($option_type == 'email') { ?>
<span class="sign-sect">👇<?=
$label_text ?></span>
<input type="email" id="hlm-
typeform-email" class="hlm-typeform-email-field" style="margin-top: 12px;" name="<?
= $this->get_input_name($question_text) ?>" placeholder="[email protected]">
<?php } elseif ($option_type ==
'textarea') { ?>
<textarea id="hlm-typeform-
summary" class="form-control" style="margin-top: 12px;" rows="8" placeholder="<?=
$label_text ?>" name="<?= $this->get_input_name($question_text) ?>"></textarea>
<?php } elseif ($option_type ==
'radio') { ?>
<div class="form-radio-outer-
sect">
<input type="radio"
id="hlm-typeform-male" style="margin-top: 12px;" name="<?= $this-
>get_input_name($question_text) ?>" value="<?php echo $label_text; ?>">
<?php if
(isset($letters[$index])) {
echo '<span
class="form-circle-sect">' . $letters[$index] . '</span>';
$index++;
} ?>
<span class="form-radio-
label"><?php echo $label_text; ?></span>
</div>
<?php } elseif ($option_type ==
'checkbox') { ?>
<div class="form-checkbox-
outer-sect">
<input type="checkbox"
id="hlm-typeform-option1" style="margin-top: 12px;" name="<?= $this-
>get_input_name($question_text) ?>[]" value="<?php echo $label_text; ?>">
<span class="form-circle-
sect">&#x2714;</span>
<span class="form-checkbox-
label"><?php echo $label_text; ?></span>
</div>
<?php } elseif ($option_type ==
'text') { ?>
<input type="text" id="hlm-
typeform-text" class="hlm-typeform-text-field" style="margin-top: 12px;" name="<?=
$this->get_input_name($question_text) ?>" placeholder="<?= $label_text; ?>">
<?php } elseif ($option_type ==
'url'){
$url = get_sub_field('url');?>
<a href="<?php echo $url; ?>"
target="_blank" class="form-anchor-link"><?php echo $label_text; ?></a>
<?php }

endwhile; ?>
<?php } ?>

<div class="hlm-typeform-error-message"
id="hlm-typeform-errors">Sorry! Answer to this question is required.</div>

<div style="width: 100%;" id="hlm-


typeform-desktop-next-btn">
<?php if(get_row_index() <
count(get_field('questionnaire', $form_id))){ ?>
<button class="hlm-typeform-btn
hlm-typeform-nextBtns" id="hlm-typeform-nextBtn<?php echo $counter++;
?>">Next</button>
<?php }else{ ?>
<button type="submit"
class="hlm-typeform-btn hlm-typeform-nextBtns" id="hlm-typeform-
submitBtn">Submit</button>
<?php } ?>
</div>
</div>
<?php if($image_url){ ?>
<div class="hlm-typeform-right-column">
<img src="<?php echo
esc_url($image_url); ?>" alt="Email Step Image">
</div>
<?php } ?>

</div>
<?php endwhile; ?>
</div>
<!-- Navigation Buttons -->
<div style="position:absolute; bottom: 15px;
left:36px;" id="hlm-typeform-desktop-navigation">
<button class="hlm-typeform-btn hlm-typeform-
prevBtn" id="hlm-typeform-prevBtn" disabled>
<!-- &#10216; -->
<svg xmlns="http://www.w3.org/2000/svg"
width="20" height="33" viewBox="0 0 20 33" fill="none">
<path d="M20 28.5502L7.63318 16.1834L20
3.81659L16.1834 0L0 16.1834L16.1834 32.3668L20 28.5502Z" fill="currentColor"/>
</svg>
</button>
<button class="hlm-typeform-btn hlm-typeform-
nextBtn" id="hlm-typeform-nextBtn">
<!-- &#10217; -->
<svg xmlns="http://www.w3.org/2000/svg"
width="20" height="33" viewBox="0 0 20 33" fill="none">
<path opacity="1" d="M0 28.5502L12.3668
16.1834L0 3.81659L3.81659 0L20 16.1834L3.81659 32.3668L0 28.5502Z"
fill="currentColor"/>
</svg>
</button>
</div>
<div id="hlm-typeform-mobile-navigation">
<button class="hlm-typeform-btn hlm-typeform-
prevBtn" id="hlm-typeform-prevBtn" disabled>
<!-- &#10216; -->
<svg xmlns="http://www.w3.org/2000/svg"
width="20" height="33" viewBox="0 0 20 33" fill="none">
<path d="M20 28.5502L7.63318 16.1834L20
3.81659L16.1834 0L0 16.1834L16.1834 32.3668L20 28.5502Z" fill="currentColor"/>
</svg>
</button>
<button class="hlm-typeform-btn hlm-typeform-
nextBtns" style="width: inherit;" id="hlm-typeform-mobile-nextBtn">Next</button>
<button type="submit" class="hlm-typeform-btn hlm-
typeform-nextBtns" style="width: inherit; display: none;" id="hlm-typeform-mobile-
submitBtn">Submit</button>
</div>
</form>
</div>
</div>
<!-- Progress Bar at the Bottom -->
<div class="hlm-typeform-progress-bar-wrapper">
<div class="hlm-typeform-progress-bar" id="hlm-typeform-
progressBar"></div>
</div>
</main>
<?php } // End if (have_rows('questionnaire'))
?>
<script>
jQuery(document).ready(function($) {
jQuery('.hlm-typeform-right-column').each(function(index) {
var imgSrc = $(this).find('img').attr('src');
var className = 'hlm-typeform-right-column-' + index;

// Add a unique class to each element


$(this).addClass(className);

// Inject CSS for the ::after pseudo-element


var css = '.' + className + '::after {content: "";position:
absolute;background: url('+imgSrc+');left: 0;top: 0;width: 100%;height:
100%;background-position: center;background-size: cover;}';
jQuery('<style>')
.prop('type', 'text/css')
.html(css)
.appendTo('head');
});
jQuery('input[type="radio"]').on('click', function(){
jQuery(this).parents('.hlm-typeform-left-
column').find('.form-radio-outer-sect').removeClass('active-answer-sect');
jQuery(this).parent().addClass('active-answer-sect');
})
jQuery('input[type="checkbox"]').on('click', function(){
if(jQuery(this).parent().hasClass('active-answer-sect')){
jQuery(this).parent().removeClass('active-answer-
sect');
jQuery(this).siblings('.form-circle-
sect').removeClass('active-check-sign');
}else{
jQuery(this).parent().addClass('active-answer-sect');
jQuery(this).siblings('.form-circle-
sect').addClass('active-check-sign');
}
});
let currentStep = 0;
const steps = $('.hlm-typeform-step');
const progressBar = $('#hlm-typeform-progressBar');

// Function to move to the next/previous step


function hlmTypeformNextPrev(n) {
const currentInputs = $(steps[currentStep]).find('input,
textarea');

if (n === -1){
jQuery('.form-radio-outer-sect').removeClass('active-
answer-sect');
}

if (n === 1 && !hlmTypeformValidateForm(currentInputs))


return;

$(steps[currentStep]).removeClass('hlm-typeform-
active').addClass(n === 1 ? 'hlm-typeform-previous' : 'hlm-typeform-next');
currentStep += n;

setTimeout(() => {
$(steps[currentStep]).removeClass('hlm-typeform-
previous hlm-typeform-next').addClass('hlm-typeform-active');
}, 10);

hlmTypeformUpdateProgressBar();

if (currentStep === 0) {
$('.hlm-typeform-prevBtn').attr('disabled', true);
} else {
$('.hlm-typeform-prevBtn').attr('disabled', false);
}

if (currentStep === steps.length - 1) {


$('.hlm-typeform-nextBtn').attr('disabled', true);
$('#hlm-typeform-mobile-nextBtn').hide();
$('#hlm-typeform-mobile-submitBtn').show();
} else {
$('.hlm-typeform-nextBtn').attr('disabled', false);
$('#hlm-typeform-mobile-submitBtn').hide();
$('#hlm-typeform-mobile-nextBtn').show();
}
}

// Validate the form fields


function hlmTypeformValidateForm(inputs) {
let valid = true;
// console.log(inputs);

inputs.each(function() {
const input = $(this);
const errorDiv = jQuery('.hlm-typeform-error-message');
input.removeClass('hlm-typeform-error');
errorDiv.hide();

if (input.attr('type') === 'email') {


if (!hlmTypeformValidateEmail(input.val())) {
errorDiv.text('Please enter a valid email
address.');
errorDiv.show();
valid = false;
} else {
errorDiv.hide();
valid = true;
}
} else if (input.attr('type') === 'radio') {
const radios = $(`input[name=$
{input.attr('name')}]`);
if (!radios.is(':checked')) {
errorDiv.text('Please select any option.');
errorDiv.show();
valid = false;
} else {
errorDiv.hide();
valid = true;
}
} else if (input.attr('type') === 'checkbox') {
const checkboxes = $(`input[name="$
{input.attr('name')}"]:checked`);
if (checkboxes.length === 0) {
errorDiv.text('Please check at least 1
option.');
errorDiv.show();
valid = false;
} else {
errorDiv.hide();
valid = true;
}
} else if (input.prop('tagName') === 'textarea') {
if (!input.val().trim()) {
errorDiv.text('Please fill this field.');
errorDiv.show();
valid = false;
} else {
errorDiv.hide();
valid = true;
}
} else if (input.attr('type') === 'text') {
if (!input.val().trim()) {
errorDiv.text('Please fill this field.');
errorDiv.show();
valid = false;
} else {
errorDiv.hide();
valid = true;
}
}
});

return valid;
}

// Show error message and add red border


function hlmTypeformShowError(input, errorDiv) {
input.addClass('hlm-typeform-error');
errorDiv.show();
return false;
}

// Email validation helper


function hlmTypeformValidateEmail(email){
const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return re.test(String(email).toLowerCase());
}

// Function to update the progress bar width


function hlmTypeformUpdateProgressBar() {
const progressPercentage = ((currentStep + 1) /
steps.length) * 100;
progressBar.css('width', progressPercentage + "%");
}

// Function to reset form wizard


function hlmTypeformResetForm() {
steps.removeClass('hlm-typeform-active hlm-typeform-
previous hlm-typeform-next');
$(steps[0]).addClass('hlm-typeform-active');
hlmTypeformUpdateProgressBar();
$('.hlm-typeform-prevBtn').attr('disabled', true);
jQuery('#hlm-typeform-loader-overlay').hide();
}

// Initialize the form wizard


hlmTypeformUpdateProgressBar();

// Attach event listeners to the buttons


$('.hlm-typeform-prevBtn').on('click', function(e) {
e.preventDefault();
e.stopPropagation();
hlmTypeformNextPrev(-1);
});

$('.hlm-typeform-nextBtn').on('click', function(e) {
e.preventDefault();
e.stopPropagation();
hlmTypeformNextPrev(1);
});

jQuery('input[type=radio]').change(function(){
if (currentStep < steps.length - 1) {
// Trigger the next button if it's not the last step
jQuery('#hlm-typeform-nextBtn2').trigger('click');
}
// jQuery('#hlm-typeform-nextBtn2').trigger('click');
})

jQuery('.hlm-typeform-nextBtns').on('click', function(e) {
if((jQuery(this).attr('id') === 'hlm-typeform-submitBtn')
|| (jQuery(this).attr('id') === 'hlm-typeform-mobile-submitBtn')){
e.preventDefault();
e.stopPropagation();

// if (!hlmTypeformValidateForm(currentInputs)) return;
jQuery('#hlm-typeform-loader-overlay').show();

var form = jQuery('form[name="hlm-typeform-form"]');


var formData = form.serialize(); // Serialize form data
formData = formData + '&email_field=' + jQuery('#hlm-
typeform-email').val();

var form_id_redirect_url =
jQuery('#form_id_redirect_url').val();
var ajaxurl = '<?php echo admin_url('admin-
ajax.php'); ?>';
jQuery.ajax({
url: ajaxurl,
method: 'POST',
data: {
action: 'hlm_typeform_submit',
form_data: formData,
_ajax_nonce:
jQuery('#hlm_forms_quest_ans_noncefield').val()
},
success: function(response) {
// form[0].reset();
window.location.href = (form_id_redirect_url);
},
complete: function() {
// form[0].reset();
// currentStep = 0;
// hlmTypeformResetForm();
},
error: function() {
alert('There was an error submitting the form.
Please try again.');
console.log('There was an error submitting the
form. Please try again.');
},
});
}else{
e.preventDefault();
e.stopPropagation();
hlmTypeformNextPrev(1);
}
});

});
</script>
<style>
.hlm-typeform-nextBtns,
.hlm-typeform-nextBtns:hover,
.hlm-typeform-nextBtns:focus,
.hlm-typeform-nextBtns:active,
.hlm-typeform-nextBtns:visited,
.hlm-typeform-nextBtns:link {
margin: 50px 0 0;
width: 204.878px;
height: 58.437px;
flex-shrink: 0;
border-radius: 39.971px;
background: var(--iHeartDogs-Red, #E22726);
color: var(--iHeartDogs-White, #FFF);
text-align: center;
font-size: 28px;
font-style: normal;
font-weight: 750;
line-height: 135%;
}
</style>
</html>
<?php
return ob_get_clean();
}

// Enqueue jQuery and the custom script for the form wizard
function hlm_typeform_enqueue_scripts() {
// Enqueue jQuery (default in WordPress)
wp_enqueue_script('jquery');

// Enqueue custom script for handling the form wizard logic


// wp_enqueue_script('hlm-typeform-wizard-script',
get_template_directory_uri() . '/js/hlm-typeform-wizard.js', array('jquery'), null,
true);

// Add inline styles for the form wizard


wp_add_inline_style('hlm-typeform-wizard-style', '
/ Basic styling /
.hlm-typeform-wizard { background-color: white; padding: 20px;
border-radius: 10px; max-width: 800px; margin: auto; box-shadow: 0 0 10px
rgba(0,0,0,0.1); overflow: hidden; position: relative; }
.hlm-typeform-progress-bar-wrapper { position: fixed; bottom: 0;
left: 0; width: 100%; height: 10px; background-color: #ddd; border-radius: 5px; }
.hlm-typeform-progress-bar { height: 10px; background-color:
#4a90e2; width: 0%; border-radius: 5px; }
.hlm-typeform-form-container { position: relative; display: flex;
flex-direction: row; height: 300px; overflow: hidden; }
.hlm-typeform-step { width: 100%; position: absolute; top: 0; left:
100%; transition: all 0.5s ease; opacity: 0; display: flex; }
.hlm-typeform-step.hlm-typeform-active { left: 0; opacity: 1; }
.hlm-typeform-left-column { width: 50%; padding: 20px; }
.hlm-typeform-right-column { width: 50%; display: flex; justify-
content: center; align-items: center; }
.hlm-typeform-btn { background-color: #4a90e2; color: white;
padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer; margin-
right: 10px; }
.hlm-typeform-error-message { color: red; font-size: 0.9em;
display: none; }
input.hlm-typeform-error, textarea.hlm-typeform-error { border: 1px
solid red; }
');
}
function handle_typeform_hlm_form_submission() {
check_ajax_referer('hlm_forms_quest_ans_nonceaction',
'_ajax_nonce'); // Verify nonce for security

if (!isset($_POST['form_data'])) {
wp_send_json_error('No form data received');
}

parse_str($_POST['form_data'], $form_data);
// Validate form ID and email
if (empty($form_data['form_id_inputfield'])) {
wp_send_json_error('Form ID is missing');
}

if (empty($form_data['email_field']) || !
filter_var($form_data['email_field'], FILTER_VALIDATE_EMAIL)) {
wp_send_json_error('Invalid or missing email');
}

$form_id = sanitize_text_field($form_data['form_id_inputfield']);
$email = sanitize_email($form_data['email_field']);

// Get the platform associated with the form (optional, adjust as


needed)
$platform = get_field('platform', $form_id);

// Fields to exclude from storage


$exclude_fields = array(
'email_field',
'form_id_inputfield',
'hlm_forms_quest_ans_noncefield',
'_wp_http_referer',
'form_id_redirect_url'
);

// Filter the array to exclude unwanted fields


$filtered_data = array_diff_key($form_data,
array_flip($exclude_fields));

// Sanitize the remaining data


$sanitized_data = array();
foreach ($filtered_data as $key => $value) {
if (filter_var($value, FILTER_VALIDATE_EMAIL)) {
$sanitized_data[$key] = sanitize_email($value);
}
elseif (filter_var($value, FILTER_VALIDATE_URL)) {
$sanitized_data[$key] = esc_url_raw($value);
}
elseif (is_array($value)) {
$sanitized_data[$key] = array_map('sanitize_text_field',
$value);
}
else {
$sanitized_data[$key] = sanitize_text_field($value);
}
}

$json_data = json_encode($sanitized_data);

if ($form_id) {
global $wpdb;
$table_name = "hlm_forms";

$result = $wpdb->insert($table_name, array(


'form_id' => $form_id,
'email' => $email,
'entry' => $json_data
), array(
'%s',
'%s',
'%s'
));

if ($result === false) {


error_log('Database Insert Error: ' . $wpdb->last_error);
wp_send_json_error('Failed to save form data');
} else {
if(!empty($platform) && $platform == 'Klaviyo') {
$listID = get_field('klaviyo_list_ID', $form_id);
if(!empty($listID) && !empty($email)) {
$result = $this->klaviyo_data_insert($listID, $email);
}
}elseif(!empty($platform) && $platform == 'Sendlane') {
$listID = get_field('sendlane_list_id', $form_id);
if(!empty($listID) && !empty($email)) {
$result = $this->sendlane_data_insert($listID, $email);
}
}

wp_send_json_success('Form submitted successfully');


}
} else {
wp_send_json_error('Invalid form ID');
}

wp_die(); // Properly terminate AJAX requests


}

function handle_filter_or_export_records() {
// Check nonce for security
if (!isset($_POST['records_hlmforms_noncefield']) || !
wp_verify_nonce($_POST['records_hlmforms_noncefield'],
'records_hlmforms_nonceaction')) {
die('Invalid nonce');
}

if (isset($_POST['export_csv']) && $_POST['export_csv'] == '1') {


// Get filter parameters
$startdate = !empty($_POST['start_date']) ?
sanitize_text_field($_POST['start_date']) : '';
$todate = !empty($_POST['end_date']) ?
sanitize_text_field($_POST['end_date']) . ' 23:59:59' : '';
$email_or_id = !empty($_POST['email']) ?
sanitize_text_field($_POST['email']) : '';

global $wpdb;

// Start building the query


$query_main = "SELECT * FROM hlm_forms WHERE 1=1";

// Add conditions for non-empty variables


$where_conditions = [];
if (!empty($email_or_id)) {
if (is_numeric($email_or_id)) {
// Search by form_id
$where_conditions[] = $wpdb->prepare("hlm_forms.form_id =
%d", $email_or_id);
} else {
// Search by email
$where_conditions[] = $wpdb->prepare("hlm_forms.email =
%s", $email_or_id);
}
}

// Date range conditions


if (!empty($startdate) && !empty($todate)) {
$where_conditions[] = $wpdb->prepare("hlm_forms.created_at
BETWEEN %s AND %s", $startdate, $todate);
} elseif (!empty($startdate)) {
// If only start date is provided, filter from that date
onwards
$where_conditions[] = $wpdb->prepare("hlm_forms.created_at >=
%s", $startdate);
}

// Combine conditions if any are present


if (!empty($where_conditions)) {
$query_main .= " AND " . implode(" AND ", $where_conditions);
}

// Complete the query with ordering (no pagination here for export)
$query_main .= " ORDER BY hlm_forms.id DESC";

// Get results based on the query


$results = $wpdb->get_results($query_main);

// Prepare CSV data


$csv_data = [];

// Add CSV headers


$headers = ['Form ID', 'Email', 'Entry', 'Date'];
$csv_data[] = $headers;

// Add entry data


foreach ($results as $result) {
$form_id = $result->form_id;
$email = $result->email;
$created_at = $result->created_at;
$entry = json_decode($result->entry, true);

// Format the entry as a single string without extra spaces or


line breaks
$formatted_entry = '';
foreach ($entry as $question => $answer) {
// Format the question (replace underscores with spaces and
capitalize words)
$formatted_question = ucwords(str_replace('_', ' ',
$question));

// Handle array answers (e.g., checkboxes)


if (is_array($answer)) {
$answer = implode(', ', $answer);
}

// Add the question and answer to the formatted entry


$formatted_entry .= $formatted_question . "\nAnswer: " .
$answer . "\n";
}

// Remove the trailing newline character


$formatted_entry = rtrim($formatted_entry, "\n");

// Add a row for the entry


$csv_data[] = [
$form_id,
$email,
$formatted_entry,
$created_at
];
}

// Clear any previous output


ob_end_clean();

// Generate CSV filename


$date = date('Y-m-d-H-i-s');
$filename = "hlm-forms-export-{$date}.csv";

// Output headers to force download


header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="' . $filename .
'"');

// Create a file handle for PHP to output to


$output = fopen('php://output', 'w');

// Output each row of the CSV


foreach ($csv_data as $row) {
fputcsv($output, $row);
}

// Close the file handle


fclose($output);

// Stop further execution


exit();
}
}
function klaviyo_data_insert($listID, $email){
$apiKey = 'pk_afaf47d23fe3c12cbcffa9d429711635ef';
$email_signup = 'Success';

$requestPayload = json_encode([
'data' => [
'type' => 'profile-subscription-bulk-create-job',
'attributes' => [
'custom_source' => 'Marketing Event',
'profiles' => [
'data' => [
[
'type' => 'profile',
'attributes' => [
'email' => $email,
'subscriptions' => [
'email' => [
'marketing' => [
'consent' => 'SUBSCRIBED'
]
]
]
]
]
]
]
],
'relationships' => [
'list' => [
'data' => [
'type' => 'list',
'id' => $listID
]
]
]
]
]);

// Initialize cURL session


$curl = curl_init();
// Set cURL options
curl_setopt_array($curl, [
CURLOPT_URL => "https://a.klaviyo.com/api/profile-
subscription-bulk-create-jobs/",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $requestPayload,
CURLOPT_HTTPHEADER => [
"Authorization: Klaviyo-API-Key $apiKey",
"accept: application/json",
"content-type: application/json",
"revision: 2024-05-15"
]
]);

// Execute cURL request and capture the response


$response = curl_exec($curl);
// Check for errors
if ($err = curl_error($curl)) {
$email_signup = 'Failed';
}

// Close cURL session


curl_close($curl);
return $email_signup;
}
function sendlane_data_insert($listID, $email){
$status = "Success";
$decrypted_sendlane_api_key = "";
$data_encryption = new HLM_Data_Encryption();
$encrypted_sendlane_api_key = get_option('sendlane_api_key');
if( $encrypted_sendlane_api_key ) {
$decrypted_sendlane_api_key = $data_encryption-
>decrypt($encrypted_sendlane_api_key);
}
$headers = array(
'Accept: application/json',
'Authorization: Bearer ' . $decrypted_sendlane_api_key,
'Content-Type: application/json'
);
$ip_address = $_SERVER['REMOTE_ADDR'];
$user_agent = $_SERVER['HTTP_USER_AGENT'];
$endPoint = "https://api.sendlane.com/v2/lists/".$listID."/contacts";

$contact_data = array(
'contacts' => array(
array(
'email' => $email,
'email_consent' => true,
),
),
);

$curl = curl_init();

curl_setopt_array($curl, [
CURLOPT_URL => $endPoint,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode($contact_data),
CURLOPT_HTTPHEADER => $headers,
]);

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
echo "cURL Error #:" . $err;
} else {
$status = 'Failed';

return $status;
}

} // class
$Displaying_HLM_TypeForms_Class = new Displaying_HLM_TypeForms_Class();
} // if class

You might also like