<?php

if ( isset( $_POST['action'] ) && $_POST['action'] === 'lp-maker' ) {
        lp_maker_action();
}
?>

<div class="wrap">
    <h1>Inception Landing Page Maker</h1>
    <p>Please fill out all fields below to generate your landing page.</p>
    <form method="post" action="" enctype="multipart/form-data">
    <style>
        .alt-text-input-wrapper {
            display: flex;
            justify-content: center; /* Center horizontally */
        }
        
        .alt-text-input-container {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
            margin-top: 20px;
        }
        
        .alt-text-input-container .input-label {
            margin-right: 20px;
            min-width: 200px; /* Adjust the label width as needed */
        }
        
        .alt-text-input-container .input-field {
            flex: 1; /* Use flex to expand the input field */
            min-width: 0; /* Allow the input field to shrink if necessary */
            width: 400px; /* Set the width to 400px */
        }
        
        /* Add CSS for consistent label width and input width */
        .input-container {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
            margin-top: 20px;
        }
    
        .input-label {
            margin-right: 20px;
            min-width: 200px; /* Adjust the label width as needed */
        }
    
        .input-field {
            flex: 0;
            min-width: 400px; /* Adjust the input field minimum width as needed */
            width: calc(100% + 300px);
        }
        
        .input-field.button {
            width: auto; /* Set the width as per your design */
            display: inline-block; /* Set as inline-block to match other buttons */
        }
        
        .lp-input-container {
            text-align: center; /* Center text horizontally within the container */
        }
        
        .lp-input-field {
            width: 60%; /* Set a width for the dropdown */
            margin: 0 auto; /* Center the dropdown within its container */
            display: block; /* Make it a block-level element to center with margin */
        }

        #wpfooter {
            display: none !important;  /* Hide the WP footer on the page */
        }
        
    </style>

    <div class="lp-input-container">
        <label for="lpType" class="input-label"><strong>Type of Landing Page:</strong></label>
        <select name="lpType" id="lpType" class="lp-input-field">
            <option value="" selected>-- Select a Landing Page Type --</option>
            <option value="custom">*** CUSTOM ***</option>
            <option value="acupuncture">Acupuncture</option>
            <option value="allergies">Allergies</option>
            <option value="animal-chiro">Animal Chiropractic</option>
            <option value="auto-injury">Auto Injury</option>
            <option value="back-pain">Back Pain</option>
            <option value="hormone-replacement-female">Bio-Identical Hormone Replacement Therapy - FEMALE</option>
            <option value="hormone-replacement-general">Bio-Identical Hormone Replacement Therapy - GENERAL</option>
            <option value="hormone-replacement-male">Bio-Identical Hormone Replacement Therapy - MALE</option>
            <option value="chiropractic">Chiropractic</option>
            <option value="muscles">Chiropractic - Muscles</option>
            <option value="chronic-pain">Chronic Pain</option>
            <option value="decompression">Decompression</option>
            <option value="dental">Dental</option>
            <option value="depression">Depression</option>
            <option value="digestive-health">Digestive Health</option>
            <option value="dot-exams">DOT Exams</option>
            <option value="dot-exams-xl">DOT Exams - XL</option>
            <option value="emsculpt-neo">EMSCULPT neo</option>
            <option value="erectile-dysfunction">Erectile Dysfunction</option>
            <option value="functional-medicine">Functional Medicine</option>
            <option value="headaches">Headaches</option>
            <option value="iv-drip-therapy">IV Drip Therapy</option>
            <option value="knee-pain">Knee Pain</option>
            <option value="massage-therapy">Massage Therapy</option>
            <option value="mls-laser">MLS Laser</option>
            <option value="neck-pain">Neck Pain</option>
            <option value="neuropathy">Neuropathy</option>
            <option value="nucca-chiropractic">Nucca Chiropractic</option>
            <option value="nutrition">Nutrition</option>
            <option value="ozone-therapy">Ozone Therapy</option>
            <option value="pediatrics">Pediatrics</option>
            <option value="plantar-fasciitis">Plantar Fasciitis</option>
            <option value="posture">Posture</option>
            <option value="pregnancy">Pregnancy</option>
            <option value="prp-treatment">PRP Treatment</option>
            <option value="red-light-therapy">Red Light Therapy</option>
            <option value="sciatica">Sciatica</option>
            <option value="scoliosis">Scoliosis</option>
            <option value="shockwave-therapy">Shockwave Therapy</option>
            <option value="shoulder-pain">Shoulder Pain</option>
            <option value="softwave">SoftWave</option>
            <option value="stem-cell">Stem Cell</option>
            <option value="tmj">TMJ</option>
            <option value="wl-chirothin">Weight Loss - Chirothin</option>
            <option value="weight-loss">Weight Loss</option>
        </select>
    </div>

    <div class="input-container">
		<label for="newSlug" class="input-label"><strong>New Slug: (No Spaces<br>or Slashes Before or After)</strong></label>
		<input type="text" name="newSlug" id="newSlug" class="input-field" value="<?= esc_attr($_POST['newSlug'] ?? '') ?>">
                
        <label for="typeOfLP" class="input-label" style="margin-left: 80px;"><strong>Type of Landing Page:</strong></label>
        <select name="typeOfLP" id="typeOfLP" class="typeOfLP-input-field" style="margin-left: -60px;">
            <option value="lp">Regular LP</option>
            <option value="facebook">Facebook</option>
            <option value="google">Google</option>
        </select>
    </div>

    <div class="input-container">
        <label for="clinicName" class="input-label"><strong>Clinic Name:</strong></label>
        <input type="text" name="clinicName" id="clinicName" class="input-field" value="<?= esc_attr($_POST['clinicName'] ?? '') ?>">
    </div>
    
    <div class="input-container">
        <label for="address" class="input-label"><strong>Address:</strong></label>
        <input type="text" name="address" id="address" class="input-field" value="<?= esc_attr($_POST['address'] ?? '') ?>">
    </div>
    
    <div class="input-container">
        <label for="city" class="input-label"><strong>City:</strong></label>
        <input type="text" name="city" id="city" class="input-field" value="<?= esc_attr($_POST['city'] ?? '') ?>">
        
        <label for="state" class="input-label" style="margin-left: 20px;"><strong>State:</strong></label>
        <input type="text" name="state" id="state" class="input-field-state" style="margin-left: -175px; width: 400px;" value="<?= esc_attr($_POST['state'] ?? '') ?>">
        
        <label for="zip" class="input-label" style="margin-left: 20px;"><strong>ZIP:</strong></label>
        <input type="text" name="zip" id="zip" class="input-field-zip" style="margin-left: -175px; width: 400px;" value="<?= esc_attr($_POST['zip'] ?? '') ?>">
    </div>
    
    <div class="input-container">
        <label for="doctor_name" class="input-label"><strong>Doctor's Full Name:</strong></label>
        <input type="text" name="doctor_name" id="doctor_name" class="input-field" value="<?= esc_attr($_POST['doctor_name'] ?? '') ?>">
    </div>
    
    <div class="input-container">
        <label for="phone" class="input-label"><strong>Phone Number:<br>(In Style of (000) 000-0000)</strong></label>
        <input type="text" name="phone" id="phone" class="input-field" value="<?= esc_attr($_POST['phone'] ?? '') ?>">
    </div>
    
    <div class="input-container">
        <label for="hl_id" class="input-label"><strong>HL Form ID:</strong></label>
        <input type="text" name="hl_id" id="hl_id" class="input-field" value="<?= esc_attr($_POST['hl_id'] ?? '') ?>">
    </div>
    
    <div class="input-container">
        <label for="special" class="input-label"><strong>Special Offer:</strong></label>
        <input type="text" name="special" id="special" class="input-field" value="<?= esc_attr($_POST['special'] ?? '') ?>">
        
        <label for="price" class="input-label" style="margin-left: 20px;"><strong>Price (Include $ If Needed):</strong></label>
        <input type="text" name="price" id="price" class="input-field-price" style="margin-left: -10px; width: 400px;" value="<?= esc_attr($_POST['price'] ?? '') ?>">
    </div>
    
    <div class="input-container">
        <label for="doctor_image" class="input-label"><strong>Upload Doctor Photo: <br> (Must be .jpeg, .jpg, .png,<br>.gif, or .webp)</strong></label>
        <input type="file" name="doctor_image" id="doctor_image" class="input-field" style="display: none;">
        <label for="doctor_image" class="input-field button" id="image-label">Upload Doctor Photo</label>
        <label for="selectedImage" class="input-label" style="margin-left: 20px;"><strong>Don't Have an Image For the Doctor?<br>Select One From The Media Library:</strong></label>
    
        <!-- Dropdown for selecting images from the Media Library -->
        <select name="selectedImage" id="selectedImage" class="input-field" style="margin-left: -10px;">
            <option value="">-- Select an Image --</option>
            <?php
            // Get the attachment posts from the Media Library
            $args = array(
                'post_type' => 'attachment',
                'post_mime_type' => 'image',
                'posts_per_page' => -1,
                'orderby'        => 'post_title', // Sort by post title
                'order'          => 'ASC',        // Sort in ascending order
                'post_parent' => null, // Exclude attachments attached to posts
            );
    
            $attachments = get_posts($args);
    
            // Display each attachment as an option in the dropdown, excluding those with a file size of 0
            foreach ($attachments as $attachment) {
                $image_url = wp_get_attachment_url($attachment->ID);
                
                // Check if the file size is greater than 0
                $file_size = filesize(get_attached_file($attachment->ID));
                
                if ($file_size > 0) {
                    echo '<option value="' . esc_url($image_url) . '">' . esc_html($attachment->post_title) . '</option>';
                }
            }
            ?>
        </select>
        <input type="hidden" name="selectedImageInput" id="selectedImageInput" value="">
    </div>
    <!-- Image preview container with centering -->
    <div id="imagePreview" class="image-preview">
        <label for="imagePreview" class="text" id="image-preview" style="display: none;"><strong>Doctor Image Preview:</strong></label><br>
        <img id="selectedImagePreview" src="" alt="Selected Image" height="220">
        <div id="imageDetails" class="image-details" style="display: none; align-items: center; text-align: center; margin-top: 10px;"></div>
    </div>

    <div class="alt-text-input-wrapper">
        <div class="alt-text-input-container" id="altDoctorTextFieldContainer" style="display: none;">
            <label for="alt_text_doctor" class="input-label"><strong>Alternate Text & Title for Doctor Photo:</strong></label>
            <input type="text" name="alt_text_doctor" id="alt_text_doctor" class="input-field" style="margin-right: 100px;" value="<?= esc_attr($_POST['alt_text_doctor'] ?? '') ?>"><br><br><br>
        </div>
    </div>
    
    <style>
        /* Center the image both vertically and horizontally */
        .image-preview {
            display: flex;
            flex-direction: column; /* Place text above the image */
            justify-content: center;
            align-items: center;
            margin-bottom: 20px;
        }
        
    </style>

