Richard
Richard

Reputation: 71

Woocommerce, get ID and passing over

Im looking for some advice around something i'm trying to create for a customer.

https://pjs-adventures.com/test-checkout/

Essentially, they run "events" which are really woocommerce products, I need to attach "attendees" to that Product an pass the ID over from step 1 - 5 so when step 5 comes, the person doing the booking for the adventure, can fill out medical forms for each attendee.

Step 4 is working great:

step 41

Step 5 isn't as I don't think the ID is being passed over from the "event" selector properly, thus it can;t find the attendees but they are there in the post type.

Step 5

Here is my complete code:

<?php
/**
 * Template Name: Registration Form
 */

get_header();

// Handle attendee form submission
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['acf_attendee_submit'])) {
    if (!empty($_POST['attendee_first_name'])) {
        foreach ($_POST['attendee_first_name'] as $index => $first_name) {
            if (!empty($first_name) && !empty($_POST['attendee_surname'][$index]) && !empty($_POST['attendee_email'][$index]) && !empty($_POST['event_id'])) {

                $event_id = intval($_POST['event_id']);

                $attendee_data = array(
                    'post_title'   => sanitize_text_field($first_name . ' ' . $_POST['attendee_surname'][$index]),
                    'post_status'  => 'publish',
                    'post_type'    => 'attendees',
                );

                // Insert new Attendee post
                $attendee_id = wp_insert_post($attendee_data);

                // If attendee post was successfully created, update ACF fields
                if ($attendee_id) {
                    update_field('attendee_first_name', sanitize_text_field($first_name), $attendee_id);
                    update_field('attendee_surname', sanitize_text_field($_POST['attendee_surname'][$index]), $attendee_id);
                    update_field('attendee_email', sanitize_email($_POST['attendee_email'][$index]), $attendee_id);
                    update_field('event_id', $event_id, $attendee_id);
                }
            }
        }
    }

    
}

// Ensure session starts
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Ensure session array exists
if (!isset($_SESSION['attendees'])) {
    $_SESSION['attendees'] = [];
}
?>

<div class="container">
    <h1>Adventure Registration</h1>

   

    <!-- Registration Form -->
    <div class="form-container">
        <div class="progress-sidebar">
            <div class="step active" data-step="1"><i class="fas fa-user"></i> Personal Details </div>
            <div class="step" data-step="2"><i class="fas fa-map-marker-alt"></i> Address & Contact Details</div>
            <div class="step" data-step="3"><i class="fas fa-credit-card"></i> Billing Details</div>
            <div class="step" data-step="4"><i class="fas fa-users"></i> Adventure Attendees</div>
            <div class="step" data-step="5"><i class="fas fa-medkit"></i> Medical Assessment</div>
            <div class="step" data-step="6"><i class="fas fa-file-signature"></i> Consent</div>
        </div>

        <form method="post" id="acf-attendee-form">
            <!-- Step 1: Personal Details -->
            <div class="form-step active" data-step="1">
    <h3><i class="fas fa-user"></i> Personal Details</h3>

    <!-- Event Selection Warning -->
    <p id="event-warning" style="color: red; font-weight: bold;">
        ⚠️ You must choose an event before proceeding!
    </p>

    <!-- Event Dropdown -->
    <label for="event-dropdown"><strong>Select Your Adventure:</strong></label>
    <select id="event-dropdown" name="event_id" required>
        <option value="">-- Choose an Adventure --</option>
        <?php
        // Fetch WooCommerce Products (Events)
        $events = get_posts([
            'post_type' => 'product',
            'posts_per_page' => -1
        ]);

        foreach ($events as $event) {
            $event_date = get_post_meta($event->ID, '_event_date', true);
            $formatted_date = $event_date ? date("jS F Y", strtotime($event_date)) : 'Date Not Set';
            echo '<option value="' . esc_attr($event->ID) . '" data-name="' . esc_attr($event->post_title) . '">'
                 . esc_html($event->post_title) . ' - (' . $formatted_date . ')</option>';
        }
        ?>
    </select>

    <!-- Hidden input to store selected event ID -->
    <input type="hidden" name="selected_event_id" id="selected_event_id" value="">

    <hr>

    <!-- Personal Details -->
    <input type="text" name="personal_first_name[]" placeholder="First Name" required>
    <input type="text" name="personal_surname[]" placeholder="Surname" required>
    <input type="email" name="personal_email[]" placeholder="Email" required>
    <input type="text" name="personal_dob[]" id="personal_dob" placeholder="DD/MM/YYYY" required>

    <p id="dob-warning" style="color: red; font-size: 14px; display: none;">⚠️ Please enter a valid date in DD/MM/YYYY format.</p>

    <button type="button" id="next-step-btn" class="next-step" disabled>Next</button>
