<?php
// includes/actions/submit.php
defined('ABSPATH') || exit;

// Process the blog-maker action
function blog_maker_action() {

    // Used to suppress the "monthly limit reached" popup on the same request
    // when the user just successfully posted their 2nd free blog.
    $GLOBALS['blog_maker_just_posted_successfully'] = false;

    check_admin_referer('blog_maker_nonce');
    
        // Get the user's IP address for the log file
    $user_ip = $_SERVER['REMOTE_ADDR'];
    
    // Get current user ID
    $current_user = wp_get_current_user();
    $user_id = $current_user->ID;
    
    // Enforce free-tier monthly post limit (based on blog-maker.log).
    $limit_status = blog_maker_get_monthly_limit_status();
    if (!empty($limit_status['is_limited'])) {
        $reset_at = $limit_status['reset_at'];
        $reset_str = ($reset_at instanceof DateTime) ? $reset_at->format('F j, Y') : '';
        add_settings_error(
            'blog_maker_monthly_limit_reached',
            'Monthly limit reached: you\'ve already created ' . (int)$limit_status['count_this_month'] . ' blog posts this month. You can create more on ' . $reset_str . '.',
            'error'
        );
        return;
    }
    
    // Track whether this submission will be scheduled (future) vs published immediately
    $was_scheduled = false;
    
    $h1 = $_POST['h1'];
    $postmetadata = $_POST['postmetadata'];
    $slug = $_POST['slug'];

    // Optional destination selector (now supports selecting any page ID OR the legacy 'newsletters' string)
    $post_destination_raw = isset($_POST['post_destination']) ? sanitize_text_field($_POST['post_destination']) : '';
    $post_destination = '';
    $post_destination_page_id = 0;
    
    // Detect the canonical newsletters page ID (so selecting it by ID behaves like legacy "newsletters")
    $newsletters_page = get_page_by_path('newsletters');
    $newsletters_id   = ($newsletters_page && !is_wp_error($newsletters_page)) ? (int) $newsletters_page->ID : 0;
    
    if (ctype_digit($post_destination_raw)) {
        // numeric value -> page ID
        $post_destination_page_id = (int) $post_destination_raw;
    
        // If they picked the newsletters page by ID, treat it as newsletters
        if (!empty($newsletters_id) && $post_destination_page_id === $newsletters_id) {
            $post_destination = 'newsletters';
        } else {
            $post_destination = 'page:' . $post_destination_page_id;
        }
    } elseif ($post_destination_raw === 'newsletters') {
        // legacy behavior
        $post_destination = 'newsletters';
    } else {
        // empty / unknown -> fallback to blog (legacy default)
        $post_destination = 'blog';
    }

    $p1 = $_POST['p1'];
    $h3 = $_POST['h3'];
    $p2 = $_POST['p2'];
    $secondh3 = $_POST['secondh3'];
    $p3 = $_POST['p3'];
    $thirdh3 = $_POST['thirdh3'];
    $p4 = $_POST['p4'];
    $fourthh3 = $_POST['fourthh3'];
    $p5 = $_POST['p5'];
    $selectedImageData = $_POST['selectedImageData'];
    $fifthh3 = $_POST['fifthh3'];
    $p6 = $_POST['p6'];
    $sixthh3 = $_POST['sixthh3'];
    $p7 = $_POST['p7'];
    $seventhh3 = $_POST['seventhh3'];
    $p8 = $_POST['p8'];
    $eighthh3 = $_POST['eighthh3'];
    $p9 = $_POST['p9'];
    $ninthh3 = $_POST['ninthh3'] ?? '';
    $p10 = $_POST['p10'] ?? '';
    $tenthh3 = $_POST['tenthh3'] ?? '';
    $p11 = $_POST['p11'] ?? '';
    $eleventhh3 = $_POST['eleventhh3'] ?? '';
    $p12 = $_POST['p12'] ?? '';
    $twelfthh3 = $_POST['twelfthh3'] ?? '';
    $p13 = $_POST['p13'] ?? '';
    $thirteenthh3 = $_POST['thirteenthh3'] ?? '';
    $p14 = $_POST['p14'] ?? '';
    $fourteenthh3 = $_POST['fourteenthh3'] ?? '';
    $p15 = $_POST['p15'] ?? '';
    $fifteenthh3 = $_POST['fifteenthh3'] ?? '';
    $p16 = $_POST['p16'] ?? '';
    $sixteenthh3 = $_POST['sixteenthh3'] ?? '';
    $p17 = $_POST['p17'] ?? '';
    $h3separator = isset($_POST['h3-checkbox']) && $_POST['h3-checkbox'] === 'on';
    $secondh3separator = isset($_POST['secondh3-checkbox']) && $_POST['secondh3-checkbox'] === 'on';
    $thirdh3separator = isset($_POST['thirdh3-checkbox']) && $_POST['thirdh3-checkbox'] === 'on';
    $fourthh3separator = isset($_POST['fourthh3-checkbox']) && $_POST['fourthh3-checkbox'] === 'on';
    $fifthh3separator = isset($_POST['fifthh3-checkbox']) && $_POST['fifthh3-checkbox'] === 'on';
    $sixthh3separator = isset($_POST['sixthh3-checkbox']) && $_POST['sixthh3-checkbox'] === 'on';
    $seventhh3separator = isset($_POST['seventhh3-checkbox']) && $_POST['seventhh3-checkbox'] === 'on';
    $eighthh3separator = isset($_POST['eighthh3-checkbox']) && $_POST['eighthh3-checkbox'] === 'on';
    $ninthh3separator = isset($_POST['ninthh3-checkbox']) && $_POST['ninthh3-checkbox'] === 'on';
    $tenthh3separator = isset($_POST['tenthh3-checkbox']) && $_POST['tenthh3-checkbox'] === 'on';
    $eleventhh3separator = isset($_POST['eleventhh3-checkbox']) && $_POST['eleventhh3-checkbox'] === 'on';
    $twelfthh3separator = isset($_POST['twelfthh3-checkbox']) && $_POST['twelfthh3-checkbox'] === 'on';
    $thirteenthh3separator = isset($_POST['thirteenthh3-checkbox']) && $_POST['thirteenthh3-checkbox'] === 'on';
    $fourteenthh3separator = isset($_POST['fourteenthh3-checkbox']) && $_POST['fourteenthh3-checkbox'] === 'on';
    $fifteenthh3separator = isset($_POST['fifteenthh3-checkbox']) && $_POST['fifteenthh3-checkbox'] === 'on';
    $sixteenthh3separator = isset($_POST['sixteenthh3-checkbox']) && $_POST['sixteenthh3-checkbox'] === 'on';
    // Video fields (used only when a Vimeo/YouTube URL is provided)
    $videoTitle = isset($_POST['videoTitle']) ? sanitize_text_field($_POST['videoTitle']) : '';
    // Allow basic formatting but strip unsafe markup
    $videoDescription = isset($_POST['videoDescription']) ? wp_kses_post(stripslashes($_POST['videoDescription'])) : '';
    // Scheduling (optional)
    $schedule_datetime = isset($_POST['schedule_datetime']) ? sanitize_text_field($_POST['schedule_datetime']) : '';

    $domain = parse_url( home_url(), PHP_URL_HOST );
    $domain = preg_replace( '/^www\./', '', $domain );

    /*
     * Ensure a stable slug: if the user left the slug blank, generate one
     * that reflects the actual publish time (or scheduled time). This value
     * is used when importing the XML template so the imported post gets
     * the correct, timestamped slug.
     */
    if (empty($slug)) {
        // Prefer the scheduled datetime if provided, otherwise use "now".
        $tz = function_exists('wp_timezone') ? wp_timezone() : new DateTimeZone(wp_get_timezone_string());
        try {
            if (!empty($schedule_datetime)) {
                // schedule_datetime is expected as "YYYY-MM-DDTHH:MM" from datetime-local
                $dt = new DateTimeImmutable($schedule_datetime, $tz);
            } else {
                $dt = new DateTimeImmutable('now', $tz);
            }
        } catch (Exception $e) {
            // Fallback to current time if parsing fails
            $dt = new DateTimeImmutable('now', $tz);
        }

        // Format like: post-YYYYMMDD-HHMMSS (safe for slugs)
        $slug = 'post-' . $dt->format('Ymd-His');
        $slug = sanitize_title($slug);
    }

    // Check if an image was uploaded
    if (isset($_FILES['image']) && !empty($_FILES['image']['tmp_name'])) {
        // Handle uploaded image
        $uploaded_image = $_FILES['image']['tmp_name'];
    
        // Determine the target file path in the destination directory
        $target_directory = dirname(dirname(dirname(dirname(dirname(__FILE__)))));
        $target_file = $target_directory . '/' . basename($_FILES['image']['name']);
    
    } elseif (!empty($_POST['selectedImageData'])) {
        // Handle selected image from JavaScript
        $selected_image_data = $_POST['selectedImageData'];
        $uploaded_image = $selected_image_data;
    } else {
        $uploaded_image = ''; // No image provided
    }

    // If there are any errors, display them
    if (preg_match('/[^a-z0-9-]/', $slug)) {
        $errors[] = 'ERROR: Slug can only contain lowercase letters, numbers, and hyphens (-).';
    }
    if (empty($h1)) {
        $errors[] = 'ERROR: Please Enter Page Title Before Submitting.';
    }
    
    if (empty($p1)) {
        $errors[] = 'ERROR: Please Enter Something In First Section Before Submitting.';
    }
    
    // Schedule validation (optional): only validate if user provided a datetime
    if (!empty($schedule_datetime)) {
        try {
            $tz = function_exists('wp_timezone') ? wp_timezone() : new DateTimeZone(wp_get_timezone_string());
            // HTML datetime-local: "YYYY-MM-DDTHH:MM"
            $dt_local = new DateTimeImmutable($schedule_datetime, $tz);
            $now_local = new DateTimeImmutable('now', $tz);
            if ($dt_local <= $now_local) {
                $errors[] = 'ERROR: Scheduled date/time must be in the future.';
            }
        } catch (Exception $e) {
            $errors[] = 'ERROR: Invalid schedule date/time.';
        }
    }

    if (!empty($_FILES['image']['tmp_name']) && !empty($_POST['videoUrl'])) {
        $errors[] = 'ERROR: You can only upload an image OR enter a video URL, you cannot do both.';
    }
    
    // Check if video URL is provided and validate it
    $videoUrl = isset($_POST['videoUrl']) ? $_POST['videoUrl'] : '';
    if (!empty($videoUrl) && !preg_match('/(vimeo\.com|youtube\.com|youtu\.be)/', $videoUrl)) {
        $errors[] = 'ERROR: Video URL must be either a Vimeo or a YouTube link. Please check your link and try again!';
    }
  
    if (!empty($errors)) {
        echo '<div class="notice notice-error">';
        foreach ($errors as $error) {
            echo '<p>' . esc_html($error) . '</p>';
        }
        echo '</div>';
    
    // Clear the form fields after a successful submission
    clearFormFieldsFromSlashes();
        return;
    }
    
    // Log the form data to file blog-maker.log
    $log_data = date('Y-m-d H:i:s') . "\t" . $user_ip;
    $log_data .= "\t";
    $log_data .= $h1 . "\t";
    $log_data .= $slug . "\t";
    $log_data .= $postmetadata . "\t";
    $log_data .= $uploaded_image . "\t";
    $log_data .= $p1 . "\t";
    $log_data .= $h3 . "\t";
    $log_data .= $p2 . "\t";
    $log_data .= $secondh3 . "\t";
    $log_data .= $p3 . "\t";
    $log_data .= $thirdh3 . "\t";
    $log_data .= $p4 . "\t";
    $log_data .= $fourthh3 . "\t";
    $log_data .= $p5 . "\t";
    $log_data .= $selectedImageData . "\t";
    $log_data .= $videoUrl . "\t";
    $log_data .= $videoTitle . "\t";
    $log_data .= $videoDescription . "\t";
    $log_data .= $fifthh3 . "\t";
    $log_data .= $p6 . "\t";
    $log_data .= $sixthh3 . "\t";
    $log_data .= $p7 . "\t";
    $log_data .= $seventhh3 . "\t";
    $log_data .= $p8 . "\t";
    $log_data .= $eighthh3 . "\t";
    $log_data .= $p9 . "\t";
    $log_data .= $ninthh3 . "\t";
    $log_data .= $p10 . "\t";
    $log_data .= $tenthh3 . "\t";
    $log_data .= $p11 . "\t";
    $log_data .= $eleventhh3 . "\t";
    $log_data .= $p12 . "\t";
    $log_data .= $twelfthh3 . "\t";
    $log_data .= $p13 . "\t";
    $log_data .= $thirteenthh3 . "\t";
    $log_data .= $p14 . "\t";
    $log_data .= $fourteenthh3 . "\t";
    $log_data .= $p15 . "\t";
    $log_data .= $fifteenthh3 . "\t";
    $log_data .= $p16 . "\t";
    $log_data .= $sixteenthh3 . "\t";
    $log_data .= $p17 . "\t";
    $log_data .= "\n";
    
    $log_file = BLOG_MAKER_DIR . '/blog-maker.log';
    file_put_contents($log_file, $log_data, FILE_APPEND);
    
    // Import the appropriate XML template (stored alongside this plugin) and create the post in PHP.
    $output = array();
    $status = 0;

    $xml_dir = BLOG_MAKER_DIR . '/xml';

    // Content Type selector from the form (defaults to Blog Post)
    $content_type = isset($_POST['content_type']) ? sanitize_text_field($_POST['content_type']) : 'blog_post';
    $is_page = ($content_type === 'page');

    // New fields: Clinic Name, City, State
    $clinic_name = isset($_POST['clinicName']) ? sanitize_text_field($_POST['clinicName']) : '';
    $city        = isset($_POST['city']) ? sanitize_text_field($_POST['city']) : '';
    $state       = isset($_POST['state']) ? sanitize_text_field($_POST['state']) : '';

    if (empty($clinic_name)) {
        $clinic_name = get_option('blogname');
    }

    // Compute geo suffix only when BOTH city and state are present
    $geo_suffix = '';
    if ($city !== '' && $state !== '') {
        $geo_suffix = ' in ' . $city . ' ' . $state;
    }

    // Title & metadata inputs (base vs final)
    $h1_base = isset($_POST['h1']) ? sanitize_text_field($_POST['h1']) : '';
    $h1_final = $h1_base;

    $postmetadata = isset($_POST['postmetadata']) ? wp_kses_post(stripslashes($_POST['postmetadata'])) : '';

    // First H3 (Second Headline) from the form
    $h3 = isset($_POST['h3']) ? sanitize_text_field($_POST['h3']) : '';
    $h3_final = $h3;

    if ($geo_suffix !== '') {
        if ($h1_final !== '' && stripos($h1_final, $geo_suffix) === false) {
            $h1_final .= $geo_suffix;
        }

        if (empty(trim($postmetadata))) {
            $noun = ($is_page ? 'page' : 'blog post');
            $postmetadata = "Check out this {$noun} and visit us today in {$city} {$state}!";
        }
        // Append geo_suffix to first H3 if present
        if ($h3_final !== '' && stripos($h3_final, $geo_suffix) === false) {
            $h3_final .= $geo_suffix;
        }
    } else {
        if (empty(trim($postmetadata))) {
            $noun = ($is_page ? 'page' : 'blog post');
            $postmetadata = "Check out this {$noun} and visit us today!";
        }
    }

    // Choose which XML template to use based on video URL
    $videoUrl = isset($_POST['videoUrl']) ? $_POST['videoUrl'] : '';
    $video_template = 'none';

    if ($is_page) {
        // Regular Page template
        $xml_file = $xml_dir . '/h1.xml';
    } else if (strpos($videoUrl, 'vimeo.com') !== false) {
        $video_template = 'vimeo';
        $xml_file = $xml_dir . '/vph1.xml';
    } else if (strpos($videoUrl, 'youtube.com') !== false || strpos($videoUrl, 'youtu.be') !== false) {
        $video_template = 'youtube';
        $xml_file = $xml_dir . '/yph1.xml';
    } else {
        $xml_file = $xml_dir . '/ph1.xml';
    }

    // Import the post from the XML template and force the slug the user provided.
    $import_result = blog_maker_import_wxr_template($xml_file, $slug, $user_id);
    
    if (is_wp_error($import_result)) {
        $status = 1;
        $output[] = $import_result->get_error_message();
    } else {
        $status  = 0;
        $post_id = (int) $import_result;
        
        // Decide what to feed into *title tokens* (PH1*/H1*/YPH1*/VPH1*)
        // If the imported template already includes "TOKEN in CITY* STATE*", do NOT also bake geo into the token value.
        $h1_for_tokens = $h1_final;

        if ($geo_suffix !== '') {
            $bb_data = get_post_meta($post_id, '_fl_builder_data', true);
            $bb_str  = is_string($bb_data) ? $bb_data : wp_json_encode($bb_data);

            $template_already_appends_geo =
                (stripos($bb_str, 'PH1* in CITY* STATE*') !== false) ||
                (stripos($bb_str, 'H1* in CITY* STATE*') !== false)  ||
                (stripos($bb_str, 'YPH1* in CITY* STATE*') !== false) ||
                (stripos($bb_str, 'VPH1* in CITY* STATE*') !== false);

            if ($template_already_appends_geo) {
                $h1_for_tokens = $h1_base;
            }
        }

        // ===== Publish now OR schedule for later =====
        $now_local = current_time('mysql');
        $now_gmt   = current_time('mysql', 1);

        $update_args = array(
            'ID'            => $post_id,
            'post_date'     => $now_local,
            'post_date_gmt' => $now_gmt,
            // Explicitly publish the imported draft when doing a normal (non-scheduled) publish
            'post_status'   => 'publish',

            // IMPORTANT: Ensure title is never left as template token (e.g., "H1*")
            'post_title'    => $h1_final,

            // If Page selected, make sure this is a page
            'post_type'     => ($is_page ? 'page' : 'post'),
        );


        if (!empty($schedule_datetime)) {
            try {
                $tz = function_exists('wp_timezone') ? wp_timezone() : new DateTimeZone(wp_get_timezone_string());
                $dt_local = new DateTimeImmutable($schedule_datetime, $tz);
                // WordPress expects MySQL datetime strings
                $update_args['post_date']     = $dt_local->format('Y-m-d H:i:s');
                $update_args['post_date_gmt'] = $dt_local->setTimezone(new DateTimeZone('UTC'))->format('Y-m-d H:i:s');
                $update_args['post_status']   = 'future';
                
                // Mark that this post was scheduled (used to customize the success message)
                $was_scheduled = true;
            } catch (Exception $e) {
                // If scheduling fails for any reason, fall back to publishing now.
            }
        }

        wp_update_post($update_args);

        // Apply taxonomy filters based on "Post To" selection.
        // - Newsletters: force category "Newsletters"
        // - Specific page: apply that page's "Includes" (category/post_tag) filters to the new post
        if ($post_destination === 'newsletters') {
            // Always force the Newsletters category
            blog_maker_apply_newsletters_category($post_id);

            // Apply includes/excludes from the newsletters page (if selected by ID)
            if (!empty($post_destination_page_id)) {
                blog_maker_apply_destination_terms_from_page($post_id, $post_destination_page_id);
                blog_maker_apply_destination_exclusions_from_page($post_id, $post_destination_page_id);
            }
        } else {

            // If posting to a specific destination page, apply includes + excludes from that page.
            if (!empty($post_destination_page_id)) {
                blog_maker_apply_destination_terms_from_page($post_id, $post_destination_page_id);
                blog_maker_apply_destination_exclusions_from_page($post_id, $post_destination_page_id);
            }

            // If posting to the main blog (or default), enforce /blog exclusions.
            // This guarantees the post will NOT have "Newsletters".
            $blog_page = get_page_by_path('blog');
            $blog_id   = ($blog_page && !is_wp_error($blog_page)) ? (int) $blog_page->ID : 0;

            if (!empty($blog_id)) {
                blog_maker_apply_destination_exclusions_from_page($post_id, $blog_id);
            }

            // Extra hard safety for /blog behavior
            blog_maker_ensure_no_newsletters_category($post_id);
        }

        blog_maker_set_clean_excerpt_for_video($post_id, $video_template);

        // ===== Build PC* like the bash script =====
        $pc_combined = blog_maker_build_pc($p1, array(
            // Use the geo-appended final H3 here so the first H3 inside PC* contains "in City State"
            array('headline' => $h3_final,        'content' => $p2,  'separator' => $h3separator),
            array('headline' => $secondh3,        'content' => $p3,  'separator' => $secondh3separator),
            array('headline' => $thirdh3,         'content' => $p4,  'separator' => $thirdh3separator),
            array('headline' => $fourthh3,        'content' => $p5,  'separator' => $fourthh3separator),
            array('headline' => $fifthh3,         'content' => $p6,  'separator' => $fifthh3separator),
            array('headline' => $sixthh3,         'content' => $p7,  'separator' => $sixthh3separator),
            array('headline' => $seventhh3,       'content' => $p8,  'separator' => $seventhh3separator),
            array('headline' => $eighthh3,        'content' => $p9,  'separator' => $eighthh3separator),
            array('headline' => $ninthh3,         'content' => $p10, 'separator' => $ninthh3separator),
            array('headline' => $tenthh3,         'content' => $p11, 'separator' => $tenthh3separator),
            array('headline' => $eleventhh3,      'content' => $p12, 'separator' => $eleventhh3separator),
            array('headline' => $twelfthh3,       'content' => $p13, 'separator' => $twelfthh3separator),
            array('headline' => $thirteenthh3,    'content' => $p14, 'separator' => $thirteenthh3separator),
            array('headline' => $fourteenthh3,    'content' => $p15, 'separator' => $fourteenthh3separator),
            array('headline' => $fifteenthh3,     'content' => $p16, 'separator' => $fifteenthh3separator),
            array('headline' => $sixteenthh3,     'content' => $p17, 'separator' => $sixteenthh3separator),
        ));
        
        // ===== Match bash defaults =====
        if (empty($postmetadata)) {
                if ($is_page) {
                    $postmetadata = "Check out this page and visit us today!";
            } else {
                    $postmetadata = "Check out this blog post and visit us today!";
            }
        }
    
    // Ensure hero image is resolved BEFORE replacements.
    // Priority:
    // 1) Master Library selection (selectedImageUrl)
    // 2) Uploaded file (blog_maker_get_featured_image_url_and_set)
    // 3) Template placeholder (last resort)
    $selected_master_url = isset($_POST['selectedImageUrl']) ? esc_url_raw($_POST['selectedImageUrl']) : '';
    $media_url = '';

    // Optional image title/alt (you already collect this in the form)
    $image_alt_title = isset($_POST['image_alt_title'])
        ? sanitize_text_field(wp_unslash($_POST['image_alt_title']))
        : '';

    if (!empty($selected_master_url)) {

        // Try to resolve the selected URL to a Media Library attachment ID.
        // attachment_url_to_postid() often fails on resized URLs (e.g. -714x250),
        // so we also try the "original" URL by stripping the size suffix.
        $attachment_id = attachment_url_to_postid($selected_master_url);

        $maybe_original = '';
        if (empty($attachment_id)) {
            $maybe_original = preg_replace('/-\d+x\d+(?=\.(jpg|jpeg|png|gif|webp|avif)$)/i', '', $selected_master_url);
            if ($maybe_original && $maybe_original !== $selected_master_url) {
                $attachment_id = attachment_url_to_postid($maybe_original);
            }
        }

        // If still not found locally, sideload/import into this site's Media Library
        if (empty($attachment_id)) {
            $source_for_import = $maybe_original ? $maybe_original : $selected_master_url;

            // Downloads + imports + de-dupes by storing blog_maker_source_url meta
            $attachment_id = blog_maker_sideload_master_image_to_media_library(
                $source_for_import,
                (int) $post_id,
                $image_alt_title,   // title
                $image_alt_title    // alt
            );
        }

        if (!empty($attachment_id)) {
            // Use the canonical attachment URL (helps consistency)
            $canonical = wp_get_attachment_url((int) $attachment_id);
            if (!empty($canonical)) {
                $media_url = $canonical;
            }

            // Set featured image so BB / theme components that rely on thumbnail ID work
            set_post_thumbnail($post_id, (int) $attachment_id);
        }

        // If we still don't have a media URL, fall back to the selected URL itself
        if (empty($media_url)) {
            $media_url = $selected_master_url;
        }

    } else {
        // No master library selection Ã¢â‚¬â€ use upload/default behavior
        $media_url = blog_maker_get_featured_image_url_and_set($post_id);
    }

    // Absolute last resort: never let $media_url be empty (prevents blank src)
    if (empty($media_url)) {
        $media_url = 'https://www.chiro.inceptionimages.com/wp-content/uploads/2023/01/Placeholder-714x250-1.jpg';
    }
    
        // Build replacements based on which template was imported.
        // YouTube and Vimeo templates use different placeholder tokens.
        $replacements = array(
            'https://www.chiro.inceptionimages.com/wp-content/uploads/2023/01/Placeholder-714x250-1.jpg' => $media_url,
            'CLINIC NAME*' => (string) $clinic_name,
            'CITY*'        => (string) $city,
            'STATE*'       => (string) $state,
        );

        // Merge type-specific placeholder keys (include H3 variants)
        if ($is_page) {
            // Page placeholders
            $replacements = array_merge($replacements, array(
                'permalink123-copy' => (string) $slug,
                'metadata*'         => (string) $postmetadata,
                'H1*'               => (string) $h1_for_tokens,
                'H3*'               => (string) $h3_final,
                'C*'                => (string) $pc_combined,
            ));
        } else if ($video_template === 'youtube') {
            $replacements = array_merge($replacements, array(
                'yvideolink'              => (string) $videoUrl,
                'youtubevideotitle'       => (string) $videoTitle,
                'youtubevideodescription' => (string) $videoDescription,
                'permalink345y'           => (string) $slug,
                'ypostmetadata*'          => (string) $postmetadata,
                'YPH1*'                   => (string) $h1_for_tokens,
                'YPH3*'                   => (string) $h3_final,
                'YPC*'                    => (string) $pc_combined,
            ));
        } else if ($video_template === 'vimeo') {
            $replacements = array_merge($replacements, array(
                'vvideolink'              => (string) $videoUrl,
                'vimeovideotitle'         => (string) $videoTitle,
                'vimeovideodescription'   => (string) $videoDescription,
                'permalink345v'           => (string) $slug,
                'vpostmetadata*'          => (string) $postmetadata,
                'VPH1*'                   => (string) $h1_for_tokens,
                'VPH3*'                   => (string) $h3_final,
                'VPC*'                    => (string) $pc_combined,
            ));
        } else {
            // Non-video blog placeholders
            $replacements = array_merge($replacements, array(
                'permalink345-copy' => (string) $slug,
                'postmetadata*'     => (string) $postmetadata,
                'PH1*'              => (string) $h1_for_tokens,
                'PH3*'              => (string) $h3_final,
                'PC*'               => (string) $pc_combined,
            ));
        }
    
        // Apply replacements ONLY to this imported post + its meta (BB data lives in meta)
        blog_maker_apply_replacements_to_post($post_id, $replacements);
        
        $debug_data = get_post_meta($post_id, '_fl_builder_data', true);
        
        // Safely stringify and search (handles arrays/objects/strings)
        $debug_str = is_string($debug_data) ? $debug_data : wp_json_encode($debug_data);
        $has_pc    = (is_string($debug_str) && strpos($debug_str, 'PC*') !== false);

        // Sync BB draft + clear caches AFTER changes
        blog_maker_bb_sync_and_clear_cache($post_id);
        
        // Remove ONLY preview drafts created for this slug and selected content type.
        blog_maker_delete_preview_drafts_for_published_slug($slug, $post_id, $h1, $user_id);

        // Fallback cleanup for preview drafts named like {slug}-preview-xxxxxx.
        // Keep it type-specific so publishing a blog never trashes page drafts, and publishing a page never trashes blog drafts.
        blog_maker_delete_preview_drafts_for_slug_by_type($slug, $post_id, ($is_page ? 'page' : 'post'));
        
        $output[] = get_permalink($post_id);
    }

    // Display success or error message based on the exit status
    switch ($status) {
        case 1:
            echo '<div class="notice notice-error"><p>' . esc_html__( 'ERROR!', 'text-domain' ) . '</p>';
            foreach ($output as $output_line) {
                echo '<p>' . esc_html($output_line) . '</p>';
            }
            echo '</div>';
            
            // Clear the forward slashes if there's an error and the page refreshes
            clearFormFieldsFromSlashes();
            break;
        case 0:
            // Mark that we successfully created a post on this request
            $GLOBALS['blog_maker_just_posted_successfully'] = true;

            // Display success message
            if ( ! empty( $was_scheduled ) ) {
                if ($is_page) {
                    // Custom message for scheduled pages
                    $success_message = '<div class="notice notice-success"><p>' . esc_html__( 'Page is scheduled to be posted!', 'text-domain' ) . '</p>';
                } else {
                    // Custom message for scheduled posts
                    $success_message = '<div class="notice notice-success"><p>' . esc_html__( 'Blog is scheduled to be posted!', 'text-domain' ) . '</p>';
                }
                $success_message .= '<p>Take it in for a moment - <strong>You are amazing!</strong></p>';
            } else {
                // Default published-now success message
                $success_message = '<div class="notice notice-success"><p>' . esc_html__( 'Blog Successfully Posted! ', 'text-domain' ) . '</p>';
                foreach ($output as $output_line) {
                    // Use a regular expression to find URLs in the output_line
                    $output_line = preg_replace(
                        '/(https?:\/\/[^\s]+)/',
                        '<a href="$1" target="_blank" rel="noopener noreferrer">$1</a>',
                        $output_line
                    );
                    $success_message .= wp_kses(
                        '<p>' . $output_line . '</p>',
                        array(
                            'a' => array(
                                'href' => array(),
                                'target' => array(),
                                'rel' => array(),
                            ),
                        )
                    );
                }
                $success_message .= '<p>Take it in for a moment - <strong>You are amazing!</strong></p>';
            }

            $success_message .= '</div>';
            echo $success_message;
            
            // Clear the form fields only after a successful submission
            clearFormFields();
            
            // Call JavaScript function to reset sections
            echo '<script type="text/javascript">
                    window.addEventListener("load", function() {
                        clearFormAndResetSections();
                    });
                  </script>';
            break;
    }
}