<script>
    // Get references to the file input and image preview element
    const imageSearchInput = document.getElementById('imageSearch');
    const fileInput = document.getElementById('doctor_image');
    const selectedImage = document.getElementById('selectedImage');
    const selectedImagePreview = document.getElementById('selectedImagePreview');
    const imageLabel = document.getElementById('image-preview');
    const selectedImageInput = document.getElementById('selectedImageInput');

    // Store a reference to the original options
    const originalOptions = [...selectedImage.options];
    
    // Variable to store the last selected value
    let lastSelectedValue = '';
    
    // Store the image data
    const imageData = <?php echo json_encode($groupedAndSortedOptions); ?>;

    // Function to update the image preview based on the last selected value
    function updateImagePreview() {
        // Check if a file is selected
        if (fileInput.files.length > 0) {
            const file = fileInput.files[0];
            const imageURL = URL.createObjectURL(file);

            // Update the image preview source
            selectedImagePreview.src = imageURL;
            selectedImagePreview.style.display = 'block'; // Show the image preview

            // Show the image label
            imageLabel.style.display = 'block';

            // Update the last selected value
            lastSelectedValue = imageURL;
            
            // Reset the dropdown to "Select an Image"
            selectedImage.value = '';
            
            // Show the alt text field when an image is uploaded
            altDoctorTextFieldContainer.style.display = 'block';

        } else {
            // If no file is selected, use the last selected value from the dropdown
            const selectedValue = selectedImage.value;

            if (!selectedValue || selectedValue === '') {
                selectedImagePreview.src = ''; // Clear the image preview source
                selectedImagePreview.style.display = 'none'; // Hide the image preview

                // Hide the image label
                imageLabel.style.display = 'none';
                
                // Hide the alt text field when no image is selected
                altDoctorTextFieldContainer.style.display = 'none';
                
                // Display image file name and dimensions
                displayImageDetails(selectedValue);
            } else {
                selectedImagePreview.src = selectedValue;
                selectedImagePreview.style.display = 'block'; // Show the image preview

                // Show the image label
                imageLabel.style.display = 'block';

                // Update the hidden input field with the selected image data (URL)
                document.getElementById('selectedImageInput').value = selectedValue;
                
                // Update the last selected value
                lastSelectedValue = selectedValue;
                
                // Hide the alt text field when an image is selected from the dropdown
                altDoctorTextFieldContainer.style.display = 'none';
                
                // Clear image details when no image is selected
                clearImageDetails();
            }
        }
    }

    // Function to display image details (file name and dimensions)
    async function displayImageDetails(imageURL) {
        const fileName = getFileName(imageURL);
        const dimensions = await getImageDimensions(imageURL);
    
        // Display image details underneath the image preview
        const imageDetails = document.getElementById('imageDetails');
        imageDetails.innerHTML = `<strong>File Name:</strong> ${fileName} <br> <strong>Dimensions:</strong> ${dimensions}`;
        imageDetails.style.display = 'block';
    }


    // Function to clear image details
    function clearImageDetails() {
        // Hide image details when no image is selected
        const imageDetails = document.getElementById('imageDetails');
        imageDetails.style.display = 'none';
        imageDetails.innerHTML = '';
    }

    // Function to get the file name from the image URL
    function getFileName(imageURL) {
        const urlParts = imageURL.split('/');
        return urlParts[urlParts.length - 1];
    }

    // Function to get the dimensions of the image from the URL
    function getImageDimensions(imageURL) {
        return new Promise((resolve) => {
            const img = new Image();
            img.onload = function () {
                resolve(`${img.width} x ${img.height}`);
            };
            img.src = imageURL;
        });
    }