</div>

<script>
document.addEventListener("DOMContentLoaded", function() {
    const eventDropdown = document.getElementById("event-dropdown");
    const nextButton = document.getElementById("next-step-btn");
    const eventWarning = document.getElementById("event-warning");
    const selectedEventId = document.getElementById("selected_event_id");

    // Load stored event from sessionStorage (if previously selected)
    if (sessionStorage.getItem("selected_event_id")) {
        eventDropdown.value = sessionStorage.getItem("selected_event_id");
        selectedEventId.value = sessionStorage.getItem("selected_event_id");
        eventWarning.style.display = "none";
        nextButton.disabled = false;
    }

    // Store event selection in sessionStorage
    eventDropdown.addEventListener("change", function() {
        if (this.value !== "") {
            nextButton.disabled = false;
            eventWarning.style.display = "none";
            selectedEventId.value = this.value;

            // Store event ID & name in sessionStorage
            const selectedOption = this.options[this.selectedIndex];
            sessionStorage.setItem("selected_event_id", this.value);
            sessionStorage.setItem("selected_event_name", selectedOption.dataset.name);
        } else {
            nextButton.disabled = true;
            eventWarning.style.display = "block";
            sessionStorage.removeItem("selected_event_id");
            sessionStorage.removeItem("selected_event_name");
        }
    });

    // Validate DOB format
    const dobInput = document.getElementById("personal_dob");
    const dobWarning = document.getElementById("dob-warning");
    const datePattern = /^(0[1-9]|[12][0-9]|3[01])\/(0[1-9]|1[0-2])\/(19|20)\d{2}$/;

    dobInput.addEventListener("input", function() {
        if (!datePattern.test(dobInput.value)) {
            dobWarning.style.display = "block";
            dobInput.style.border = "2px solid red";
        } else {
            dobWarning.style.display = "none";
            dobInput.style.border = "2px solid green";
        }
    });
});
</script>

            <!-- Step 2: Address & Contact -->
            <div class="form-step" data-step="2">
                <h3><i class="fas fa-map-marker-alt"></i> Address & Contact Details</h3>
                <input type="text" name="attendee_address_line_1" placeholder="Address Line 1" required>
                <input type="text" name="attendee_address_line_2" placeholder="Address Line 2" required>
                <input type="text" name="attendee_city" placeholder="Town/City" required>
                <input type="text" name="attendee_county" placeholder="County" required>
                <input type="text" name="attendee_postcode" placeholder="Postcode" required>
                <input type="text" name="attendee_country" placeholder="Country" required>
                <button type="button" class="prev-step">Back</button>
                <button type="button" class="next-step">Next</button>
            </div>

            <!-- Step 3: Billing -->
            <div class="form-step" data-step="3">
                <h3><i class="fas fa-credit-card"></i> Billing Details</h3>
                <input type="text" name="billing_name" placeholder="Billing Name" required>
                <input type="text" name="billing_address" placeholder="Billing Address" required>
                <button type="button" class="prev-step">Back</button>
                <button type="button" class="next-step">Next</button>
            </div>

           
