mailferno-theme/page-edit-campaign.php
2024-12-26 12:33:40 -06:00

439 lines
20 KiB
PHP

<?php
/**
* Template Name: Campaign Edit template
* Template Post Type: page
*/
if (!defined('ABSPATH')) {
exit;
}
// log_to_file("Campaign Edit template - Loaded");
$current_user_id = get_current_user_id();
$message = false;
$new_post = true;
$professions = [];
// log_to_file("Campaign Edit template - Current user ID: $current_user_id");
// log_to_file("Campaign Edit template - Server Request Method: ", $_SERVER['REQUEST_METHOD']);
// log_to_file("Campaign Edit template - Post Data: ", $_POST);
// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['campaign_submit'])) {
// log_to_file("Campaign Edit template - Handling post request");
$post_data = array(
'post_title' => sanitize_text_field($_POST['campaign_name']),
'post_type' => 'campaign',
'post_status' => 'publish'
);
if (isset($_POST['post_id']) && !empty($_POST['post_id'])) {
// log_to_file("Campaign Edit template - Updating campaign");
$post_data['ID'] = intval($_POST['post_id']);
$post_id = wp_update_post($post_data);
$new_post = false;
$message = ['status' => 'success', 'message' => 'Campaign updated successfully.'];
} else {
// log_to_file("Campaign Edit template - Creating new campaign");
$post_id = wp_insert_post($post_data);
$message = ['status' => 'success', 'message' => 'Campaign added successfully.'];
}
if (!is_wp_error($post_id)) {
// log_to_file("Campaign Edit template - Create/update successful!");
$acf_fields = [
'domain_id',
'email_accounts',
// 'num_additional_emails',
'start_date',
'warmup_period',
'starting_volume',
'target_volume',
'target_profession',
'target_profession_other',
'campaign_conversation_topics'
];
foreach ($acf_fields as $field) {
if (isset($_POST[$field])) {
// log_to_file("Campaign Edit template - Checking for $field in POST: ", $_POST[$field]);
switch ($field) {
case 'email_accounts':
// log_to_file("Campaign Edit template - Found email_accounts in POST", $_POST[$field]);
update_field($field, $_POST[$field], $post_id);
break;
case 'domain_id':
// log_to_file("Campaign Edit template - Found domain in POST", $_POST['domain_id']);
try {
update_field('domain', $_POST['domain_id'], $post_id);
} catch (Exception $e) {
throw new Exception(__('fetch_dns_records - Campaign Edit template: Unable to update domain field for Campaign', 'rl-mailwarmer') . $e->getMessage());
}
break;
default:
update_field($field, sanitize_text_field($_POST[$field]), $post_id);
break;
}
}
}
// log_to_file("Campaign Edit template - Setting campaign owner_id to $current_user_id");
update_post_meta($post_id, 'owner_id', $current_user_id);
// Run a domain health check
$campaign_timeline = RL_MailWarmer_Campaign_Helper::calculate_campaign_timeline($post_id);
log_to_file("Campaign Edit template - Campaign timeline: ", $campaign_timeline);
} else {
$message = ['status' => 'error', 'message' => 'Error: ' . $post_id->get_error_message()];
}
if ( !(isset($_POST['stay_on_page']) && ($_POST['stay_on_page'] === 'on')) ) {
// log_to_file("Domain Edit template - stay_on_page not set; redirecting!");
wp_redirect( get_permalink( $post_id ) );
exit;
}
} else {
// log_to_file("Campaign Edit template - Post request not set");
}
// Get existing post data if editing
if (isset($_GET['edit'])) {
$post_id = intval($_GET['edit']);
$new_post = false;
} else {
$post_id = 0;
}
$campaign_data = [
'campaign_name' => '',
'domain_id' => '',
'email_accounts' => [],
'num_additional_emails' => '',
'start_date' => '',
'warmup_period' => '8',
'starting_volume' => '5',
'target_volume' => '50',
'target_profession' => '',
'target_profession_other' => '',
'campaign_conversation_topics' => ''
];
if ($post_id > 0) {
$post_item = get_post($post_id);
if ($post_item && $post_item->post_type === 'campaign') {
$campaign_data['campaign_name'] = $post_item->post_title;
foreach ($campaign_data as $key => $value) {
if ($key !== 'campaign_name') {
switch ($key) {
case 'domain_id':
$domain_id = get_field('domain', $post_id);
$campaign_data[$key] = $domain_id->ID;
break;
case 'email_accounts':
$email_accounts = get_field($key, $post_id);
// log_to_file("Campaign Edit template - Email accounts: ", $email_accounts);
$campaign_data[$key] = $email_accounts;
break;
case 'start_date':
$start_date = get_field($key, $post_id);
$campaign_data[$key] = date('Y-m-d', strtotime($start_date));
break;
default:
$campaign_data[$key] = get_field($key, $post_id);
break;
}
// if ($key === 'domain_id') {
// $domain_id = get_field('domain', $post_id);
// $campaign_data[$key] = $domain_id->ID;
// } else {
// $campaign_data[$key] = get_field($key, $post_id);
// }
}
}
}
}
// Get domains for current user
$domains = get_posts([
'orderby' => 'title',
'order' => 'ASC',
'post_type' => 'domain',
'posts_per_page' => -1,
'meta_query' => [
[
'key' => 'owner_id',
'value' => $current_user_id
]
]
]);
// log_to_file("Campaign Edit template - Domains: ", $domains);
// Get the list of default professions
$professions = rl_get_textarea_meta_as_array('option', 'default_profession_pool');
// log_to_file("Campaign Edit template - Professions: ", $professions);
get_header(); ?>
<div <?php generate_do_attr('content'); ?>>
<main <?php generate_do_attr('main'); ?>>
<?php do_action('generate_before_main_content');
if (generate_has_default_loop()) {
while (have_posts()) :
the_post(); ?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?> <?php generate_do_microdata('article'); ?>>
<div class="inside-article mf-dashboard-page">
<header <?php generate_do_attr('entry-header'); ?>>
<?php if ($message): ?>
<div class="notice notice-<?php echo $message['status']; ?> is-dismissible">
<p><?php echo esc_html($message['message']); ?></p>
<button type="button" class="notice-dismiss">
<span class="screen-reader-text">Dismiss this notice.</span>
</button>
</div>
<?php endif; ?>
</header>
<div class="entry-content">
<div class="wrap">
<h1><?php echo $post_id ? 'Edit Campaign' : 'Add New Campaign'; ?></h1>
<form method="post" action="" class="mf-dashboard-form">
<?php wp_nonce_field('campaign_form_nonce', 'campaign_nonce'); ?>
<?php if ($post_id) : ?>
<input type="hidden" name="post_id" value="<?php echo esc_attr($post_id); ?>">
<?php endif; ?>
<div class="mf-form-field-block">
<table class="mf-form-table">
<tr>
<th><label for="campaign_name">Campaign Name</label></th>
<td>
<input type="text" id="campaign_name" name="campaign_name"
value="<?php echo esc_attr($campaign_data['campaign_name']); ?>"
class="regular-text" required>
</td>
</tr>
<tr>
<th><label for="domain_id">Domain</label></th>
<td>
<select id="domain_id" name="domain_id" required>
<option value="">Select Domain</option>
<?php foreach ($domains as $domain) : ?>
<option value="<?php echo $domain->ID; ?>"<?php selected($campaign_data['domain_id'], $domain->ID); ?>><?php echo esc_html($domain->post_title); ?></option>
<?php endforeach; ?>
</select>
</td>
</tr>
<tr>
<th><label for="email_accounts">Email Accounts</label></th>
<td>
<select id="email_accounts" name="email_accounts[]" multiple required class="email-accounts-select">
<?php
$email_accounts = get_posts([
'post_type' => 'email-account',
'posts_per_page' => -1,
'meta_query' => [
[
'key' => 'owner_id',
'value' => $current_user_id
]
]
]);
$selected_accounts = isset($campaign_data['email_accounts']) ? $campaign_data['email_accounts'] : [];
// log_to_file("Selected email accounts: ", $selected_accounts);
foreach ($email_accounts as $account) :
$account_id = $account->ID;
$account_name = $account->post_title; ?>
<option value="<?php echo esc_attr($account_id); ?>"<?php echo in_array($account_id, $selected_accounts) ? 'selected' : ''; ?>><?php echo esc_html($account_name); ?></option>
<?php endforeach; ?>
</select>
</td>
</tr>
<!-- <tr>
<th><label for="num_additional_emails">Number of Additional Emails</label></th>
<td>
<input type="number" id="num_additional_emails" name="num_additional_emails"
value="<?php //echo esc_attr($campaign_data['num_additional_emails']); ?>"
class="small-text" required>
</td>
</tr> -->
<tr>
<th><label for="start_date">Start Date</label></th>
<td>
<input type="date" id="start_date" name="start_date"
value="<?php echo esc_attr($campaign_data['start_date']); ?>" required>
</td>
</tr>
<tr>
<th><label for="warmup_period">Warmup Period (in weeks)</label></th>
<td>
<input type="number" id="warmup_period" name="warmup_period"
value="<?php echo esc_attr($campaign_data['warmup_period']); ?>"
class="small-text" min="2" max="52" placeholder="8" required>
</td>
</tr>
<tr>
<th><label for="starting_volume">Starting Daily Volume</label></th>
<td>
<input type="number" id="starting_volume" name="starting_volume"
value="<?php echo esc_attr($campaign_data['starting_volume']); ?>"
class="small-text" min="1" max="50" placeholder="5" required>
</td>
</tr>
<tr>
<th><label for="target_volume">Target Daily Volume</label></th>
<td>
<input type="number" id="target_volume" name="target_volume"
value="<?php echo esc_attr($campaign_data['target_volume']); ?>"
class="small-text" min="10" max="1000" placeholder="50" required>
</td>
</tr>
<tr>
<th><label for="target_profession">Target Profession</label></th>
<td>
<select id="target_profession" name="target_profession" required>
<option value="">Select Profession</option>
<?php foreach ($professions as $profession) :
?>
<option value="<?php echo htmlentities($profession); ?>"<?php selected($campaign_data['target_profession'], $profession); ?>><?php echo htmlentities($profession); ?></option>
<?php endforeach; ?>
</select>
</td>
</tr>
<tr>
<th><label for="target_profession_other">Other Profession</label></th>
<td>
<input type="text" id="target_profession_other" name="target_profession_other"
value="<?php echo esc_attr($campaign_data['target_profession_other']); ?>"
class="regular-text">
</td>
</tr>
<tr>
<th><label for="campaign_conversation_topics">Conversation Topics</label></th>
<td>
<textarea id="campaign_conversation_topics" name="campaign_conversation_topics"
class="regular-text" rows="5"><?php echo esc_textarea($campaign_data['campaign_conversation_topics']); ?></textarea>
</td>
</tr>
</table>
</div>
<p class="submit">
<input type="submit" name="campaign_submit" class="button button-primary"
value="<?php echo $post_id ? 'Update Campaign' : 'Add Campaign'; ?>">
</p>
<?php if ($new_post) : ?>
<div class="mf-form-field-block">
<label for="stay_on_page">Stay on this page to create another?</label>
<input type="checkbox"
id="stay_on_page"
name="stay_on_page"
class="">
</div>
<?php endif; ?>
</form>
</div>
</div>
</div>
</article>
<?php endwhile;
wp_reset_postdata();
}
do_action('generate_after_main_content'); ?>
</main>
</div>
<script>
jQuery(document).ready(function($) {
/*
* Filter email accounts to only display those matching the selected domain
*
*/
const $domainSelect = $('#domain_id');
const $emailSelect = $('#email_accounts');
const $emailOptions = $emailSelect.find('option');
function filterEmailAccounts() {
const selectedDomain = $domainSelect.val();
console.log("Filtering for " + selectedDomain);
$emailOptions.hide();
if (selectedDomain) {
$emailOptions.each(function() {
const $option = $(this);
const email = $option.text();
// console.log("Checking " + email);
const domain = $domainSelect.find('option:selected').text();
// console.log("Domain " + domain);
if (email.endsWith('@' + domain)) {
// console.log("Showing this option");
$option.show();
}
});
}
}
$domainSelect.on('change', function() {
$emailSelect.val([]); // Clear selection
filterEmailAccounts();
});
// Initial filter
filterEmailAccounts();
/*
* Show the Other Profession field when the Target Profession is set to "Other"
*
*/
const $professionSelect = $('#target_profession');
const $otherField = $('#target_profession_other').closest('tr');
function toggleOtherField() {
if ($professionSelect.val() === 'Other') {
$otherField.show();
} else {
$otherField.hide();
$('#target_profession_other').val('');
}
}
$professionSelect.on('change', toggleOtherField);
// Initial state
toggleOtherField();
});
</script>
<?php
do_action('generate_after_primary_content_area');
generate_construct_sidebars();
get_footer();