// Add a click event listener to the image input label to allow reselection
document.getElementById('image-label').addEventListener('click', function () {
    fileInput.value = null; // Clear the file input
    updateImagePreview();
});
    
    // Add an event listener to the file input
    fileInput.addEventListener('change', updateImagePreview);

    // Add an event listener to the select element
    selectedImage.addEventListener('change', function () {
        // Reset the file input by clearing its selected files
        fileInput.value = null;

        // Update the image preview source if a value is selected
        updateImagePreview();
        
        // Get the selected value (image URL)
        const selectedValue = selectedImage.value;

        // Update the image preview source if a value is selected
        if (selectedValue) {
            selectedImagePreview.src = selectedValue;
            selectedImagePreview.style.display = 'block'; // Show the image preview
    
            // Show the image label
            imageLabel.style.display = 'block';
    
            // Update the hidden input field with the selected image URL
            document.getElementById('selectedImageInput').value = selectedValue;
            
            // Hide the alt text field when an image is selected from the dropdown
            altDoctorTextFieldContainer.style.display = 'none';
            
            // Display image details if a value is selected
            displayImageDetails(selectedValue);
        } else {
            selectedImagePreview.src = ''; // Clear the image preview source
            selectedImagePreview.style.display = 'none'; // Hide the image preview
    
            // Hide the image label
            imageLabel.style.display = 'none';
    
            // Update the hidden input field to an empty value
            document.getElementById('selectedImageInput').value = '';
            
            // Show the alt text field when no image is selected
            altDoctorTextFieldContainer.style.display = 'block';
            
            // Clear image details when no image is selected
            clearImageDetails();

        }
    });

    // Call the function initially to hide the preview and label when the page first loads
    updateImagePreview();

</script>

    <style>
        .button {
            text-align: center; /* Center text horizontally */
            line-height: inherit; /* Maintain the same line height as the parent container */
        }
    </style>
    
    <script>
        // Get references to the file input and the label
        const fileInput = document.getElementById('image');
        const imageLabel = document.getElementById('image-label');
    
        // Add an event listener to the file input
        fileInput.addEventListener('change', function (e) {
            const selectedFile = e.target.files[0]; // Get the selected file
    
            if (selectedFile) {
                // Display the file name in the label
                imageLabel.textContent = selectedFile.name;
            } else {
                // No file selected, reset the label
                imageLabel.textContent = 'Upload Image';
            }
        });
    </script>
    
    <div class="input-container">
    <label for="clinicLogo" class="input-label"><strong>Upload Clinic Logo: <br> (Must be .jpeg, .jpg, .png,<br>.gif, or .webp)</strong></label>
    <input type="file" name="clinicLogo" id="clinicLogo" class="input-field" style="display: none;">
    <label for="clinicLogo" class="input-field button" id="clinic-logo-label">Upload Clinic Logo</label>
    <label for="selectedClinicLogo" class="input-label" style="margin-left: 20px;"><strong>Don't Have a Logo?<br>Select One From The Media Library:</strong></label>

    <!-- Dropdown for selecting images from the Media Library -->
    <select name="selectedClinicLogo" id="selectedClinicLogo" class="input-field" style="margin-left: -10px;">
        <option value="">-- Select a Logo --</option>
        <?php
        // Get the attachment posts from the Media Library
        $logoArgs = array(
            'post_type' => 'attachment',
            'post_mime_type' => 'image',
            'posts_per_page' => -1,
            'orderby'        => 'post_title', // Sort by post title
            'order'          => 'ASC',        // Sort in ascending order
            'post_parent' => null, // Exclude attachments attached to posts
        );

        $logoAttachments = get_posts($logoArgs);

        // Display each attachment as an option in the dropdown
        foreach ($logoAttachments as $logoAttachment) {
            $logo_url = wp_get_attachment_url($logoAttachment->ID);
            
            // Check if the file size is greater than 0
            $logo_file_size = filesize(get_attached_file($logoAttachment->ID));
            
            if ($logo_file_size > 0) {
                echo '<option value="' . esc_url($logo_url) . '">' . esc_html($logoAttachment->post_title) . '</option>';
            }
        }
        ?>
    </select>
    <input type="hidden" name="selectedClinicLogoInput" id="selectedClinicLogoInput" value="">
    </div>
    <!-- Image preview container with centering -->
    <div id="clinicLogoPreview" class="image-preview">
        <label for="clinicLogoPreview" class="text" id="clinic-logo-preview" style="display: none;"><strong>Clinic Logo Preview:</strong></label><br>
        <img id="selectedClinicLogoPreview" src="" alt="Selected Logo" height="220">
        <div id="clinicLogoDetails" class="image-details" style="display: none; align-items: center; text-align: center; margin-top: 10px;"></div>
    </div>
    
    <div class="alt-text-input-wrapper">
        <div class="alt-text-input-container" id="altClinicTextFieldContainer" style="display: none;">
            <label for="clinicAltText" class="input-label"><strong>Alternate Text & Title for Clinic Logo:</strong></label>
            <input type="text" name="clinicAltText" id="clinicAltText" class="input-field" style="margin-right: 100px;" value="<?= esc_attr($_POST['clinicAltText'] ?? '') ?>"><br><br><br>
        </div>
    </div>
    
    <style>
        /* Center the image both vertically and horizontally */
        .image-preview {
            display: flex;
            flex-direction: column; /* Place text above the image */
            justify-content: center;
            align-items: center;
        }
    </style>
    
<script>
    // Get references to the file input and image preview element
    const clinicLogoInput = document.getElementById('clinicLogo');
    const selectedClinicLogo = document.getElementById('selectedClinicLogo');
    const selectedClinicLogoPreview = document.getElementById('selectedClinicLogoPreview');
    const clinicLogoLabel = document.getElementById('clinic-logo-preview');
    const selectedClinicLogoInput = document.getElementById('selectedClinicLogoInput');

    // Store a reference to the original options
    const originalClinicLogoOptions = [...selectedClinicLogo.options];

    // Variable to store the last selected value
    let lastSelectedClinicLogoValue = '';

    // Store the image data
    const clinicLogoData = <?php echo json_encode($clinicLogoGroupedAndSortedOptions); ?>;
    
    // Function to display image details for clinic logo
    async function displayClinicLogoDetails(imageURL) {
        const fileName = getFileName(imageURL);
        const dimensions = await getImageDimensions(imageURL);

        // Display image details underneath the clinic logo preview
        const clinicLogoDetails = document.getElementById('clinicLogoDetails');
        clinicLogoDetails.innerHTML = `<strong>File Name:</strong> ${fileName} <br> <strong>Dimensions:</strong> ${dimensions}`;
        clinicLogoDetails.style.display = 'block';
    }


    // Function to update the image preview based on the last selected value
    function updateClinicLogoPreview() {
        const selectedValue = selectedClinicLogo.value;

        if (selectedValue) {
            selectedClinicLogoPreview.src = selectedValue;
            selectedClinicLogoPreview.style.display = 'block'; // Show the image preview

            // Show the image label
            clinicLogoLabel.style.display = 'block';

            // Update the hidden input field with the selected image data (URL)
            document.getElementById('selectedClinicLogoInput').value = selectedValue;
            
            // Display clinic logo details if a value is selected
            displayClinicLogoDetails(selectedValue);
            
            // Hide the alt text field when an image is selected from the dropdown
            document.getElementById('altClinicTextFieldContainer').style.display = 'none';

        } else {
            selectedClinicLogoPreview.src = ''; // Clear the image preview source
            selectedClinicLogoPreview.style.display = 'none'; // Hide the image preview

            // Hide the image label
            clinicLogoLabel.style.display = 'none';

            // Update the hidden input field to an empty value
            document.getElementById('selectedClinicLogoInput').value = '';
            
            // Show the alt text field when an image is uploaded
            document.getElementById('altClinicTextFieldContainer').style.display = clinicLogoInput.files.length ? 'block' : 'none';
            
            // Clear clinic logo details when no image is selected
            clearClinicLogoDetails();
        }
        
        // Function to clear clinic logo details
        function clearClinicLogoDetails() {
            // Hide clinic logo details when no image is selected
            const clinicLogoDetails = document.getElementById('clinicLogoDetails');
            clinicLogoDetails.style.display = 'none';
            clinicLogoDetails.innerHTML = '';
        }

        // Update the last selected value
        lastSelectedClinicLogoValue = selectedValue;
    }

    // Add an event listener to the file input
    clinicLogoInput.addEventListener('change', function () {
        const selectedFile = clinicLogoInput.files[0]; // Get the selected file

        if (selectedFile) {
            const imageURL = URL.createObjectURL(selectedFile);

            // Update the logo preview source
            selectedClinicLogoPreview.src = imageURL;
            selectedClinicLogoPreview.style.display = 'block'; // Show the image preview

            // Show the image label
            clinicLogoLabel.style.display = 'block';

            // Update the last selected value
            lastSelectedClinicLogoValue = imageURL;

            // Reset the dropdown to "Select a Logo"
            selectedClinicLogo.value = '';
            
            // Show the alt text field when an image is uploaded
            document.getElementById('altClinicTextFieldContainer').style.display = 'block';

        } else {
            // If no file is selected, use the last selected value from the dropdown
            const selectedValue = selectedClinicLogo.value;

            if (!selectedValue || selectedValue === '') {
                selectedClinicLogoPreview.src = ''; // Clear the image preview source
                selectedClinicLogoPreview.style.display = 'none'; // Hide the image preview

                // Hide the image label
                clinicLogoLabel.style.display = 'none';
            } else {
                selectedClinicLogoPreview.src = selectedValue;
                selectedClinicLogoPreview.style.display = 'block'; // Show the image preview

                // Show the image label
                clinicLogoLabel.style.display = 'block';

                // Update the hidden input field with the selected image data (URL)
                document.getElementById('selectedClinicLogoInput').value = selectedValue;

                // Update the last selected value
                lastSelectedClinicLogoValue = selectedValue;
            }
        }
    });

    // Add an event listener to the select element
    selectedClinicLogo.addEventListener('change', function () {
        // Reset the file input by clearing its selected files
        clinicLogoInput.value = null;

        // Update the logo preview source if a value is selected
        updateClinicLogoPreview();
    });

    // Call the function initially to hide the preview and label when the page first loads
    updateClinicLogoPreview();