<!-- Step 4: Display Attendees -->



    <div class="form-step" data-step="4">
    <h3><i class="fas fa-users"></i> Adventure Attendees</h3>

    <?php
    global $product;
    $product_id = isset($product) ? $product->get_id() : null;
    ?>

    <!-- Show Selected WooCommerce Product -->
    <p><strong>Adding attendees for:</strong> 
        <span id="selected-product-name" style="color: #C1272D; font-weight: bold;">Loading...</span>
    </p>

    <!-- Add Attendee Form -->
    <input type="text" id="attendee_first_name" placeholder="First Name" required>
    <input type="text" id="attendee_surname" placeholder="Surname" required>
    <input type="email" id="attendee_email" placeholder="Email" required>
    <input type="text" id="attendee_dob" placeholder="Date of Birth (DD/MM/YYYY)" required>
    <button type="button" id="add-attendee-btn">+ Add Attendee</button>

    <!-- Show Attendees Added -->
    <h4>Attendees Added:</h4>
    <ul id="attendee-list">
        <?php
        if (!empty($_SESSION['attendees'])) {
            foreach ($_SESSION['attendees'] as $attendee) {
                echo "<li>{$attendee['firstName']} {$attendee['surname']} ({$attendee['email']})</li>";
            }
        } else {
            echo "<li>No attendees added yet.</li>";
        }
        ?>
    </ul>

    <p><strong>Important:</strong> You <span style="color: red;">must submit attendees</span> before proceeding to medical assessment.</p>

    <button type="button" id="submit-attendees-btn">Submit Attendees</button>
    <p id="submission-status"></p>

    <button type="button" class="prev-step">Back</button>
    <button type="button" class="next-step" id="next-medical" disabled>Next</button>

    <!-- Hidden input to store the WooCommerce product ID -->
    <input type="hidden" name="selected_product_id" id="selected_product_id" value="<?php echo esc_attr($product_id); ?>">
</div>

<script>
document.addEventListener("DOMContentLoaded", function() {
    const selectedProductName = document.getElementById("selected-product-name");
    const selectedProductIdInput = document.getElementById("selected_product_id");

    // Retrieve the WooCommerce product name and ID from sessionStorage
    const storedProductId = sessionStorage.getItem("selected_product_id");
    const storedProductName = sessionStorage.getItem("selected_product_name");

    if (storedProductId && storedProductName) {
        selectedProductIdInput.value = storedProductId;
        selectedProductName.innerText = storedProductName; // FIX: Ensure correct name appears
    } else {
        selectedProductName.innerText = "(No event selected)";
    }
});
</script>


