<?php
/*
Template Name: Appointment Page
*/

get_header();

// The Loop
if (have_posts()) {
    while (have_posts()) {
        the_post();

        $post_meta = get_post_meta(get_the_ID(), '', true);
       
        ?>
        <main id="content-container" class="overflow-scroll no-scrollbar">
            <div class="max-w-7xl mx-auto">
                <h2><?php the_title(); ?></h2>
                <div><?php the_content(); ?></div>
                <div id="appointment-body"></div>
            </div>
        </main>

        <script>
            document.addEventListener('DOMContentLoaded', function() {
                let rawVehicleDetails = <?php echo json_encode($post_meta); ?>;
                let postDetails = {};

                for (let key in rawVehicleDetails) {
                    if (rawVehicleDetails.hasOwnProperty(key)) {
                        if (key === 'vehicle' && rawVehicleDetails[key][0]) {
                            postDetails[key] = JSON.parse(rawVehicleDetails[key][0]);
                        } else {
                            postDetails[key] = rawVehicleDetails[key][0] || null;
                        }
                    }
                }
                const appointmentForm = new AppointmentForm(postDetails.vehicle);
                if(appointmentForm){
                    const financeForm = new FinanceForm(postDetails.vehicle, appointmentForm, ()=>{});
                    const appointmentBody = document.querySelector('#appointment-body');
                    let userForm = financeForm.initForm();
                    
                    const elementsToRemove = userForm.querySelectorAll('.finance-view-only');
                    elementsToRemove.forEach(element => {
                        element.remove();
                    });

                   

                  
                    appointmentBody.appendChild(userForm);
                    
                    const allInputs = [...appointmentForm.inputs, ...financeForm.inputs ]
                    allInputs.forEach(input=>{
                        const inputElement = userForm.querySelector(`#${input}`);
                        if (inputElement) {
                            inputElement.value = postDetails[input] || 0;
                            inputElement.dispatchEvent(new Event('input'));
                            inputElement.disabled = true; 

                        }
                    })
               
                    financeForm.updateView();

                }



            });
        </script>
        <?php
    }
} else {
    echo 'Appointment not found.';
}

get_footer();