</script>

    <div class="input-container">
        <label for="testimonial_name1" class="input-label"><strong>Testimonial Name 1:</strong></label>
        <input type="text" name="testimonial_name1" id="testimonial_name1" class="input-field" value="<?= esc_attr($_POST['testimonial_name1'] ?? '') ?>">
    </div>
    
    <div class="input-container">
        <label for="testimonial1" class="input-label"><strong>Testimonial 1:</strong></label>
        <textarea name="testimonial1" id="testimonial1" class="input-field" rows="5"><?= esc_textarea($_POST['testimonial1'] ?? '') ?></textarea>
    </div>
    
    <div class="input-container">
        <label for="testimonial_name2" class="input-label"><strong>Testimonial Name 2:</strong></label>
        <input type="text" name="testimonial_name2" id="testimonial_name2" class="input-field" value="<?= esc_attr($_POST['testimonial_name2'] ?? '') ?>">
    </div>
    
    <div class="input-container">
        <label for="testimonial2" class="input-label"><strong>Testimonial 2:</strong></label>
        <textarea name="testimonial2" id="testimonial2" class="input-field" rows="5"><?= esc_textarea($_POST['testimonial2'] ?? '') ?></textarea>
    </div>
    
    <div class="input-container">
        <label for="testimonial_name3" class="input-label"><strong>Testimonial Name 3:</strong></label>
        <input type="text" name="testimonial_name3" id="testimonial_name3" class="input-field" value="<?= esc_attr($_POST['testimonial_name3'] ?? '') ?>">
    </div>
    
    <div class="input-container">
        <label for="testimonial3" class="input-label"><strong>Testimonial 3:</strong></label>
        <textarea name="testimonial3" id="testimonial3" class="input-field" rows="5"><?= esc_textarea($_POST['testimonial3'] ?? '') ?></textarea>
    </div>
    
    <div class="input-container">
        <label for="google_map" class="input-label"><strong>Google Maps Embed Code:</strong></label>
        <textarea name="google_map" id="google_map" class="input-field" rows="5"><?= esc_textarea($_POST['google_map'] ?? '') ?></textarea>
    </div>

        <div id="customLPContainer">
            <br>
            <br>
            <h1><center><strong>Custom Landing Page Information:</strong></center></h1>
            <div class="input-container">
            	<label for="lpOptimization" class="input-label"><strong>LP Optimization:</strong></label>
            	<input type="text" name="lpOptimization" id="lpOptimization" class="input-field" value="<?= esc_attr($_POST['lpOptimization'] ?? '') ?>">
            </div>

            <div class="input-container">
                <label for="postMetadata" class="input-label"><strong>Post Metadata:</strong></label>
                <textarea name="postMetadata" id="postMetadata" class="input-field" rows="5"><?= esc_textarea($_POST['postMetadata'] ?? '') ?></textarea>
            </div>
        
            <div class="input-container">
                <label for="mobileBackground" class="input-label"><strong>Upload Background: <br> (Must be .jpeg, .jpg, .png,<br>.gif, or .webp)</strong></label>
                <input type="file" name="mobileBackground" id="mobileBackground" class="input-field" style="display: none;">
                <label for="mobileBackground" class="input-field button" id="mobile-background-label">Upload Background</label>
                <label for="selectedmobileBackground" class="input-label" style="margin-left: 20px;"><strong>Don't Have a Background?<br>Select One From Our Existing Library:</strong></label>
            
                <!-- Dropdown for selecting images from the LP List -->
                <select name="selectedmobileBackground" id="selectedmobileBackground" class="input-field" style="margin-left: -10px;">
                    <option value="">-- Select a Background --</option>
                    <?php
                    // Include the file lp-photo-list.php
                    $images = include 'lp-photo-list.php';
                    
                    // Create an array to hold sorted options
                    $sortedOptions = [];
                
                    // Assuming lp-photo-list.php defines an array $images with the structure you provided
                    if (isset($images) && is_array($images)) {
                        foreach ($images as $imageName => $imageData) {
                            if ($imageData['type'] === 'Images') { // Check if the type is 'Images'
                                // Store the image data in the sorted array
                                $sortedOptions[] = [
                                    'id' => esc_url($imageData['id']),
                                    'label' => esc_html($imageData['label']),
                                ];
                            }
                        }
                
                        // Sort the options alphabetically by label
                        usort($sortedOptions, function ($a, $b) {
                            return strcmp($a['label'], $b['label']);
                        });
                
                        // Iterate through the sorted options to output the HTML
                        foreach ($sortedOptions as $option) {
                            echo '<option value="' . $option['id'] . '">' . $option['label'] . '</option>';
                        }
                    }
                    ?>
                </select>

                <input type="hidden" name="selectedmobileBackgroundData" id="selectedmobileBackgroundData" value="">
                </div>
                <!-- Image preview container with centering -->
                <div id="mobileBackgroundPreview" class="image-preview">
                    <label for="mobileBackgroundPreview" class="text" id="mobile-background-preview" style="display: none;"><strong>Background Preview:</strong></label><br>
                    <img id="selectedmobileBackgroundPreview" src="" alt="Selected Mobile Background" height="220">
                </div>
                
                <div class="alt-text-input-wrapper">
                    <div class="input-container">
                        <label for="mBkgrdAltText" class="input-label"><strong>Alternate Text & Title for Background:</strong></label>
                        <input type="text" name="mBkgrdAltText" id="mBkgrdAltText" class="input-field" style="margin-right: 100px;" value="<?= esc_attr($_POST['mBkgrdAltText'] ?? '') ?>"><br><br><br>
                    </div>
                </div>
                
                <style>
                    /* Center the image both vertically and horizontally */
                    .image-preview {
                        display: flex;
                        flex-direction: column; /* Place text above the image */
                        justify-content: center;
                        align-items: center;
                    }
                </style>
                
                <script>
                    // Get references to the file input and image preview element
                    const mobileBackgroundInput = document.getElementById('mobileBackground');
                    const selectedmobileBackground = document.getElementById('selectedmobileBackground');
                    const selectedmobileBackgroundPreview = document.getElementById('selectedmobileBackgroundPreview');
                    const mobileBackgroundLabel = document.getElementById('mobile-background-preview');
                    const selectedmobileBackgroundData = document.getElementById('selectedmobileBackgroundData');
                
                    // Store a reference to the original options
                    const originalmobileBackgroundOptions = [...selectedmobileBackground.options];
                
                    // Variable to store the last selected value
                    let lastSelectedmobileBackgroundValue = '';
                
                    // Store the image data
                    const mobileBackgroundData = <?php echo json_encode($mobileBackgroundGroupedAndSortedOptions); ?>;
                
                    // Function to update the image preview based on the last selected value
                    function updatemobileBackgroundPreview() {
                        const selectedValue = selectedmobileBackground.value;
                
                        if (selectedValue) {
                            selectedmobileBackgroundPreview.src = selectedValue;
                            selectedmobileBackgroundPreview.style.display = 'block'; // Show the image preview
                
                            // Show the image label
                            mobileBackgroundLabel.style.display = 'block';
                
                            // Update the hidden input field with the selected image data (URL)
                            document.getElementById('selectedmobileBackgroundData').value = selectedValue;
                        } else {
                            selectedmobileBackgroundPreview.src = ''; // Clear the image preview source
                            selectedmobileBackgroundPreview.style.display = 'none'; // Hide the image preview
                
                            // Hide the image label
                            mobileBackgroundLabel.style.display = 'none';
                
                            // Update the hidden input field to an empty value
                            document.getElementById('selectedmobileBackgroundData').value = '';
                        }
                
                        // Update the last selected value
                        lastSelectedmobileBackgroundValue = selectedValue;
                    }
                
                    // Add an event listener to the file input
                    mobileBackgroundInput.addEventListener('change', function () {
                        const selectedFile = mobileBackgroundInput.files[0]; // Get the selected file
                
                        if (selectedFile) {
                            const imageURL = URL.createObjectURL(selectedFile);
                
                            // Update the mobile background preview source
                            selectedmobileBackgroundPreview.src = imageURL;
                            selectedmobileBackgroundPreview.style.display = 'block'; // Show the image preview
                
                            // Show the image label
                            mobileBackgroundLabel.style.display = 'block';
                
                            // Update the last selected value
                            lastSelectedmobileBackgroundValue = imageURL;
                
                            // Reset the dropdown to "Select a Mobile Background"
                            selectedmobileBackground.value = '';
                        } else {
                            // If no file is selected, use the last selected value from the dropdown
                            const selectedValue = selectedmobileBackground.value;
                
                            if (!selectedValue || selectedValue === '') {
                                selectedmobileBackgroundPreview.src = ''; // Clear the image preview source
                                selectedmobileBackgroundPreview.style.display = 'none'; // Hide the image preview
                
                                // Hide the image label
                                mobileBackgroundLabel.style.display = 'none';
                            } else {
                                selectedmobileBackgroundPreview.src = selectedValue;
                                selectedmobileBackgroundPreview.style.display = 'block'; // Show the image preview
                
                                // Show the image label
                                mobileBackgroundLabel.style.display = 'block';
                
                                // Update the hidden input field with the selected image data (URL)
                                document.getElementById('selectedmobileBackgroundData').value = selectedValue;
                
                                // Update the last selected value
                                lastSelectedmobileBackgroundValue = selectedValue;
                            }
                        }
                    });
                
                    // Add an event listener to the select element
                    selectedmobileBackground.addEventListener('change', function () {
                        // Reset the file input by clearing its selected files
                        mobileBackgroundInput.value = null;
                
                        // Update the Mobile Background preview source if a value is selected
                        updatemobileBackgroundPreview();
                    });
                
                    // Call the function initially to hide the preview and label when the page first loads
                    updatemobileBackgroundPreview();
                </script>
    
        <div class="input-container">
            <label for="lphc" class="input-label"><strong>Hero Content:</strong></label>
            <textarea name="lphc" id="lphc" class="input-field" rows="5"><?= esc_textarea($_POST['lphc'] ?? '') ?></textarea>
        </div>
        
        <div class="input-container">
            <label for="custom_list_headline_checkbox" class="input-label">
                <strong>Do you need a custom List Items Headline?</strong>
            </label>
            <input type="checkbox" name="custom_list_headline_checkbox" id="custom_list_headline_checkbox" class="input-field" onchange="toggleListHeadlineField()">
        </div>
        
        <div class="input-container" id="list_headline_container">
            <label for="list_items_headline" class="input-label">
                <strong>List Items Headline:</strong>
            </label>
            <input type="text" name="list_items_headline" id="list_items_headline" class="input-field" value="<?= esc_attr($_POST['list_items_headline'] ?? '') ?>" style="margin-left: 83px; max-width: 400px;">
        </div>
        
        <script>
            function toggleListHeadlineField() {
                var listHeadlineContainer = document.getElementById('list_headline_container');
                var listItemsHeadlineInput = document.getElementById('list_items_headline');
                var checkbox = document.getElementById('custom_list_headline_checkbox');
        
                if (checkbox.checked) {
                    listHeadlineContainer.style.display = 'block';
                } else {
                    listHeadlineContainer.style.display = 'none';
                    listItemsHeadlineInput.value = "We're seeing fantastic results helping people with the following:";
                }
            }
        
            // Initial state
            toggleListHeadlineField();
        </script>
        
        <div class="input-container">
            <label for="list_item1" class="input-label"><strong>List Item 1:</strong></label>
            <input type="text" name="list_item1" id="list_item1" class="input-field" value="<?= esc_attr($_POST['list_item1'] ?? '') ?>">
        </div>
        
        <div class="input-container">
            <label for="list_item2" class="input-label"><strong>List Item 2:</strong></label>
            <input type="text" name="list_item2" id="list_item2" class="input-field" value="<?= esc_attr($_POST['list_item2'] ?? '') ?>">
        </div>
        
        <div class="input-container">
            <label for="list_item3" class="input-label"><strong>List Item 3:</strong></label>
            <input type="text" name="list_item3" id="list_item3" class="input-field" value="<?= esc_attr($_POST['list_item3'] ?? '') ?>">
        </div>
        
        <div class="input-container">
            <label for="list_item4" class="input-label"><strong>List Item 4:</strong></label>
            <input type="text" name="list_item4" id="list_item4" class="input-field" value="<?= esc_attr($_POST['list_item4'] ?? '') ?>">
        </div>
        
        <div class="input-container">
            <label for="list_item5" class="input-label"><strong>List Item 5:</strong></label>
            <input type="text" name="list_item5" id="list_item5" class="input-field" value="<?= esc_attr($_POST['list_item5'] ?? '') ?>">
        </div>
        
        <div class="input-container">
            <label for="main_headline_black" class="input-label"><strong>First Heading Text (Black):</strong></label>
            <input type="text" name="main_headline_black" id="main_headline_black" class="input-field" value="<?= esc_attr($_POST['main_headline_black'] ?? '') ?>">
            
            <label for="main_headline_blue" class="input-label" style="margin-left: 20px;"><strong>First Heading Text (Blue):</strong></label>
            <input type="text" name="main_headline_blue" id="main_headline_blue" class="input-field" style="margin-left: -65px; width: 400px;" value="<?= esc_attr($_POST['main_headline_blue'] ?? '') ?>">
        </div>
        
        <div class="input-container">
            <label for="p1" class="input-label"><strong>First Paragraph:</strong></label>
            <textarea name="p1" id="p1" class="input-field" rows="5"><?= esc_textarea($_POST['p1'] ?? '') ?></textarea>
        </div>
        
        <div class="input-container">
            <label for="first_h3" class="input-label"><strong>First H3:</strong></label>
            <input type="text" name="first_h3" id="first_h3" class="input-field" value="<?= esc_attr($_POST['first_h3'] ?? '') ?>">
        </div>
        
        <div class="input-container">
            <label for="p2" class="input-label"><strong>Second Paragraph:</strong></label>
            <textarea name="p2" id="p2" class="input-field" rows="5"><?= esc_textarea($_POST['p2'] ?? '') ?></textarea>
        </div>
        
        <div class="input-container">
            <label for="second_h3" class="input-label"><strong>Second H3:</strong></label>
            <input type="text" name="second_h3" id="second_h3" class="input-field" value="<?= esc_attr($_POST['second_h3'] ?? '') ?>">
        </div>
        
        <div class="input-container">
            <label for="p3" class="input-label"><strong>Final Paragraph:</strong></label>
            <textarea name="p3" id="p3" class="input-field" rows="5"><?= esc_textarea($_POST['p3'] ?? '') ?></textarea>
        </div>
    </div>
    
    <!-- Hidden field for gMapOrig -->
    <input type="hidden" name="gMapOrig" value="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d2849.06440844762!2d-88.12671408425835!3d44.43184100974899!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x8802fee355be516f%3A0x95a8f520c250b36b!2sSgambati's%20New%20York%20Pizza!5e0!3m2!1sen!2sus!4v1568047413280!5m2!1sen!2sus">

    <div id="gif-container" style="opacity: 0; height: 0; overflow: hidden; transition: opacity 1s, height 1s;">
    <p><img src="<?php echo plugins_url('../search-and-replace/working-on-it.gif', __FILE__); ?>" alt="Working on it" style="width: 400px;" /></p>
    </div>
    
    <input type="hidden" name="action" value="lp-maker">
    <?php wp_nonce_field('lp_maker_nonce'); ?>
    <input type="submit" name="submit" class="button-primary" value="Submit" style="margin-top:20px;" onclick="showGif();">

    <p><strong>Please be patient!</strong> It can take between 90 seconds and 2 minutes to create the landing page after clicking submit.</p>
    </form>