<!-- Step 5: Medical Assessment -->
<div class="form-step" data-step="5">
    <h3><i class="fas fa-medkit"></i> Medical Assessment</h3>
    <p>We take your safety on all our adventures very seriously.</p>
    <p>It is vital all participants fully disclose their medical information prior to departure. This information will remain confidential and is only viewed by PJS Adventures, the PJS Team Leader or Guide, and your expedition medic, if applicable.</p>

    <?php
    global $wpdb;

    // Retrieve the event (product) ID from sessionStorage (JS will populate this)
    echo '<script>
        var storedEventId = sessionStorage.getItem("selected_event_id");
        document.getElementById("stored-event-id").value = storedEventId;
    </script>';

    // Get event ID from form submission or session
    $product_id = isset($_POST['selected_event_id']) ? intval($_POST['selected_event_id']) : 0;

    // DEBUG: Show product ID
    echo "<p><strong>DEBUG: Selected Product (Event) ID:</strong> " . esc_html($product_id) . "</p>";

    // Query attendees where event_id (WooCommerce product ID) matches
    $attendees = get_posts([
        'post_type'   => 'attendees',
        'post_status' => 'publish',
        'numberposts' => -1,
        'meta_query'  => [
            [
                'key'     => 'event_id', // Ensure attendees store product_id under 'event_id'
                'value'   => (string) $product_id, 
                'compare' => '='
            ]
        ]
    ]);

    // DEBUG: Show fetched attendees
    echo "<p><strong>DEBUG: Found " . count($attendees) . " attendees.</strong></p>";

    if (!empty($attendees)) {
        echo "<ul>";
        foreach ($attendees as $attendee) {
            echo "<li>" . esc_html(get_field('attendee_first_name', $attendee->ID)) . " " . esc_html(get_field('attendee_surname', $attendee->ID)) . "</li>";
        }
        echo "</ul>";
    }
    ?>

    <!-- Attendee Selection Dropdown -->
    <label for="attendee-select"><strong>Select an Attendee:</strong></label>
    <select id="attendee-select" name="attendee_id">
        <option value="">-- Choose an Attendee --</option>
        <?php if (!empty($attendees)): ?>
            <?php foreach ($attendees as $attendee): ?>
                <option value="<?php echo esc_attr($attendee->ID); ?>">
                    <?php echo esc_html(get_field('attendee_first_name', $attendee->ID) . ' ' . get_field('attendee_surname', $attendee->ID)); ?>
                </option>
            <?php endforeach; ?>
        <?php else: ?>
            <option value="">No attendees found</option>
        <?php endif; ?>
    </select>
</div>

<!-- Medical Assessment Form (Hidden by Default) -->
<div id="medical-form-container" style="display: none;">
    <h4>Medical Information for <span id="selected-attendee-name"></span></h4>
    
    <textarea name="medical_conditions" id="medical_conditions" placeholder="Enter medical conditions..." required></textarea>
    <input type="text" name="allergies" id="allergies" placeholder="Allergies (if any)">
    <input type="text" name="medications" id="medications" placeholder="Medications (if any)">

    <button type="button" id="save-medical-info">Save Medical Info</button>
    <p id="save-message" style="display: none; color: green;">Medical info saved successfully!</p>
</div>

            <!-- Step 6: Consent -->
            <div class="form-step" data-step="6">
                <h3><i class="fas fa-file-signature"></i> Consent</h3>
                <button type="button" class="prev-step">Back</button>
                <button type="submit" name="acf_attendee_submit">Save & Submit</button>
            </div>
        </form>
    </div>

    <script>
document.addEventListener("DOMContentLoaded", function () {
    const eventDropdown = document.getElementById("event-dropdown");

    // Check if there's an event stored in sessionStorage
    if (sessionStorage.getItem("selectedEvent")) {
        eventDropdown.value = sessionStorage.getItem("selectedEvent");
    }

    eventDropdown.addEventListener("change", function () {
        sessionStorage.setItem("selectedEvent", eventDropdown.value);
    });
});
</script>
  
    
</div>

<script>
document.addEventListener("DOMContentLoaded", function () {
    const steps = document.querySelectorAll(".step");
    const formSteps = document.querySelectorAll(".form-step");
    let currentStep = 1;

    function showStep(step) {
        formSteps.forEach(el => el.classList.remove("active"));
        steps.forEach(el => el.classList.remove("active"));
        document.querySelector(`.form-step[data-step="${step}"]`).classList.add("active");
        document.querySelector(`.step[data-step="${step}"]`).classList.add("active");
    }

    document.querySelectorAll(".next-step").forEach(button => {
        button.addEventListener("click", () => {
            if (currentStep < formSteps.length) {
                currentStep++;
                showStep(currentStep);
            }
        });
    });

    document.querySelectorAll(".prev-step").forEach(button => {
        button.addEventListener("click", () => {
            if (currentStep > 1) {
                currentStep--;
                showStep(currentStep);
            }
        });
    });
});
</script>



</script>

<script>