// Clear the forward slashes if there's an error and the page refreshes
function clearFormFieldsFromSlashes() {
    // Strip slashes if they exist
    $_POST['p1'] = stripslashes($_POST['p1'] ?? ''); 
    $_POST['p2'] = stripslashes($_POST['p2'] ?? ''); 
    $_POST['p3'] = stripslashes($_POST['p3'] ?? ''); 
    $_POST['p4'] = stripslashes($_POST['p4'] ?? ''); 
    $_POST['p5'] = stripslashes($_POST['p5'] ?? ''); 
    $_POST['p6'] = stripslashes($_POST['p6'] ?? ''); 
    $_POST['p7'] = stripslashes($_POST['p7'] ?? ''); 
    $_POST['p8'] = stripslashes($_POST['p8'] ?? ''); 
    $_POST['p9'] = stripslashes($_POST['p9'] ?? ''); 
    $_POST['p10'] = stripslashes($_POST['p10'] ?? ''); 
    $_POST['p11'] = stripslashes($_POST['p11'] ?? ''); 
    $_POST['p12'] = stripslashes($_POST['p12'] ?? ''); 
    $_POST['p13'] = stripslashes($_POST['p13'] ?? ''); 
    $_POST['p14'] = stripslashes($_POST['p14'] ?? ''); 
    $_POST['p15'] = stripslashes($_POST['p15'] ?? ''); 
    $_POST['p16'] = stripslashes($_POST['p16'] ?? ''); 
    $_POST['p17'] = stripslashes($_POST['p17'] ?? ''); 
    $_POST['h1'] = stripslashes($_POST['h1'] ?? ''); 
    $_POST['postmetadata'] = stripslashes($_POST['postmetadata'] ?? ''); 
    $_POST['slug'] = stripslashes($_POST['slug'] ?? ''); 
    $_POST['h3'] = stripslashes($_POST['h3'] ?? ''); 
    $_POST['secondh3'] = stripslashes($_POST['secondh3'] ?? ''); 
    $_POST['thirdh3'] = stripslashes($_POST['thirdh3'] ?? ''); 
    $_POST['fourthh3'] = stripslashes($_POST['fourthh3'] ?? ''); 
    $_POST['fifthh3'] = stripslashes($_POST['fifthh3'] ?? ''); 
    $_POST['sixthh3'] = stripslashes($_POST['sixthh3'] ?? ''); 
    $_POST['seventhh3'] = stripslashes($_POST['seventhh3'] ?? ''); 
    $_POST['eighthh3'] = stripslashes($_POST['eighthh3'] ?? ''); 
    $_POST['ninthh3'] = stripslashes($_POST['ninthh3'] ?? ''); 
    $_POST['tenthh3'] = stripslashes($_POST['tenthh3'] ?? ''); 
    $_POST['eleventhh3'] = stripslashes($_POST['eleventhh3'] ?? ''); 
    $_POST['twelfthh3'] = stripslashes($_POST['twelfthh3'] ?? ''); 
    $_POST['thirteenthh3'] = stripslashes($_POST['thirteenthh3'] ?? ''); 
    $_POST['fourteenthh3'] = stripslashes($_POST['fourteenthh3'] ?? ''); 
    $_POST['fifteenthh3'] = stripslashes($_POST['fifteenthh3'] ?? ''); 
    $_POST['sixteenthh3'] = stripslashes($_POST['sixteenthh3'] ?? ''); 
}

