<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<style>
    #loading {
        display: none;
        position: sticky;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background-color: rgba(255, 255, 255, 0.8);
        padding: 20px;
        border-radius: 10px;
        box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.5);
        width: fit-content;
        z-index: 9
    }

    #loading img {
        width: 50px;
        height: 50px;
    }

    .cardCap {
        background-color: #f2f2f2;
        height: 150px;
        border-radius: 10px;
    }

    .cardCap2 {
        background-color: #f2f2f2;

        border-radius: 10px;
    }

    .cardCap2 img {
        width: 100%;
        max-height: 200px;
    }

    .chngBtn {
        background-color: #707070;
        color: #fff !important;
        border-radius: 10px !important;
    }

    .SavBtn {
        background-color: #0455bf;
        color: #fff !important;
        border-radius: 10px !important;
    }

    /* #video {
        height: 100px;
        width: 90%;
      } */
    .video-wrapper {
        overflow: hidden;
    }

    .btnphUpl {
        background: #eeee;
        font-size: 12px !important;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center
    }

    .btnphUpl:hover {
        background: #CECDCF;

    }


    @media (max-width: 992px) {
        video {
            height: 200px;
        }
    }
</style>
<script>
    // This example requires the Places library. Include the libraries=places
    // parameter when you first load the API. For example:
    // <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">

    function initMap() {
        var map = new google.maps.Map(document.getElementById('map'), {
            center: {
                lat: 33.6824444,
                lng: 72.99091609999999
            },
            zoom: 11
        });
        var card = document.getElementById('pac-card');
        var input1 = document.getElementById('address');
        var input2 = document.getElementById('pac-input-2');
        var types = document.getElementById('type-selector');
        var strictBounds = document.getElementById('strict-bounds-selector');

        map.controls[google.maps.ControlPosition.TOP_RIGHT].push(card);

        var autocomplete1 = new google.maps.places.Autocomplete(input1);

        autocomplete1.bindTo('bounds', map);

        autocomplete1.setFields(
            ['address_components', 'geometry', 'icon', 'name']);


        var infowindow = new google.maps.InfoWindow();
        var infowindowContent = document.getElementById('infowindow-content');
        infowindow.setContent(infowindowContent);
        var marker = new google.maps.Marker({
            map: map,
            anchorPoint: new google.maps.Point(0, -29)
        });

        autocomplete1.addListener('place_changed', function() {
            infowindow.close();
            marker.setVisible(false);
            var place = autocomplete1.getPlace();


            if (!place.geometry) {
                // User entered the name of a Place that was not suggested and
                // pressed the Enter key, or the Place Details request failed.
                window.alert("No details available for input: '" + place.name + "'");
                return;
            }

            // If the place has a geometry, then present it on a map.
            if (place.geometry.viewport) {
                map.fitBounds(place.geometry.viewport);
            } else {
                map.setCenter(place.geometry.location);
                map.setZoom(17); // Why 17? Because it looks good.
            }
            marker.setPosition(place.geometry.location);
            marker.setVisible(true);

            var address = '';
            console.log(place.address_components)
            if (place.address_components) {
                var latitude = place.geometry.location.lat();
                var longitude = place.geometry.location.lng();
                console.log("pickuplat:" + latitude);
                console.log("pickuplng:" + longitude);
                document.getElementById("lat").value = latitude;
                document.getElementById("lng").value = longitude;

                //infodetail
                //    $("#lat").val(latitude);
                //   $("#lng").val(longitude);


                address = [
                    (place.address_components[0] && place.address_components[0].short_name || ''),
                    (place.address_components[1] && place.address_components[1].short_name || ''),
                    (place.address_components[2] && place.address_components[2].short_name || '')
                ].join(' ');
            }
            // document.getElementById("infodetail").value = place.name;
            infowindowContent.children['place-icon'].src = place.icon;
            infowindowContent.children['place-name'].textContent = place.name;
            infowindowContent.children['place-address'].textContent = address;
            infowindow.open(map, marker);
        });


        // Sets a listener on a radio button to change the filter type on Places
        // Autocomplete2.
        function setupClickListener(id, types) {
            var radioButton = document.getElementById(id);
            radioButton.addEventListener('click', function() {
                autocomplete1.setTypes(types);
            });
        }

        setupClickListener('changetype-all', []);
        setupClickListener('changetype-address', ['address']);
        setupClickListener('changetype-establishment', ['establishment']);
        setupClickListener('changetype-geocode', ['geocode']);

        document.getElementById('use-strict-bounds')
            .addEventListener('click', function() {
                console.log('Checkbox clicked! New state=' + this.checked);
                autocomplete2.setOptions({
                    strictBounds: this.checked
                });
            });
    }
</script>
<script
    src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAe_Fm2ja1OuDHswu4mgZKQN9DRakGyzzs&libraries=places&callback=initMap"
    async defer></script>