document.addEventListener("DOMContentLoaded", function () {
    const attendeeSelect = document.getElementById("attendee-select");
    const medicalForm = document.getElementById("medical-form-container");
    const selectedAttendeeName = document.getElementById("selected-attendee-name");
    const saveMedicalInfoBtn = document.getElementById("save-medical-info");
    const nextConsentBtn = document.getElementById("next-consent");
    const saveMessage = document.getElementById("save-message");

    // Show Medical Form when Attendee is Selected
    attendeeSelect.addEventListener("change", function () {
        if (this.value) {
            selectedAttendeeName.textContent = this.options[this.selectedIndex].text;
            medicalForm.style.display = "block";
        } else {
            medicalForm.style.display = "none";
        }
    });

    // Save Medical Info
    saveMedicalInfoBtn.addEventListener("click", function () {
        const attendeeIndex = attendeeSelect.value;
        const medicalConditions = document.getElementById("medical_conditions").value;
        const allergies = document.getElementById("allergies").value;
        const medications = document.getElementById("medications").value;

        if (!attendeeIndex) {
            alert("Please select an attendee.");
            return;
        }

        fetch("<?php echo admin_url('admin-ajax.php'); ?>", {
            method: "POST",
            headers: { "Content-Type": "application/x-www-form-urlencoded" },
            body: `action=save_medical_info&attendee_index=${attendeeIndex}&medical_conditions=${medicalConditions}&allergies=${allergies}&medications=${medications}`
        }).then(response => response.text()).then(data => {
            if (data.trim() === "success") {
                saveMessage.style.display = "block";
                nextConsentBtn.disabled = false;
                setTimeout(() => {
                    saveMessage.style.display = "none";
                }, 2000);
            } else {
                alert("Failed to save medical info.");
            }
        });
    });
});

</script>

<script>
    function fetch_attendees_by_event() {
    if (isset($_POST['event_id'])) {
        global $wpdb;
        $event_id = intval($_POST['event_id']);

        $attendees = $wpdb->get_results($wpdb->prepare(
            "SELECT ID, post_title FROM {$wpdb->posts} WHERE post_type = 'attendees' AND post_status = 'publish' AND ID IN (
                SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = 'event_id' AND meta_value = %d
            )",
            $event_id
        ));

        $attendee_list = [];
        foreach ($attendees as $attendee) {
            $attendee_list[] = [
                'id' => $attendee->ID,
                'name' => $attendee->post_title
            ];
        }

        echo json_encode($attendee_list);
    }
    wp_die();
}

add_action("wp_ajax_fetch_attendees_by_event", "fetch_attendees_by_event");
add_action("wp_ajax_nopriv_fetch_attendees_by_event", "fetch_attendees_by_event");
</script>
<script>
    document.addEventListener("DOMContentLoaded", function () {
    // Add Attendee
    document.getElementById("add-attendee-btn").addEventListener("click", function () {
        const firstName = document.getElementById("attendee_first_name").value;
        const surname = document.getElementById("attendee_surname").value;
        const email = document.getElementById("attendee_email").value;
        const dob = document.getElementById("attendee_dob").value;

        if (!firstName || !surname || !email || !dob) {
            alert("Please fill all fields.");
            return;
        }

        fetch("<?php echo admin_url('admin-ajax.php'); ?>", {
            method: "POST",
            headers: { "Content-Type": "application/x-www-form-urlencoded" },
            body: `action=add_temp_attendee&first_name=${firstName}&surname=${surname}&email=${email}&dob=${dob}`
        }).then(response => response.text()).then(data => {
            if (data === "success") {
                document.getElementById("attendee-list").innerHTML += `<li>${firstName} ${surname} (${email})</li>`;
                document.getElementById("attendee_first_name").value = "";
                document.getElementById("attendee_surname").value = "";
                document.getElementById("attendee_email").value = "";
                document.getElementById("attendee_dob").value = "";
            }
        });
    });

    // Submit Attendees
    document.getElementById("submit-attendees-btn").addEventListener("click", function () {
        fetch("<?php echo admin_url('admin-ajax.php'); ?>", {
            method: "POST",
            headers: { "Content-Type": "application/x-www-form-urlencoded" },
            body: "action=submit_attendees"
        }).then(response => response.text()).then(data => {
            if (data.trim() === "success") {
                document.getElementById("submission-status").innerHTML = "<span style='color: green;'>Attendees submitted successfully!</span>";
                document.getElementById("next-medical").disabled = false;
                document.getElementById("attendee-list").innerHTML = "<li>All attendees submitted.</li>";
            } else {
                document.getElementById("submission-status").innerHTML = "<span style='color: red;'>No attendees found to submit.</span>";
            }
        });
    });
});
</script>