// Clear the form fields after the form is submitted
function clearFormFields() {
    $_POST['h1'] = '';
    $_POST['postmetadata'] = '';
    $_POST['slug'] = '';
    $_POST['p1'] = '';
    $_POST['h3'] = '';
    $_POST['p2'] = '';
    $_POST['secondh3'] = '';
    $_POST['p3'] = '';
    $_POST['thirdh3'] = '';
    $_POST['p4'] = '';
    $_POST['fourthh3'] = '';
    $_POST['p5'] = '';
    $_POST['fifthh3'] = '';
    $_POST['p6'] = '';
    $_POST['sixthh3'] = '';
    $_POST['p7'] = '';
    $_POST['seventhh3'] = '';
    $_POST['p8'] = '';
    $_POST['eighthh3'] = '';
    $_POST['p9'] = '';
    $_POST['ninthh3'] = '';
    $_POST['p10'] = '';
    $_POST['tenthh3'] = '';
    $_POST['p11'] = '';
    $_POST['eleventhh3'] = '';
    $_POST['p12'] = '';
    $_POST['twelfthh3'] = '';
    $_POST['p13'] = '';
    $_POST['thirteenthh3'] = '';
    $_POST['p14'] = '';
    $_POST['fourteenthh3'] = '';
    $_POST['p15'] = '';
    $_POST['fifteenthh3'] = '';
    $_POST['p16'] = '';
    $_POST['sixteenthh3'] = '';
    $_POST['p17'] = '';
    $_POST['videoUrl'] = '';
    $_POST['videoTitle'] = '';
    $_POST['videoDescription'] = '';
    
    // Reset "Post To:" back to the default behavior.
    // - If the dropdown is shown, your rendering logic will default to Main Blog when $_POST is empty.
    // - If only one destination exists, your hidden input logic will choose sole_destination_id.
    unset($_POST['post_destination']);
}