</div>

<script>
    // Function to show the GIF container
    function showGif() {
        var gifContainer = document.getElementById('gif-container');
        gifContainer.style.opacity = '1';
        gifContainer.style.height = 'auto';
    }
</script>

<script>
    // Assuming you have a dropdown with the ID "lpType"
    const lpTypeDropdown = document.getElementById('lpType');
    const customLPContainer = document.getElementById('customLPContainer');

    // Function to toggle visibility based on the selected value
    function toggleCustomFieldsVisibility() {
        const selectedValue = lpTypeDropdown.value;

        // Check if the selected value is "CUSTOM"
        if (selectedValue === 'custom') {
            customLPContainer.style.display = 'block'; // Show the container
        } else {
            customLPContainer.style.display = 'none'; // Hide the container
        }
    }

    // Add an event listener to the dropdown
    lpTypeDropdown.addEventListener('change', toggleCustomFieldsVisibility);

    // Call the function initially to set the initial visibility
    toggleCustomFieldsVisibility();
</script>


<?php

// Process the lp-maker action
function lp_maker_action() {
    if (!current_user_can('manage_options')) {
        return;
    }

    check_admin_referer('lp_maker_nonce');
    
    $lpType = $_POST['lpType'];
    $clinicName = $_POST['clinicName'];
    $address = $_POST['address'];
    $city = $_POST['city'];
    $state = $_POST['state'];
    $zip = $_POST['zip'];
    $doctor_name = $_POST['doctor_name'];
    $phone = $_POST['phone'];
    $hl_id = $_POST['hl_id'];
    $special = stripslashes($_POST['special']);
    $price = stripslashes($_POST['price']);
    $list_items_headline = $_POST['list_items_headline'];
    $list_item1 = stripslashes($_POST['list_item1']);
    $list_item2 = $_POST['list_item2'];
    $list_item3 = stripslashes($_POST['list_item3']);
    $list_item4 = $_POST['list_item4'];
    $list_item5 = $_POST['list_item5'];
    $main_headline_black = $_POST['main_headline_black'];
    $main_headline_blue = stripslashes($_POST['main_headline_blue']);
    $p1 = stripslashes($_POST['p1']);
    $first_h3 = stripslashes($_POST['first_h3']);
    $p2 = stripslashes($_POST['p2']);
    $second_h3 = stripslashes($_POST['second_h3']);
    $p3 = stripslashes($_POST['p3']);
    $testimonial_name1 = stripslashes($_POST['testimonial_name1']);
    $testimonial1 = stripslashes($_POST['testimonial1']);
    $testimonial_name2 = stripslashes($_POST['testimonial_name2']);
    $testimonial2 = stripslashes($_POST['testimonial2']);
    $testimonial_name3 = stripslashes($_POST['testimonial_name3']);
    $testimonial3 = stripslashes($_POST['testimonial3']);
    $google_map = stripslashes($_POST['google_map']);
    $alt_text_doctor = stripslashes($_POST['alt_text_doctor']);
    $clinicAltText = stripslashes($_POST['clinicAltText']);
    $mBkgrdAltText = stripslashes($_POST['mBkgrdAltText']);
    $newSlug = stripslashes($_POST['newSlug']);
    $postMetadata = stripslashes($_POST['postMetadata']);
    $lpOptimization = stripslashes($_POST['lpOptimization']);
    $typeOfLP = stripslashes($_POST['typeOfLP']);
    $lphc = stripslashes($_POST['lphc']);
    $gMapOrig = stripslashes($_POST['gMapOrig']);

    $selectedImage = $_POST['selectedImage'];
    $selectedClinicLogoInput = $_POST['selectedClinicLogoInput'];
    $selectedmobileBackgroundData = $_POST['selectedmobileBackgroundData'];

    $domain = parse_url( home_url(), PHP_URL_HOST );
    $domain = preg_replace( '/^www\./', '', $domain );
    
    // Check if a doctor image was uploaded
    if (isset($_FILES['doctor_image']) && !empty($_FILES['doctor_image']['tmp_name'])) {
        // Handle uploaded image
        $uploaded_doctor_image = $_FILES['doctor_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['doctor_image']['name']);
    
        // Move the uploaded image to the target directory
        if (move_uploaded_file($_FILES['doctor_image']['tmp_name'], $target_file)) {
            // Image moved successfully
            $uploaded_doctor_image = $target_file; // Update the $uploaded_doctor_image variable with the new path
        } else {
            // Error moving the image
            $uploaded_doctor_image = ''; // Set to an empty string to indicate an error
        }
    } elseif (!empty($_POST['selectedImage'])) {
        // Handle selected image from JavaScript
        $selected_image_data = $_POST['selectedImage'];
        $uploaded_doctor_image = $selected_image_data;
    } else {
        $uploaded_doctor_image = ''; // No image provided
    }
    
    // Check if a clinic logo was uploaded
    if (isset($_FILES['clinicLogo']) && !empty($_FILES['clinicLogo']['tmp_name'])) {
        // Handle uploaded image
        $uploaded_clinic_logo = $_FILES['clinicLogo']['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['clinicLogo']['name']);
    
        // Move the uploaded image to the target directory
        if (move_uploaded_file($_FILES['clinicLogo']['tmp_name'], $target_file)) {
            // Image moved successfully
            $uploaded_clinic_logo = $target_file; // Update the $uploaded_clinic_logo variable with the new path
        } else {
            // Error moving the image
            $uploaded_clinic_logo = ''; // Set to an empty string to indicate an error
        }
    } elseif (!empty($_POST['selectedClinicLogoInput'])) {
        // Handle selected image from JavaScript
        $selected_image_data = $_POST['selectedClinicLogoInput'];
        $uploaded_clinic_logo = $selected_image_data;
    } else {
        $uploaded_clinic_logo = ''; // No image provided
    }
    
    // Check if a mobile background was uploaded
    if (isset($_FILES['mobileBackground']) && !empty($_FILES['mobileBackground']['tmp_name'])) {
        // Handle uploaded image
        $uploaded_mobile_background = $_FILES['mobileBackground']['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['mobileBackground']['name']);
    
        // Move the uploaded image to the target directory
        if (move_uploaded_file($_FILES['mobileBackground']['tmp_name'], $target_file)) {
            // Image moved successfully
            $uploaded_mobile_background = $target_file; // Update the $uploaded_mobile_background variable with the new path
        } else {
            // Error moving the image
            $uploaded_mobile_background = ''; // Set to an empty string to indicate an error
        }
    } elseif (!empty($_POST['selectedmobileBackgroundData'])) {
        // Handle selected image from JavaScript
        $selected_image_data = $_POST['selectedmobileBackgroundData'];
        $uploaded_mobile_background = $selected_image_data;
    } else {
        $uploaded_mobile_background = ''; // No image provided
    }
  
    // If there are any errors, display them
    if (empty($lpType)) {
        $errors[] = 'ERROR: Please Select Landing Page Type Before Submitting.';
    }
    
    if (empty($clinicName)) {
        $errors[] = 'ERROR: Please Enter Clinic Name Before Submitting.';
    }

    if (empty($address)) {
        $errors[] = 'ERROR: Please Enter Address Before Submitting.';
    }
    
    if (empty($city)) {
        $errors[] = 'ERROR: Please Enter City Before Submitting.';
    }
    
    if (empty($state)) {
        $errors[] = 'ERROR: Please Enter State Before Submitting.';
    }
    
    if (empty($zip)) {
        $errors[] = 'ERROR: Please Enter ZIP Code Before Submitting.';
    }
    
    if (empty($doctor_name)) {
        $errors[] = 'ERROR: Please Enter Doctor Name Before Submitting.';
    }
    
    if (empty($phone)) {
        $errors[] = 'ERROR: Please Enter Phone Number Before Submitting.';
    }
    
    if (empty($hl_id)) {
        $errors[] = 'ERROR: Please Enter HL Form ID Before Submitting.';
    }
    
    if (empty($special)) {
        $errors[] = 'ERROR: Please Enter Special Offer Before Submitting.';
    }
    
    if ($price === '' || $price === null) {
        $errors[] = 'ERROR: Please Enter Price Before Submitting.';
    }
    
    if (empty($testimonial_name1)) {
        $errors[] = 'ERROR: Please Enter All Testimonial Names Before Submitting.';
    }
    
    if (empty($testimonial_name2)) {
        $errors[] = 'ERROR: Please Enter All Testimonial Names Before Submitting.';
    }
    
    if (empty($testimonial_name3)) {
        $errors[] = 'ERROR: Please Enter All Testimonial Names Before Submitting.';
    }
    
    if (empty($testimonial1)) {
        $errors[] = 'ERROR: Please Enter All Testimonials Before Submitting.';
    }
    
    if (empty($testimonial2)) {
        $errors[] = 'ERROR: Please Enter All Testimonials Before Submitting.';
    }
    
    if (empty($testimonial3)) {
        $errors[] = 'ERROR: Please Enter All Testimonials Before Submitting.';
    }
    
    if (empty($google_map)) {
        $errors[] = 'ERROR: Please Enter Google Maps Embed Code Before Submitting.';
    }
    
    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;
    }
    
    // Prepare the command for the lp-maker script
    $domain = parse_url(home_url(), PHP_URL_HOST);
    $domain = preg_replace('/^www\./', '', $domain);
    
    $script_file = dirname(__FILE__) . '/lp-maker.sh';
    // Capture the exit status of the shell command
    $output = array();
    $status = 0;

    // Pass the uploaded image as an argument to the script
    $command = "/bin/bash $script_file " .
    escapeshellarg($domain) . ' ' .
    escapeshellarg($lpType) . ' ' .
    escapeshellarg($clinicName) . ' ' .
    escapeshellarg($address) . ' ' .
    escapeshellarg($city) . ' ' .
    escapeshellarg($state) . ' ' .
    escapeshellarg($zip) . ' ' .
    escapeshellarg($doctor_name) . ' ' .
    escapeshellarg($phone) . ' ' .
    escapeshellarg($hl_id) . ' ' .
    escapeshellarg($special) . ' ' .
    escapeshellarg($price) . ' ' .
    escapeshellarg($list_items_headline) . ' ' .
    escapeshellarg($list_item1) . ' ' .
    escapeshellarg($list_item2) . ' ' .
    escapeshellarg($list_item3) . ' ' .
    escapeshellarg($list_item4) . ' ' .
    escapeshellarg($list_item5) . ' ' .
    escapeshellarg($main_headline_black) . ' ' .
    escapeshellarg($main_headline_blue) . ' ' .
    escapeshellarg($p1) . ' ' .
    escapeshellarg($first_h3) . ' ' .
    escapeshellarg($p2) . ' ' .
    escapeshellarg($second_h3) . ' ' .
    escapeshellarg($p3) . ' ' .
    escapeshellarg($testimonial_name1) . ' ' .
    escapeshellarg($testimonial1) . ' ' .
    escapeshellarg($testimonial_name2) . ' ' .
    escapeshellarg($testimonial2) . ' ' .
    escapeshellarg($testimonial_name3) . ' ' .
    escapeshellarg($testimonial3) . ' ' .
    escapeshellarg($google_map) . ' ' .
    escapeshellarg($uploaded_doctor_image) . ' ' .
    escapeshellarg($alt_text_doctor) . ' ' .
    escapeshellarg($uploaded_clinic_logo) . ' ' .
    escapeshellarg($clinicAltText) . ' ' .
    escapeshellarg($uploaded_mobile_background) . ' ' .
    escapeshellarg($mBkgrdAltText) . ' ' .
    escapeshellarg($newSlug) . ' ' .
    escapeshellarg($postMetadata) . ' ' .
    escapeshellarg($lpOptimization) . ' ' .
    escapeshellarg($typeOfLP) . ' ' .
    escapeshellarg($lphc) . ' ' .
    escapeshellarg($gMapOrig);

    // Execute the escaped command
    exec($command, $output, $status);

    // Clear the form fields after a successful submission
    clearFormFields();
    
    // 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>';
            break;
        case 0:
            // Display success message
            $success_message = '<div class="notice notice-success"><p>' . esc_html__( 'Successfully Created Landing Page! ', '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">$1</a>', $output_line);
                $success_message .= wp_kses('<p>' . $output_line . '</p>', array('a' => array('href' => array())));
            }
            $success_message .= '<p>Has anyone told you how incredible you are lately? <strong>Because you are incredible!</strong></p>';
            $success_message .= '</div>';
            echo $success_message;
            
    }
}