<style>
    .step {
        display: none;
    }

    .step.active {
        display: flex;
    }

    .btnUplaod {
        border-color: #e9e9e9;
        border-width: 1px;
        border-style: solid;
        border-radius: 5px;


        background: #f2f2f2;
        background: linear-gradient(180deg,
                #f2f2f2 0.00%,
                #e9e9e9 100.00%);
        width: 100%;
    }

    .photoCard {

        border-color: #e9e9e9;
        border-width: 1px;
        border-style: solid;
        border-radius: 5px;


        background: #eeeeee;
        min-height: 165px;
        ;

    }

    .imgUploaded {
        height: 142px;
        width: 100%;
        object-fit: cover;
    }

    .UplCard {
        cursor: pointer;
    }

    .btnSign {
        border-color: #094173 !important;
        border-width: 1px;
        border-style: solid;
        border-radius: 10px !important;


        background: #ffffff !important;
        font-family: "Montserrat";
        font-size: 12px;
        font-weight: 600;
        font-style: normal;

        color: #094173;
    }

    .btnLog {
        border-radius: 10px !important;


        background: #0455bf !important;
        font-family: "Montserrat";
        font-size: 12px;
        font-weight: 600;
        font-style: normal;
        text-align: center;

        color: #ffffff;

    }

    .formInput input:checked~label {
        color: #064EA3;
        font-weight: 500;


    }

    .fselect {
        border: var(--bs-border-width) solid var(--bs-border-color) !important;
        border-radius: var(--bs-border-radius) !important;
        transition: border-color .15s ease-in-out, box-shadow .15s;
        width: 100% !important;
    }
</style>

<div id="map" class="hidden"></div>
<div class="row my-2 justify-content-center">
    <h3 class="fmon fh2">Edit Profile</h3>
    <div class="col-md-10 my-2">
        <div>

            <div class="profileCard p-2">
                <ul class="nav nav-tabs" id="settingsTabs" role="tablist">
                    <li class="nav-item" role="presentation">
                        <a href="<?php echo base_url('site/editprofile'); ?>" class="nav-link active" id="general-tab"
                            type="button" role="tab" aria-controls="general" aria-selected="true">General
                            Setting</a>
                    </li>
                    <li class="nav-item" role="presentation">
                        <a href="<?php echo base_url('site/resetIndex'); ?>" class="nav-link" id="security-tab"
                            type="button" role="tab" aria-controls="security" aria-selected="false">Profile
                            Setting</a>
                    </li>
                </ul>
                <div class="tab-content" id="settingsTabsContent">
                    <div class="tab-pane fade show active" id="general" role="tabpanel" aria-labelledby="general-tab">
                        <div class="p-3">
                            <h4>General Settings</h4>
                            <form method="post" action="<?= base_url('Site/addIssueData') ?>"
                                class="my-2 multiStepForm">

                                <div class="row step step1" id="step1">
                                    <div class="col-md-12 my-2">
                                        <label class="fLabel" for="complaint">What is your main complaint/complaints
                                            with your teeth and oral health?</label>
                                        <textarea name="complaint" id="complaint" class="form-control formInput"
                                            placeholder="Enter"
                                            required><?= isset($user->complaint) ? htmlspecialchars($user->complaint) : '' ?></textarea>
                                    </div>
                                    <div class="col-md-6 my-2">
                                        <label class="fLabel" for="problem">How long have you had this problem
                                            for?</label>
                                        <input class="form-control formInput" type="text" name="problem" id="problem"
                                            placeholder="Enter"
                                            value="<?= isset($user->problem) ? htmlspecialchars($user->problem) : '' ?>"
                                            required />
                                    </div>
                                    <div class="col-md-6 my-2">
                                        <label class="fLabel" for="symptoms">What symptoms are you experiencing?</label>
                                        <input class="form-control formInput" type="text" name="symptoms" id="symptoms"
                                            placeholder="Enter"
                                            value="<?= isset($user->symptoms) ? htmlspecialchars($user->symptoms) : '' ?>"
                                            required />
                                    </div>
                                    <div class="col-md-12 my-2">
                                        <label class="fLabel" for="discuss">How soon would you like to see a dentist to
                                            discuss your issues?</label>
                                        <select name="discuss" id="discuss" class="form-select fselect" required>
                                            <option value="asap"
                                                <?= isset($user->discuss) && $user->discuss === 'asap' ? 'selected' : '' ?>>
                                                As soon as possible</option>
                                            <option value="within-a-week"
                                                <?= isset($user->discuss) && $user->discuss === 'within-a-week' ? 'selected' : '' ?>>
                                                Within a week</option>
                                            <option value="within-a-month"
                                                <?= isset($user->discuss) && $user->discuss === 'within-a-month' ? 'selected' : '' ?>>
                                                Within a month</option>
                                            <option value="no-rush"
                                                <?= isset($user->discuss) && $user->discuss === 'no-rush' ? 'selected' : '' ?>>
                                                No rush</option>
                                        </select>
                                    </div>
                                    <div class="col-md-6 my-2">
                                        <label class="fLabel" for="medicalcondition">Do you suffer from any medical
                                            conditions?</label>
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div
                                                    class="form-control formInput d-flex justify-content-between radio-parent">
                                                    <input type="radio" id="medical_yes" name="medical_condition"
                                                        value="medical_yes"
                                                        <?= isset($user->medical_condition) && $user->medical_condition === 'medical_yes' ? 'checked' : '' ?>
                                                        class="" required />
                                                    <label for="medical_yes">Yes</label>
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div
                                                    class="form-control formInput d-flex justify-content-between radio-parent">
                                                    <input type="radio" id="medical_no" name="medical_condition"
                                                        value="medical_no"
                                                        <?= isset($user->medical_condition) && $user->medical_condition === 'medical_no' ? 'checked' : '' ?>
                                                        class="" />
                                                    <label for="medical_no">No</label>
                                                </div>
                                            </div>
                                        </div>
                                        <div id="medical_condition_textarea" class="mt-2" style="display: none;">
                                            <textarea id="discuss_medical" class="form-control"
                                                placeholder="Please specify your medical conditions"><?= isset($user->discuss_medical) ? htmlspecialchars($user->discuss_medical) : '' ?></textarea>
                                        </div>
                                    </div>

                                    <div class="col-md-6 my-2">
                                        <label class="fLabel" for="medication">Are you on any medications?</label>
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div
                                                    class="form-control formInput d-flex justify-content-between radio-parent">
                                                    <input type="radio" id="medication_yes" name="medication"
                                                        value="medication_yes"
                                                        <?= isset($user->mediciation) && $user->mediciation === 'medication_yes' ? 'checked' : '' ?>
                                                        class="" required />
                                                    <label for="medication_yes">Yes</label>
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div
                                                    class="form-control formInput d-flex justify-content-between radio-parent">
                                                    <input type="radio" id="medication_no" name="medication"
                                                        value="medication_no"
                                                        <?= isset($user->mediciation) && $user->mediciation === 'medication_no' ? 'checked' : '' ?>
                                                        class="" />
                                                    <label for="medication_no">No</label>
                                                </div>
                                            </div>
                                        </div>
                                        <div id="medication_textarea" class="mt-2" style="display: none;">
                                            <textarea id="discuss_medication" class="form-control"
                                                placeholder="Please specify your medications"><?= isset($user->discuss_medication) ? htmlspecialchars($user->discuss_medication) : '' ?></textarea>
                                        </div>
                                    </div>



                                    <div class="col-md-12 d-flex justify-content-end">
                                        <button type="button" class="btn btnLog  py-2 px-5"
                                            onclick="nextStep(2)">Next</button>
                                    </div>
                                </div>


                                <div class="row step step2" id="step2">
                                    <div class="col-md-12 my-2">
                                        <div class="mb-3">
                                            <label class="fLabel">What treatment do you think you need or are interested
                                                in?</label>
                                            <div id="treatmentForm">
                                                <div class="d-flex justifycontent-between">
                                                    <div class="row">
                                                        <div class="form-check">
                                                            <input class="form-check-input" type="checkbox"
                                                                value="consultation" id="consultation"
                                                                name="treatment[]"
                                                                <?= isset($selectedTreatments) && in_array('consultation', $selectedTreatments) ? 'checked' : '' ?>>
                                                            <label class="form-check-label"
                                                                for="consultation">Consultation/examination</label>
                                                        </div>
                                                        <div class="form-check">
                                                            <input class="form-check-input" type="checkbox"
                                                                value="emergency" id="emergency" name="treatment[]"
                                                                <?= isset($selectedTreatments) && in_array('emergency', $selectedTreatments) ? 'checked' : '' ?>>
                                                            <label class="form-check-label" for="emergency">Emergency
                                                                pain treatment</label>
                                                        </div>
                                                        <div class="form-check">
                                                            <input class="form-check-input" type="checkbox"
                                                                value="scale" id="scale" name="treatment[]"
                                                                <?= isset($selectedTreatments) && in_array('scale', $selectedTreatments) ? 'checked' : '' ?>>
                                                            <label class="form-check-label" for="scale">SCALE +
                                                                Polish</label>
                                                        </div>
                                                        <div class="form-check">
                                                            <input class="form-check-input" type="checkbox"
                                                                value="whitening" id="whitening" name="treatment[]"
                                                                <?= isset($selectedTreatments) && in_array('whitening', $selectedTreatments) ? 'checked' : '' ?>>
                                                            <label class="form-check-label"
                                                                for="whitening">Whitening</label>
                                                        </div>
                                                        <div class="form-check">
                                                            <input class="form-check-input" type="checkbox"
                                                                value="airflow" id="airflow" name="treatment[]"
                                                                <?= isset($selectedTreatments) && in_array('airflow', $selectedTreatments) ? 'checked' : '' ?>>
                                                            <label class="form-check-label"
                                                                for="airflow">Airflow</label>
                                                        </div>
                                                        <div class="form-check">
                                                            <input class="form-check-input" type="checkbox"
                                                                value="aligner" id="aligner" name="treatment[]"
                                                                <?= isset($selectedTreatments) && in_array('aligner', $selectedTreatments) ? 'checked' : '' ?>>
                                                            <label class="form-check-label" for="aligner">Aligner
                                                                treatment/orthodontics e.g., Invisalign</label>
                                                        </div>
                                                        <div class="form-check">
                                                            <input class="form-check-input" type="checkbox"
                                                                value="composite" id="composite" name="treatment[]"
                                                                <?= isset($selectedTreatments) && in_array('composite', $selectedTreatments) ? 'checked' : '' ?>>
                                                            <label class="form-check-label" for="composite">Composite
                                                                Bonding</label>
                                                        </div>
                                                    </div>
                                                    <!-- <div class="d-flex justify-content-between flex-wrap flex-md-nowrap">
                                                   
                                                </div> -->
                                                    <div class="row">
                                                        <div class="form-check">
                                                            <input class="form-check-input" type="checkbox"
                                                                value="rootcanal" id="rootcanal" name="treatment[]"
                                                                <?= isset($selectedTreatments) && in_array('rootcanal', $selectedTreatments) ? 'checked' : '' ?>>
                                                            <label class="form-check-label" for="rootcanal">Root Canal
                                                                Treatment</label>
                                                        </div>
                                                        <div class="form-check">
                                                            <input class="form-check-input" type="checkbox"
                                                                value="extractions" id="extractions" name="treatment[]"
                                                                <?= isset($selectedTreatments) && in_array('extractions', $selectedTreatments) ? 'checked' : '' ?>>
                                                            <label class="form-check-label" for="extractions">Dental
                                                                Extractions</label>
                                                        </div>
                                                        <div class="form-check">
                                                            <input class="form-check-input" type="checkbox"
                                                                value="dentures" id="dentures" name="treatment[]"
                                                                <?= isset($selectedTreatments) && in_array('dentures', $selectedTreatments) ? 'checked' : '' ?>>
                                                            <label class="form-check-label"
                                                                for="dentures">Dentures</label>
                                                        </div>
                                                        <div class="form-check">
                                                            <input class="form-check-input" type="checkbox"
                                                                value="implants" id="implants" name="treatment[]"
                                                                <?= isset($selectedTreatments) && in_array('implants', $selectedTreatments) ? 'checked' : '' ?>>
                                                            <label class="form-check-label" for="implants">Dental
                                                                Implants</label>
                                                        </div>
                                                        <div class="form-check">
                                                            <input class="form-check-input" type="checkbox"
                                                                value="crowns" id="crowns" name="treatment[]"
                                                                <?= isset($selectedTreatments) && in_array('crowns', $selectedTreatments) ? 'checked' : '' ?>>
                                                            <label class="form-check-label" for="crowns">Crowns, Onlays,
                                                                Veneers</label>
                                                        </div>
                                                        <div class="form-check">
                                                            <input class="form-check-input" type="checkbox"
                                                                value="bridges" id="bridges" name="treatment[]"
                                                                <?= isset($selectedTreatments) && in_array('bridges', $selectedTreatments) ? 'checked' : '' ?>>
                                                            <label class="form-check-label"
                                                                for="bridges">Bridges</label>
                                                        </div>
                                                        <div class="form-check">
                                                            <input class="form-check-input" type="checkbox"
                                                                value="fillings" id="fillings" name="treatment[]"
                                                                <?= isset($selectedTreatments) && in_array('fillings', $selectedTreatments) ? 'checked' : '' ?>>
                                                            <label class="form-check-label"
                                                                for="fillings">Fillings</label>
                                                        </div>
                                                    </div>
                                                    <!-- <div class="d-flex justify-content-between flex-wrap flex-md-nowrap">
                                                   
                                                </div> -->
                                                    <div class="row">
                                                        <div class="form-check">
                                                            <input class="form-check-input" type="checkbox"
                                                                value="sedation" id="sedation" name="treatment[]"
                                                                <?= isset($selectedTreatments) && in_array('sedation', $selectedTreatments) ? 'checked' : '' ?>>
                                                            <label class="form-check-label"
                                                                for="sedation">Sedation</label>
                                                        </div>
                                                        <div class="form-check">
                                                            <input class="form-check-input" type="checkbox"
                                                                value="childrensdentist" id="childrensdentist"
                                                                name="treatment[]"
                                                                <?= isset($selectedTreatments) && in_array('childrensdentist', $selectedTreatments) ? 'checked' : '' ?>>
                                                            <label class="form-check-label"
                                                                for="childrensdentist">Childrens Dentist</label>
                                                        </div>
                                                        <div class="form-check">
                                                            <input class="form-check-input" type="checkbox"
                                                                value="periodontal" id="periodontal" name="treatment[]"
                                                                <?= isset($selectedTreatments) && in_array('periodontal', $selectedTreatments) ? 'checked' : '' ?>>
                                                            <label class="form-check-label"
                                                                for="periodontal">Periodontal Treatment For Gum
                                                                Disease</label>
                                                        </div>
                                                        <div class="form-check">
                                                            <input class="form-check-input" type="checkbox"
                                                                value="botox" id="botox" name="treatment[]"
                                                                <?= isset($selectedTreatments) && in_array('botox', $selectedTreatments) ? 'checked' : '' ?>>
                                                            <label class="form-check-label" for="botox">Botox and
                                                                Fillers</label>
                                                        </div>
                                                        <div class="form-check">
                                                            <input class="form-check-input" type="checkbox"
                                                                value="cosmetic" id="cosmetic" name="treatment[]"
                                                                <?= isset($selectedTreatments) && in_array('cosmetic', $selectedTreatments) ? 'checked' : '' ?>>
                                                            <label class="form-check-label" for="cosmetic">Cosmetic
                                                                Treatment</label>
                                                        </div>
                                                        <div class="form-check">
                                                            <input class="form-check-input" type="checkbox"
                                                                value="splint" id="splint" name="treatment[]"
                                                                <?= isset($selectedTreatments) && in_array('splint', $selectedTreatments) ? 'checked' : '' ?>>
                                                            <label class="form-check-label" for="splint">Splint
                                                                Therapy</label>
                                                        </div>
                                                        <div class="form-check">
                                                            <input class="form-check-input" type="checkbox"
                                                                value="sleepapnea" id="sleepapnea" name="treatment[]"
                                                                <?= isset($selectedTreatments) && in_array('sleepapnea', $selectedTreatments) ? 'checked' : '' ?>>
                                                            <label class="form-check-label" for="sleepapnea">Sleep Apnea
                                                                Treatment</label>
                                                        </div>
                                                    </div>

                                                </div>
                                            </div>


                                        </div>
                                    </div>

                                    <div class="col-md-12 my-2">
                                        <label class="fLabel" for="willingToTravel">How far are you willing to
                                            travel?</label>
                                        <select name="willingToTravel" id="willingToTravel" class="form-select fselect"
                                            required>
                                            <option value="" <?= $user->willingToTravel === '' ? 'selected' : '' ?>>
                                                Select</option>
                                            <option value="5km" <?= $user->willingToTravel === '5' ? 'selected' : '' ?>>
                                                Up to 5 km</option>
                                            <option value="10km"
                                                <?= $user->willingToTravel === '10' ? 'selected' : '' ?>>Up to 10 km
                                            </option>
                                            <option value="20km"
                                                <?= $user->willingToTravel === '20' ? 'selected' : '' ?>>Up to 20 km
                                            </option>
                                            <option value="30km"
                                                <?= $user->willingToTravel === '30' ? 'selected' : '' ?>>Up to 30 km
                                            </option>
                                            <option value="40km"
                                                <?= $user->willingToTravel === '40' ? 'selected' : '' ?>>Up to 40 km
                                            </option>
                                            <option value="50km"
                                                <?= $user->willingToTravel === '50' ? 'selected' : '' ?>>Up to 50 km
                                            </option>
                                            <option value="no-limit"
                                                <?= $user->willingToTravel === 'no-limit' ? 'selected' : '' ?>>No limit
                                            </option>
                                        </select>

                                    </div>

                                    <div class="col-md-12 my-2">
                                        <label class="fLabel" for="importantClinic">What's important to you when
                                            considering which clinic you would like to have dental treatment?</label>
                                        <select name="importantClinic" id="importantClinic" class="form-select fselect"
                                            required>
                                            <option value="" <?= $user->importantClinic === '' ? 'selected' : '' ?>>
                                                Select</option>
                                            <option value="location"
                                                <?= $user->importantClinic === 'location' ? 'selected' : '' ?>>Location
                                            </option>
                                            <option value="reviews"
                                                <?= $user->importantClinic === 'reviews' ? 'selected' : '' ?>>Reviews
                                            </option>
                                            <option value="cost"
                                                <?= $user->importantClinic === 'cost' ? 'selected' : '' ?>>Cost</option>
                                            <option value="experience"
                                                <?= $user->importantClinic === 'experience' ? 'selected' : '' ?>>
                                                Experience of the dentist</option>
                                            <option value="facilities"
                                                <?= $user->importantClinic === 'facilities' ? 'selected' : '' ?>>
                                                Facilities</option>
                                            <option value="availability"
                                                <?= $user->importantClinic === 'availability' ? 'selected' : '' ?>>
                                                Availability of appointments</option>
                                        </select>
                                    </div>

                                    <div class="col-md-12 my-2">
                                        <label class="fLabel" for="knowAbout">Is there anything else the dentist should
                                            know about?</label>
                                        <textarea name="knowAbout" id="knowAbout" class="form-control formInput"
                                            placeholder="Enter"
                                            required><?= htmlspecialchars($user->knowAbout) ?></textarea>
                                    </div>


                                    <div class="col-md-12 d-flex justify-content-between">
                                        <button type="button" class="btn btnLog  py-2 px-5"
                                            onclick="previousStep()">Previous</button>
                                        <button type="button" class="btn btnLog  py-2 px-5"
                                            onclick="nextStep(3)">Next</button>
                                    </div>
                                </div>


                                <div class="row step step3" id="step3">
                                    <div id="loading">
                                        <img src="https://buzzwaretech.com/dentifyduser/assets/1479.gif"
                                            alt="Loading..." />
                                        <p>Loading...</p>
                                    </div>
                                    <p class="fs4">Photo Upload</p>
                                    <p class="fs3">Please see the best way to take the photos below.You need to
                                        take 4 photos in total: As in pdf, clinic letters jpeg, png etc</p>
                                    <div class="col-md-12">
                                        <label for="" class="fLabel">Please upload any details that will help including
                                            radiographs, treatment plans, recent
                                            dental letters from clinics/ hospitals?</label>
                                        <label for=""></label>
                                        <label class="btn btnUplaod" for="photos">Tap To Upload pdf,jpeg or png</label>
                                    </div>
                                    <div class="col-md-12 my-2">
                                        <!--step1-->
                                        <div class="row my-2">
                                            <p class="fLabel fw-bold mb-1">Step 1</p>
                                            <p class="fLabelmb-0">Insert the two large spoons with the curved side
                                                towards the teeth</p>
                                            <div class="col-md-6 my-2">
                                                <div class="photoCard d-flex justify-content-center align-items-center"
                                                    id="image1">
                                                    <!-- assets/images/t4.png -->
                                                    <img src="<?= base_url('assets/images/1new.png'); ?>" alt="">
                                                </div>
                                            </div>
                                            <div class="col-md-6 my-2">
                                                <div class="photoCard d-flex justify-content-center align-items-center">
                                                    <!-- assets/images/t4.png -->
                                                    <img src="<?= base_url('assets/images/2new.png'); ?>" alt="">
                                                </div>
                                            </div>

                                            <div class="col-md-6 my-2">
                                                <!-- first input -->
                                                <!-- <input type="file" id="upload_image1" name="upload_image1"
                                                    class="d-none" accept="jpg,png" onchange="previewImage(this)"> -->
                                                <div class="btn-group p-2" role="group" aria-label="Instance 1">
                                                    <button type="button" class="btn btnphUpl" id="selectPhotoBtn1">
                                                        <img src="<?= base_url('assets/images/upl.png'); ?>" alt="">
                                                        Select Image From Gallery
                                                    </button>
                                                    <button type="button" class="btn btnphUpl" id="captureBtn1">
                                                        <img src="<?= base_url('assets/images/cam.png'); ?>" alt="">
                                                        Capture Image From Camera
                                                    </button>
                                                </div>
                                                <div class="alert alert-success d-none" role="alert" id="alertfound1">
                                                    Image Found
                                                </div>
                                                <div class="alert alert-danger d-none" role="alert" id="alerterror1">
                                                    Something went Wronge Try Again
                                                </div>
                                                <label for="upload_image1"
                                                    class="photoCard d-flex justify-content-center align-items-center UplCard">
                                                    <div>
                                                        <img class="d-block mx-auto" style="width:300px;height:250px;"
                                                            src="<?php echo isset($user->upload_image1) && $user->upload_image1 !== 'undefined' ? base_url($user->upload_image1) : ''; ?>"
                                                            alt="">

                                                        <p class="fss1 mb-0">Upload Photo</p>
                                                    </div>
                                                </label>
                                                <!--  -->
                                            </div>
                                            <div class="col-md-6 my-2">
                                                <!-- 2 input -->
                                                <!-- <input type="file" id="upload_image2" name="upload_image2"
                                                    class="d-none" accepct="jpg,png" onchange="previewImage(this)"> -->
                                                <div class="btn-group p-2" role="group" aria-label="Instance 2">
                                                    <button type="button" class="btn btnphUpl" id="selectPhotoBtn2">
                                                        <img src="<?= base_url('assets/images/upl.png'); ?>" alt="">
                                                        Select Image From Gallery
                                                    </button>
                                                    <button type="button" class="btn btnphUpl" id="captureBtn2">
                                                        <img src="<?= base_url('assets/images/cam.png'); ?>" alt="">
                                                        Capture Image From Camera
                                                    </button>
                                                </div>
                                                <div class="alert alert-success d-none" role="alert" id="alertfound2">
                                                    Image Found
                                                </div>
                                                <div class="alert alert-danger d-none" role="alert" id="alerterror2">
                                                    Something went Wronge Try Again
                                                </div>
                                                <label for="upload_image2"
                                                    class="photoCard d-flex justify-content-center align-items-center UplCard">
                                                    <div>
                                                        <img class="d-block mx-auto" style="width:300px;height:250px;"
                                                            src="<?php echo isset($user->upload_image2) && $user->upload_image2 !== 'undefined' ? base_url($user->upload_image2) : ''; ?>"
                                                            alt="">

                                                        <p class="fss1 mb-0">Upload Photo</p>
                                                    </div>
                                                </label>
                                                <!--  -->
                                            </div>
                                        </div>

                                        <div class="row my-2">
                                            <p class="fLabel fw-bold mb-1">Step 2</p>
                                            <p class="fLabelmb-0">Take two small picture of upper and lower dental arch
                                            </p>
                                            <div class="col-md-6 my-2">
                                                <div class="photoCard d-flex justify-content-center align-items-center">
                                                    <img src="<?= base_url('assets/images/3new.png'); ?>" alt="">
                                                </div>
                                            </div>
                                            <div class="col-md-6 my-2">
                                                <div class="photoCard d-flex justify-content-center align-items-center">
                                                    <img src="<?= base_url('assets/images/4new.png'); ?>" alt="">
                                                </div>
                                            </div>
                                            <div class="col-md-6 my-2">
                                                <!-- 5 input -->
                                                <!-- <input type="file" id="upload_image5" name="upload_image5"
                                                    class="d-none" accepct="jpg,png" onchange="previewImage(this)"> -->
                                                <label for="upload_image5"
                                                    class="photoCard d-flex justify-content-center align-items-center UplCard">
                                                    <div>
                                                        <div class="btn-group p-2" role="group" aria-label="Instance 5">
                                                            <button type="button" class="btn btnphUpl"
                                                                id="selectPhotoBtn5">
                                                                <img src="<?= base_url('assets/images/upl.png'); ?>"
                                                                    alt="">
                                                                Select Image From Gallery
                                                            </button>
                                                            <button type="button" class="btn btnphUpl" id="captureBtn5">
                                                                <img src="<?= base_url('assets/images/cam.png'); ?>"
                                                                    alt="">
                                                                Capture Image From Camera
                                                            </button>
                                                        </div>
                                                        <div class="alert alert-success d-none" role="alert"
                                                            id="alertfound5">
                                                            Image Found
                                                        </div>
                                                        <div class="alert alert-danger d-none" role="alert"
                                                            id="alerterror5">
                                                            Something went Wronge Try Again
                                                        </div>
                                                        <img class="d-block mx-auto" style="width:300px;height:250px;"
                                                            src="<?php echo isset($user->upload_image5) && $user->upload_image5 !== 'undefined' ? base_url($user->upload_image5) : ''; ?>"
                                                            alt="">

                                                        <p class="fss1 mb-0">Upload Photo</p>
                                                    </div>
                                                </label>
                                                <!--  -->
                                            </div>
                                            <div class="col-md-6 my-2">

                                                <div class="btn-group p-2" role="group" aria-label="Instance 6">
                                                    <button type="button" class="btn btnphUpl" id="selectPhotoBtn6">
                                                        <img src="<?= base_url('assets/images/upl.png'); ?>" alt="">
                                                        Select Image From Gallery
                                                    </button>
                                                    <button type="button" class="btn btnphUpl" id="captureBtn6">
                                                        <img src="<?= base_url('assets/images/cam.png'); ?>" alt="">
                                                        Capture Image From Camera
                                                    </button>
                                                </div>
                                                <div class="alert alert-success d-none" role="alert" id="alertfound6">
                                                    Image Found
                                                </div>
                                                <div class="alert alert-danger d-none" role="alert" id="alerterror6">
                                                    Something went Wronge Try Again
                                                </div>
                                                <label for="upload_image6"
                                                    class="photoCard d-flex justify-content-center align-items-center UplCard">
                                                    <div>
                                                        <img class="d-block mx-auto" style="width:300px;height:250px;"
                                                            src="<?php echo isset($user->upload_image6) && $user->upload_image6 !== 'undefined' ? base_url($user->upload_image6) : ''; ?>"
                                                            alt="">

                                                        <p class="fss1 mb-0">Upload Photo</p>
                                                    </div>
                                                </label>
                                                <!--  -->
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-12 my-2 d-flex justify-content-between">
                                        <button type="button" class="btn btnLog  py-2 px-5"
                                            onclick="previousStep()">Previous</button>
                                        <button type="submit" class="btn btnLog  py-2 px-5"
                                            id="submitBtn">Update</button>
                                    </div>


                            </form>
                        </div>
                    </div>

    
                </div>

            </div>
        </div>
    </div>
</div>

<!-- Modals for Instance 1 -->
<div class="modal fade" id="cameraModal1" tabindex="-1" aria-labelledby="cameraModalLabel1" aria-hidden="true"
    data-bs-backdrop="false">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="p-2 d-flex justify-content-between">
                <h5 class="modal-title" id="cameraModalLabel1">Capture Photo</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <!-- Video Stream for Camera -->
                <div class="video-wrapper">
                    <video id="video1" autoplay class=""></video>
                </div>
            </div>
            <div class="p-2 d-flex justify-content-end">
                <!-- Capture Photo Button in Modal -->
                <button type="button" class="btn btn-primary SavBtn" id="capturePhotoBtn1" data-bs-dismiss="modal"
                    aria-label="Close">
                    Capture Photo
                </button>
            </div>
        </div>
    </div>
</div>
<!-- File Input -->
<input type="file" name="image1" id="upload_image1" class="d-none" accept="image/*" onchange="previewImage(this)" />
<input type="hidden" name="image_data1" id="image_data1" />
<!-- Gallery Modal -->
<div class="modal fade" id="gallery1" data-bs-backdrop="false">
    <div class="modal-dialog">
        <div class="modal-content p-2">
            <div class="d-flex justify-content-end">
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="col-md-12">
                    <div class="cardCap2">
                        <div id="photo1"></div>
                    </div>
                </div>
                <div class="col-md-12">
                    <div id="errorpic1" class="alert alert-danger" style="display: none">
                        <strong>Error!</strong> Picture Invalid.
                    </div>
                    <div id="loading1">
                        <img src="https://buzzwaretech.com/dentifyduser/assets/1479.gif" alt="Loading..." />
                        <p>Loading...</p>
                    </div>
                    <div class="d-flex justify-content-between">
                        <button class="btn chngBtn px-5" id="changeBtn1" data-bs-dismiss="modal"
                            aria-label="Close">Change</button>
                        <button type="submit" class="btn SavBtn px-5" id="submit1">Save</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- Hidden Canvas to Capture Image -->
<canvas id="canvas1" class="d-none"></canvas>
<!-- End Modals for Instance 1 -->

<!-- Repeat the above structure for instances 2, 3, 4, 5, and 6 with unique IDs -->

<!-- Modals for Instance 2 -->
<div class="modal fade" id="cameraModal2" tabindex="-1" aria-labelledby="cameraModalLabel2" aria-hidden="true"
    data-bs-backdrop="false">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="p-2 d-flex justify-content-between">
                <h5 class="modal-title" id="cameraModalLabel2">Capture Photo</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <!-- Video Stream for Camera -->
                <div class="video-wrapper">
                    <video id="video2" autoplay class=""></video>
                </div>
            </div>
            <div class="p-2 d-flex justify-content-end">
                <!-- Capture Photo Button in Modal -->
                <button type="button" class="btn btn-primary SavBtn" id="capturePhotoBtn2" data-bs-dismiss="modal"
                    aria-label="Close">
                    Capture Photo
                </button>
            </div>
        </div>
    </div>
</div>
<!-- File Input -->
<input type="file" name="image2" id="upload_image2" class="d-none" accept="image/*" onchange="previewImage(this)" />
<input type="hidden" name="image_data2" id="image_data2" />
<!-- Gallery Modal -->
<div class="modal fade" id="gallery2" data-bs-backdrop="false">
    <div class="modal-dialog">
        <div class="modal-content p-2">
            <div class="d-flex justify-content-end">
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="col-md-12">
                    <div class="cardCap2">
                        <div id="photo2"></div>
                    </div>
                </div>
                <div class="col-md-12">
                    <div id="errorpic2" class="alert alert-danger" style="display: none">
                        <strong>Error!</strong> Picture Invalid.
                    </div>
                    <div id="loading2">
                        <img src="https://buzzwaretech.com/dentifyduser/assets/1479.gif" alt="Loading..." />
                        <p>Loading...</p>
                    </div>
                    <div class="d-flex justify-content-between">
                        <button class="btn chngBtn px-5" id="changeBtn2" data-bs-dismiss="modal"
                            aria-label="Close">Change</button>
                        <button type="submit" class="btn SavBtn px-5" id="submit2">Save</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- Hidden Canvas to Capture Image -->
<canvas id="canvas2" class="d-none"></canvas>
<!-- End Modals for Instance 2 -->

<!-- Modals for Instance 5 -->
<div class="modal fade" id="cameraModal5" tabindex="-1" aria-labelledby="cameraModalLabel5" aria-hidden="true"
    data-bs-backdrop="false">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="p-2 d-flex justify-content-between">
                <h5 class="modal-title" id="cameraModalLabel5">Capture Photo</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <!-- Video Stream for Camera -->
                <div class="video-wrapper">
                    <video id="video5" autoplay class=""></video>
                </div>
            </div>
            <div class="p-2 d-flex justify-content-end">
                <!-- Capture Photo Button in Modal -->
                <button type="button" class="btn btn-primary SavBtn" id="capturePhotoBtn5" data-bs-dismiss="modal"
                    aria-label="Close">
                    Capture Photo
                </button>
            </div>
        </div>
    </div>
</div>
<!-- File Input -->
<input type="file" name="image5" id="upload_image5" class="d-none" accept="image/*" onchange="previewImage(this)" />
<input type="hidden" name="image_data5" id="image_data5" />
<!-- Gallery Modal -->
<div class="modal fade" id="gallery5">
    <div class="modal-dialog">
        <div class="modal-content p-2">
            <div class="d-flex justify-content-end">
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="col-md-12">
                    <div class="cardCap2">
                        <div id="photo5"></div>
                    </div>
                </div>
                <div class="col-md-12">
                    <div id="errorpic5" class="alert alert-danger" style="display: none">
                        <strong>Error!</strong> Picture Invalid.
                    </div>
                    <div id="loading5">
                        <img src="https://buzzwaretech.com/dentifyduser/assets/1479.gif" alt="Loading..." />
                        <p>Loading...</p>
                    </div>
                    <div class="d-flex justify-content-between">
                        <button class="btn chngBtn px-5" id="changeBtn5" data-bs-dismiss="modal"
                            aria-label="Close">Change</button>
                        <button type="submit" class="btn SavBtn px-5" id="submit5">Save</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- Hidden Canvas to Capture Image -->
<canvas id="canvas5" class="d-none"></canvas>
<!-- End Modals for Instance 5 -->

<!-- Modals for Instance 6 -->
<div class="modal fade" id="cameraModal6" tabindex="-1" aria-labelledby="cameraModalLabel6" aria-hidden="true"
    data-bs-backdrop="false">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="p-2 d-flex justify-content-between">
                <h5 class="modal-title" id="cameraModalLabel6">Capture Photo</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <!-- Video Stream for Camera -->
                <div class="video-wrapper">
                    <video id="video6" autoplay class=""></video>
                </div>
            </div>
            <div class="p-2 d-flex justify-content-end">
                <!-- Capture Photo Button in Modal -->
                <button type="button" class="btn btn-primary SavBtn" id="capturePhotoBtn6" data-bs-dismiss="modal"
                    aria-label="Close">
                    Capture Photo
                </button>
            </div>
        </div>
    </div>
</div>
<!-- File Input -->
<input type="file" name="image6" id="upload_image6" class="d-none" accept="image/*" onchange="previewImage(this)" />
<input type="hidden" name="image_data6" id="image_data6" />
<!-- Gallery Modal -->
<div class="modal fade" id="gallery6">
    <div class="modal-dialog">
        <div class="modal-content p-2">
            <div class="d-flex justify-content-end">
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="col-md-12">
                    <div class="cardCap2">
                        <div id="photo6"></div>
                    </div>
                </div>
                <div class="col-md-12">
                    <div id="errorpic6" class="alert alert-danger" style="display: none">
                        <strong>Error!</strong> Picture Invalid.
                    </div>
                    <div id="loading6">
                        <img src="https://buzzwaretech.com/dentifyduser/assets/1479.gif" alt="Loading..." />
                        <p>Loading...</p>
                    </div>
                    <div class="d-flex justify-content-between">
                        <button class="btn chngBtn px-5" id="changeBtn6" data-bs-dismiss="modal"
                            aria-label="Close">Change</button>
                        <button type="submit" class="btn SavBtn px-5" id="submit6">Save</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- Hidden Canvas to Capture Image -->
<canvas id="canvas6" class="d-none"></canvas>
<!-- End Modals for Instance 6 -->
</div>
<script>
    document.addEventListener("DOMContentLoaded", function() {
        // Check if medication is already set (Yes/No)
        let medicationYes = document.getElementById("medication_yes");
        let medicationNo = document.getElementById("medication_no");

        if (!medicationYes.checked && !medicationNo.checked) {
            // Show alert only if no value is set
            Swal.fire({
                title: "Would you like more details?",
                text: "Please click on the Next button for more details.",
                icon: "question",
                confirmButtonText: "OK"
            });
        }
    });

    function nextStep(step) {
        let medicationYes = document.getElementById("medication_yes");
        let medicationNo = document.getElementById("medication_no");

        // If neither Yes nor No is selected, show an alert
        if (!medicationYes.checked && !medicationNo.checked) {
            Swal.fire({
                title: "Selection Required",
                text: "Please select Yes or No before proceeding.",
                icon: "warning",
                confirmButtonText: "OK"
            });
        } else {
            // Proceed to the next step
            console.log("Proceeding to Step:", step);
            // Your existing logic for the next step
        }
    }
</script>

<script>
    let allImageCorrect = false; // This flag will be set to true only if all images are valid
    const totalImages = 6; // Total number of images to validate
    const imageValidationStatus = {}; // Object to track validation status for each inpu
    document.addEventListener("DOMContentLoaded", function() {
        let currentStep = 1;
        showStep(currentStep);

        function showStep(step) {
            const steps = document.querySelectorAll('.step');
            steps.forEach((el, index) => {
                el.classList.remove('active');
                if (index === step - 1) {
                    el.classList.add('active');
                }
            });
        }

        window.nextStep = function() {
            const requiredInputs = document.querySelectorAll(`#step${currentStep} [required]`);
            const missingFields = [];

            requiredInputs.forEach(input => {
                if ((input.type === 'radio' && !document.querySelector(
                        `input[name="${input.name}"]:checked`)) || !input.value) {
                    missingFields.push(input.previousElementSibling ? input.previousElementSibling
                        .innerText : '');
                    input.classList.add('border-danger');
                    input.parentElement.classList.add('border-danger');
                } else {
                    input.classList.remove('border-danger');
                    input.parentElement.classList.remove('border-danger');
                }
            });



            if (currentStep === 3) {

                const checkboxes = document.querySelectorAll('#treatmentForm input[name="treatment[]"]');
                let isChecked = false;

                // Check if at least one checkbox is checked
                checkboxes.forEach(checkbox => {
                    if (checkbox.checked) {
                        isChecked = true;
                    }
                });

                // If none are checked, show an error and stop
                if (!isChecked) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'Please select at least one treatment option before proceeding.',
                    });
                    return;
                }
            }

            // Proceed to the next step
            currentStep++;
            showStep(currentStep);
        }

        window.previousStep = function() {
            if (currentStep > 1) {
                currentStep--;
                showStep(currentStep);
            }
        }

        document.getElementById('submitBtn').addEventListener('click', function(event) {
            event.preventDefault();

            const requiredInputs = document.querySelectorAll(`.step.active [required]`);
            const missingFields = [];
            let missingFiles = false;

            requiredInputs.forEach(input => {
                if ((input.type === 'radio' && !document.querySelector(
                        `input[name="${input.name}"]:checked`)) || !input.value) {
                    if (input.type === 'file') {
                        missingFiles = true;
                    } else {
                        missingFields.push(input.previousElementSibling ? input
                            .previousElementSibling.innerText : '');
                    }
                    input.classList.add('border-danger');
                } else {
                    input.classList.remove('border-danger');
                }
            });

            if (currentStep === 4) {
                const fileInputs = [{
                        id: 'upload_image1',
                        oldSrc: '<?php echo base_url($user->upload_image1); ?>'
                    },
                    {
                        id: 'upload_image2',
                        oldSrc: '<?php echo base_url($user->upload_image2); ?>'
                    },
                    {
                        id: 'upload_image3',
                        oldSrc: '<?php echo base_url($user->upload_image3); ?>'
                    },
                    {
                        id: 'upload_image4',
                        oldSrc: '<?php echo base_url($user->upload_image4); ?>'
                    },
                    {
                        id: 'upload_image5',
                        oldSrc: '<?php echo base_url($user->upload_image5); ?>'
                    },
                    {
                        id: 'upload_image6',
                        oldSrc: '<?php echo base_url($user->upload_image6); ?>'
                    }
                ];

                let missingFiles = false;

                fileInputs.forEach(({
                    id,
                    oldSrc
                }) => {
                    const fileInput = document.getElementById(id);

                    if (!fileInput.files.length && !oldSrc) {
                        missingFiles = true;
                    }
                });


                if (missingFields.length > 0) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: "Please fill out the following required fields",
                    });
                    return;
                }

            }

            const formData = new FormData();

            const discussMedical = document.getElementById("discuss_medical");
            const discussMedication = document.getElementById("discuss_medication");

            formData.append('discuss_medical', discussMedical.value);
            formData.append('discuss_medication', discussMedication.value);


            formData.append('complaint', document.getElementById('complaint').value);
            formData.append('problem', document.getElementById('problem').value);
            formData.append('symptoms', document.getElementById('symptoms').value);
            formData.append('discuss', document.getElementById('discuss').value);
            formData.append('medicalCondition', document.querySelector(
                'input[name="medical_condition"]:checked')?.id || '');
            formData.append('medication', document.querySelector('input[name="medication"]:checked')?.id ||
                '');
            let selectedTreatments = Array.from(document.querySelectorAll(
                'input[name="treatment[]"]:checked')).map(input => input.value);
            if (selectedTreatments.length > 0) {
                formData.append('treatments', JSON.stringify(selectedTreatments));
            } else {
                formData.append('treatments', '');
            }
            formData.append('willingToTravel', document.getElementById('willingToTravel').value);
            formData.append('importantClinic', document.getElementById('importantClinic').value);
            formData.append('knowAbout', document.getElementById('knowAbout').value);

            for (let i = 1; i <= 6; i++) {
                // const fileInput = document.getElementById(`upload_image${i}`);
                const hiddenInput = document.getElementById(`image_data${i}`);


                // If the hidden input has a value (base64 image data), append it to the form data
                formData.append(`upload_image${i}`, hiddenInput.value);


            }

            $.ajax({
                type: "POST",
                url: "<?php echo base_url() . 'Site/addIssueData'; ?>",
                data: formData,
                contentType: false,
                cache: false,
                processData: false,
                success: function(data) {
                    console.log(data);
                    var json = JSON.parse(data);
                    if (json.success === 1) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Success',
                            text: 'Updated successfully.',
                            confirmButtonText: 'OK'
                        });

                        window.location.href = "<?php echo base_url(); ?>Site/editprofile";
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Oops...',
                            text: json.error
                        });
                    }
                },
                error: function(xhr, status, error) {

                    Swal.fire({
                        icon: 'error',
                        title: 'Oops...',
                        text: 'An unexpected error occurred. Please try again later.'
                    });
                }
            });


        });
        document.querySelectorAll('.formInput input[type="radio"]').forEach((radio) => {
            radio.addEventListener('change', function() {
                const groupName = this.name;

                document.querySelectorAll(`input[name="${groupName}"]`).forEach((input) => {
                    input.parentElement.style.border = '1px solid #e9e9e9';
                });

                if (this.checked) {
                    this.parentElement.style.border = '1px solid #064EA3';
                }
            });
        });
    });


    function mytestt(base64image, alertfound, alerterror, id) {
        console.log("image id is", id)
        document.getElementById(`${id}`).value = base64image
        return new Promise((resolve) => {

            $("#loading").show();
            var asticaAPI_endpoint = "https://vision.astica.ai/describe";
            var asticaAPI_payload = {
                tkn: "CD798B27-985F-4ECB-9C93-385D1209B5422533354E7FB71C-08CB-40B6-9DC2-0B38B03CF318",
                modelVersion: "2.5_full",
                input: base64image,
                visionParams: "gpt, describe, describe_all, tags",
                gpt_prompt: "",
                prompt_length: 95,
                objects_custom_kw: "",
            };

            fetch(asticaAPI_endpoint, {
                    method: "post",
                    body: JSON.stringify(asticaAPI_payload),
                    headers: {
                        "Content-Type": "application/json",
                    },
                    mode: "cors",
                })
                .then((response) => response.json())
                .then((data) => {
                    console.log("astica Vision AI Results");
                    console.log(data);
                    console.log(data.tags);

                    var filteredData = data.tags.filter((obj) => obj.confidence > 0.85);
                    var customString = filteredData.map((obj) => obj.name).join(", ");
                    console.log("customString", customString);
                    console.log(data.caption_GPTS);
                    const description = data.caption_GPTS;

                    // var keywords = ["teeth", "tooth", "laugh", "teeth", "smile"];
                    // var keywords2 = ["head", "forhead", "eyes", "eye"];

                    var keywords = ["teeth", "tooth", "smile", "laugh", "grin", "dental", "incisor", "molar", "gum", "denture", "smirk"];
                    var keywords2 = ["head", "forehead", "face", "facial", "cheeks", "eyes", "eye", "nose", "ears", "hairs"];

                    var found = checkKeywords(description, keywords);
                    if (found) {
                        var found1 = checkKeywords(customString, keywords2);
                        if (found1) {
                            $("#errorpic").show();
                            $("#loading").hide();
                            // alertfound.innerText = "Image is Invalid";
                            alerterror.innerText = "Image is Invalid ! Please upload corret Image"
                            alertfound.classList.remove("d-block");
                            alertfound.classList.add("d-none");
                            alerterror.classList.add("d-block");
                            alerterror.classList.remove("d-none");
                            console.log("invalid");
                            resolve(false);
                        } else {
                            alertfound.innerText = "Image is valid";
                            alerterror.classList.remove("d-block");
                            alerterror.classList.add("d-none");
                            alertfound.classList.add("d-block");
                            alertfound.classList.remove("d-none");

                            console.log("valid");
                            $("#errorpic").hide();
                            $("#loading").hide();
                            $("#submit").removeAttr("disabled");
                            resolve(true);
                        }
                    } else {
                        alerterror.innerText = "Image is Invalid ! Please upload corret Image"
                        alertfound.classList.remove("d-block");
                        alertfound.classList.add("d-none");
                        alerterror.classList.add("d-block");
                        alerterror.classList.remove("d-none");
                        console.log("main invalid1");

                        $("#loading").hide();
                        $("#errorpic").show();
                        resolve(false);
                    }
                })
                .catch((error) => {

                    $("#loading").hide();
                    console.log("Error:", error);

                    // this is for testing purpose
                    // alertfound.innerText = "Image is valid";
                    // alertfound.classList.toggle("d-none");
                    // resolve(true);

                    // use this on error 

                    alerterror.innerText = "Something went wrong. Please try again.";
                    alertfound.classList.remove("d-block");
                    alertfound.classList.add("d-none");
                    alerterror.classList.add("d-block");
                    alerterror.classList.remove("d-none");
                    resolve(false);
                });
        });
    }

    function convertFileToBase64(file) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = () => resolve(reader.result);
            reader.onerror = (error) => reject(error);
        });
    }



    document.addEventListener("DOMContentLoaded", function() {
        for (let i = 1; i <= 6; i++) {
            const alertfound = document.getElementById(`alertfound${i}`)
            const alerterror = document.getElementById(`alerterror${i}`)
            const selectPhotoBtn = document.getElementById(`selectPhotoBtn${i}`);
            const uploadPhoto = document.getElementById(`upload_image${i}`);
            const captureBtn = document.getElementById(`captureBtn${i}`);
            const capturePhotoBtn = document.getElementById(`capturePhotoBtn${i}`);
            const video = document.getElementById(`video${i}`);
            const canvas = document.getElementById(`canvas${i}`);
            const photoDiv = document.getElementById(`photo${i}`);
            let streaming = false;

            // When "Select Photo from File" is clicked
            selectPhotoBtn.addEventListener("click", function() {
                // Trigger click event on the uploadPhoto input to open file selection
                uploadPhoto.click();
            });


            uploadPhoto.addEventListener("change", async function(event) {
                const inputId = event.target.id;
                const file = event.target.files[0];
                if (file) {

                    // Convert the selected file to base64
                    const base64Image = await convertFileToBase64(file);
                    if (i <= 1) {
                        const isValid = await mytestt(base64Image, alertfound, alerterror,
                            `image_data${i}`);
                        allImageCorrect = isValid
                    }
                    console.log(`Base64 Image from File ${i}:`, base64Image);
                    // const isValid = await mytestt(base64Image, alertfound, alerterror,
                    // `image_data${i}`);
                    document.getElementById(`image_data${i}`).value = base64Image;
                    // imageValidationStatus[inputId] = isValid;
                    console.log(imageValidationStatus)
                    // allImageCorrect = Object.keys(imageValidationStatus).length === totalImages &&
                    //     Object.values(imageValidationStatus).every((status) => status === true);

                    console.log(`All Images Correct: ${allImageCorrect}`);
                    // Display the selected image
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        const img = document.createElement("img");
                        img.src = e.target.result;
                        img.classList.add("img-fluid");
                        photoDiv.innerHTML = ""; // Clear previous content
                        photoDiv.appendChild(img);
                    };
                    reader.readAsDataURL(file);
                }

                // const galleryModel = new bootstrap.Modal(
                //     document.getElementById(`gallery${i}`)
                // );
                // galleryModel.show();
            });


            // Open modal and start camera streaming when "Capture Online" button is clicked
            captureBtn.addEventListener("click", async function() {
                const cameraModal = new bootstrap.Modal(
                    document.getElementById(`cameraModal${i}`)
                );
                cameraModal.show();

                if (!streaming) {
                    try {
                        const stream = await navigator.mediaDevices.getUserMedia({
                            video: true,
                            zoom: true,
                        });
                        video.srcObject = stream;
                        streaming = true;
                    } catch (error) {
                        console.error(`Error accessing the camera ${i}:`, error);
                        alert("Unable to access the camera.");
                    }
                }
            });


            capturePhotoBtn.addEventListener("click", async function(event) {
                if (streaming) {
                    const context = canvas.getContext("2d");
                    canvas.width = video.videoWidth;
                    canvas.height = video.videoHeight;
                    context.drawImage(video, 0, 0, video.videoWidth, video.videoHeight);

                    const imageDataURL = canvas.toDataURL("image/png");
                    console.log(`Captured Image Data URL ${i}:`, imageDataURL);
                    if (i <= 1) {
                        console.log("in if")
                        const isValid = await mytestt(imageDataURL, alertfound, alerterror,
                            `image_data${i}`);
                        allImageCorrect = isValid
                    }
                    video.srcObject.getTracks().forEach((track) => track.stop());
                    streaming = false;
                    const hiddenInput = document.getElementById(`image_data${i}`);
                    if (hiddenInput) {
                        hiddenInput.value = imageDataURL;
                    }
                    const img = document.createElement("img");
                    img.src = imageDataURL;
                    img.classList.add("img-fluid");

                    photoDiv.innerHTML = ""; // Clear previous content
                    photoDiv.appendChild(img);
                    const label = document.querySelector(`label[for="upload_image${i}"]`)
                    console.log("label", label)
                    if (label) {
                        const imgElement = label.querySelector('img');
                        if (imgElement) {
                            imgElement.src = imageDataURL;
                            imgElement.classList.add(
                                "imgUploaded");
                        }
                    }
                    const cameraModal = new bootstrap.Modal(
                        document.getElementById(`cameraModal${i}`)
                    );
                    cameraModal.hide();
                }
            });
        }

        // Function to convert a file to Base64
        function convertFileToBase64(file) {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = () => resolve(reader.result);
                reader.onerror = (error) => reject(error);
            });
        }
    });
</script>