/**
 * Deletes draft preview PAGES created by Preview (slug pattern: {slug}-preview-xxxxxx)
 * Keeps the published page ($published_post_id) and only deletes drafts.
 */
function blog_maker_delete_preview_page_drafts_for_published_slug($slug, $published_post_id) {
    $slug = sanitize_title($slug);
    if (empty($slug)) {
        return;
    }

    $q = new WP_Query(array(
        'post_type'      => 'page',
        'post_status'    => 'draft',
        'posts_per_page' => 50,
        'fields'         => 'ids',
        // Matches your preview.php behavior: $desired_slug . '-preview-' . random
        'name__like'     => $slug . '-preview-',
        'orderby'        => 'date',
        'order'          => 'DESC',
    ));

    if (!empty($q->posts)) {
        foreach ($q->posts as $draft_id) {
            $draft_id = (int) $draft_id;
            if ($draft_id && $draft_id !== (int) $published_post_id) {
                wp_trash_post($draft_id); // trash the draft
            }
        }
    }
}

/**
 * Deletes draft previews created by Preview for one selected content type only.
 * Matches preview slugs like {slug}-preview-xxxxxx.
 */
function blog_maker_delete_preview_drafts_for_slug_by_type($slug, $published_post_id, $post_type) {
    $slug = sanitize_title($slug);
    $post_type = ($post_type === 'page') ? 'page' : 'post';

    if (empty($slug)) {
        return;
    }

    $q = new WP_Query(array(
        'post_type'      => $post_type,
        'post_status'    => array('draft', 'pending'),
        'posts_per_page' => 100,
        'fields'         => 'ids',
        'name__like'     => $slug . '-preview-',
        'orderby'        => 'date',
        'order'          => 'DESC',
    ));

    if (!empty($q->posts)) {
        foreach ($q->posts as $draft_id) {
            $draft_id = (int) $draft_id;
            if ($draft_id && $draft_id !== (int) $published_post_id) {
                wp_trash_post($draft_id);
            }
        }
    }
}