// Clear the forward slashes if there's an error and the page refreshes
function clearFormFieldsFromSlashes() {
    $_POST['lpType'] = stripslashes($_POST['lpType']);
    $_POST['clinicName'] = stripslashes($_POST['clinicName']);
    $_POST['address'] = stripslashes($_POST['address']);
    $_POST['city'] = stripslashes($_POST['city']);
    $_POST['state'] = stripslashes($_POST['state']);
    $_POST['zip'] = stripslashes($_POST['zip']);
    $_POST['doctor_name'] = stripslashes($_POST['doctor_name']);
    $_POST['phone'] = stripslashes($_POST['phone']);
    $_POST['hl_id'] = stripslashes($_POST['hl_id']);
    $_POST['special'] = stripslashes($_POST['special']);
    $_POST['price'] = stripslashes($_POST['price']);
    $_POST['list_items_headline'] = stripslashes($_POST['list_items_headline']);
    $_POST['list_item1'] = stripslashes($_POST['list_item1']);
    $_POST['list_item2'] = stripslashes($_POST['list_item2']);
    $_POST['list_item3'] = stripslashes($_POST['list_item3']);
    $_POST['list_item4'] = stripslashes($_POST['list_item4']);
    $_POST['list_item5'] = stripslashes($_POST['list_item5']);
    $_POST['main_headline_black'] = stripslashes($_POST['main_headline_black']);
    $_POST['main_headline_blue'] = stripslashes($_POST['main_headline_blue']);
    $_POST['p1'] = stripslashes($_POST['p1']);
    $_POST['first_h3'] = stripslashes($_POST['first_h3']);
    $_POST['p2'] = stripslashes($_POST['p2']);
    $_POST['second_h3'] = stripslashes($_POST['second_h3']);
    $_POST['p3'] = stripslashes($_POST['p3']);
    $_POST['testimonial_name1'] = stripslashes($_POST['testimonial_name1']);
    $_POST['testimonial1'] = stripslashes($_POST['testimonial1']);
    $_POST['testimonial_name2'] = stripslashes($_POST['testimonial_name2']);
    $_POST['testimonial2'] = stripslashes($_POST['testimonial2']);
    $_POST['testimonial_name3'] = stripslashes($_POST['testimonial_name3']);
    $_POST['testimonial3'] = stripslashes($_POST['testimonial3']);
    $_POST['google_map'] = stripslashes($_POST['google_map']);
    $_POST['alt_text_doctor'] = stripslashes($_POST['alt_text_doctor']);
    $_POST['clinicAltText'] = stripslashes($_POST['clinicAltText']);
    $_POST['mBkgrdAltText'] = stripslashes($_POST['mBkgrdAltText']);
    $_POST['newSlug'] = stripslashes($_POST['newSlug']);
    $_POST['postMetadata'] = stripslashes($_POST['postMetadata']);
    $_POST['lpOptimization'] = stripslashes($_POST['lpOptimization']);
    $_POST['lphc'] = stripslashes($_POST['lphc']);
    $_POST['typeOfLP'] = stripslashes($_POST['typeOfLP']);
}