<style>
.container {
    max-width: 75%;
    margin: 40px auto;
    padding: 30px;
    background: #f9f9f9;
    border-radius: 10px;
    box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.1);
}

h1 {
    color: #C1272D;
    text-align: center;
    font-size: 32px;
    font-weight: bold;
}

.form-container {
    display: flex;
    justify-content: space-between;
}

.progress-sidebar {
    width: 30%;
    background: #ddd;
    padding: 20px;
    border-radius: 10px;
}

.step {
    padding: 10px;
    margin-bottom: 10px;
    font-weight: bold;
    display: flex;
    align-items: center;
    cursor: pointer;
}

.step i {
    margin-right: 8px;
    font-size: 22px;
}

.step.active {
    background: #C1272D;
    color: white;
}

.form-step {
    width: 65%;
    display: none;
}

.form-step.active {
    display: block;
}

button {
    cursor: pointer;
    padding: 10px;
    border-radius: 5px;
    font-size: 16px;
    transition: all 0.3s ease;
    margin-top: 10px;
}

.next-step {
    background: #007bff;
    color: white;
}

.prev-step {
    background: #555;
    color: white;
}

#acf-attendee-form button[type="submit"] {
    background: #28a745;
    color: white;
}

.attendees-table {
    width: 100%;
    border-collapse: collapse;
    margin-top: 20px;
}

.attendees-table th, .attendees-table td {
    border: 1px solid #ddd;
    padding: 10px;
}

.attendees-table th {
    background: #C1272D;
    color: white;
    text-align: left;
}

.delete-attendee {
    background: #dc3545;
    color: white;
    padding: 6px 12px;
    border: none;
    cursor: pointer;
}
/* 📌 Improve Sidebar Layout */
.progress-sidebar {
    width: 25%;
    background: #ddd;
    padding: 25px;
    border-radius: 10px;
    min-width: 260px;
}

/* 📌 Ensure Step Icons/Text Are Aligned */
.step {
    padding: 12px 15px;
    display: flex;
    align-items: center;
    gap: 10px;
    white-space: nowrap;
    overflow: hidden;
}

/* 📌 Fix Input Field Widths */
.form-step input {
    width: calc(100% - 10px);
    padding: 10px;
    margin-bottom: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
}

/* 📌 Improve Step Navigation Buttons */
.prev-step, .next-step {
    display: inline-block;
    width: auto;
    min-width: 120px;
    text-align: center;
    font-size: 16px;
    padding: 10px;
    margin: 10px 5px;
}

/* 📌 Fix Table Alignment */
.attendees-table {
    width: 100%;
    border-collapse: collapse;
    margin-top: 20px;
    table-layout: auto;
}

/* 📌 Center Headers Properly */
h1, h3 {
    text-align: left;
    padding-left: 15px;
}

/* 📌 Adjust Form Layout to Avoid Overlap */
.form-container {
    display: flex;
    width: 100%;
    align-items: flex-start;
    gap: 40px;
}

/* 📌 Ensure Form Stays Balanced */
.form-step {
    width: 70%;
    padding-left: 20px;
}
</style>

<?php get_footer(); ?>

Upvotes: 1

Views: 27

Answers (0)

Related Questions