// Clear the form fields after the form is submitted
function clearFormFields() {
    $_POST['lpType'] = '';
    $_POST['clinicName'] = '';
    $_POST['address'] = '';
    $_POST['city'] = '';
    $_POST['state'] = '';
    $_POST['zip'] = '';
    $_POST['doctor_name'] = '';
    $_POST['phone'] = '';
    $_POST['hl_id'] = '';
    $_POST['special'] = '';
    $_POST['price'] = '';
    $_POST['list_items_headline'] = '';
    $_POST['list_item1'] = '';
    $_POST['list_item2'] = '';
    $_POST['list_item3'] = '';
    $_POST['list_item4'] = '';
    $_POST['list_item5'] = '';
    $_POST['main_headline_black'] = '';
    $_POST['main_headline_blue'] = '';
    $_POST['p1'] = '';
    $_POST['first_h3'] = '';
    $_POST['p2'] = '';
    $_POST['second_h3'] = '';
    $_POST['p3'] = '';
    $_POST['testimonial_name1'] = '';
    $_POST['testimonial1'] = '';
    $_POST['testimonial_name2'] = '';
    $_POST['testimonial2'] = '';
    $_POST['testimonial_name3'] = '';
    $_POST['testimonial3'] = '';
    $_POST['google_map'] = '';
    $_POST['alt_text_doctor'] = '';
    $_POST['clinicAltText'] = '';
    $_POST['mBkgrdAltText'] = '';
    $_POST['newSlug'] = '';
    $_POST['postMetadata'] = '';
    $_POST['lpOptimization'] = '';
    $_POST['typeOfLP'] = '';
    $_POST['lphc'] = '';
}

// Helper function to download an image from a URL (if needed)
function download_image($url) {
    $image_data = file_get_contents($url);

    if ($image_data === false) {
        return ''; // Return an empty string on failure
    }

    // Save the downloaded image to a temporary file
    $temp_file = tempnam(sys_get_temp_dir(), 'image_');
    file_put_contents($temp_file, $image_data);

    return $temp_file; // Return the path to the temporary image file
}
?>
<script>
  // Global variables to track the state of the shift key, the first clicked checkbox, and the last clicked checkbox
  var isShiftKeyPressed = false;
  var firstClickedCheckbox = null;
  var lastClickedCheckbox = null;

  // Function to handle checkbox clicks
  function handleCheckboxClick(checkbox, event) {
    if (event.shiftKey && firstClickedCheckbox) {
      var checkboxes = document.querySelectorAll('input[type="checkbox"]');
      var startIndex = Array.from(checkboxes).indexOf(firstClickedCheckbox);
      var endIndex = Array.from(checkboxes).indexOf(checkbox);

      for (var i = Math.min(startIndex, endIndex); i <= Math.max(startIndex, endIndex); i++) {
        checkboxes[i].checked = checkbox.checked;
      }
    } else {
      firstClickedCheckbox = checkbox;
    }
  }

  // Function to handle the shift key press and release
  document.addEventListener('keydown', function (event) {
    if (event.key === 'Shift') {
      isShiftKeyPressed = true;
    }
  });

  document.addEventListener('keyup', function (event) {
    if (event.key === 'Shift') {
      isShiftKeyPressed = false;
      firstClickedCheckbox = null;
    }
  });

  // Attach the handleCheckboxClick function to all checkboxes
  var checkboxes = document.querySelectorAll('input[type="checkbox"]');
  checkboxes.forEach(function (checkbox) {
    checkbox.addEventListener('click', function (event) {
      handleCheckboxClick(this, event);
    });
  });

  // Function to clear the selection
  function clearSelection(event) {
    event.preventDefault();
    var checkboxes = document.querySelectorAll('input[type="checkbox"]');
    checkboxes.forEach(function (checkbox) {
      checkbox.checked = false;
    });
  }

</script>