  
  </main>
  <!--end main wrapper-->


    <!--start overlay-->
    <div class="overlay btn-toggle"></div>
    <!--end overlay-->



     




<!--bootstrap js-->
    <script src="<?php echo base_url(); ?>assets/js/bootstrap.bundle.min.js"></script>

    <!--plugins-->
    <!-- <script src="<?php echo base_url(); ?>assets/js/jquery.min.js"></script> -->
    <!--plugins-->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="<?php echo base_url(); ?>assets/plugins/perfect-scrollbar/js/perfect-scrollbar.js"></script>
    <script src="<?php echo base_url(); ?>assets/plugins/metismenu/metisMenu.min.js"></script>

    <script src="<?php echo base_url(); ?>assets/js/index2.js"></script>
    <script src="<?php echo base_url(); ?>assets/js/main.js"></script>
    <!-- appax chart -->
    <script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
    <!-- moment js -->
    <script type="text/javascript" src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
    <!-- data rane picker -->
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <script>
        const totalUsers = 6000;
        const activeUsers = 4000;
        const inactiveUsers = totalUsers - activeUsers;

        const options = {
            tooltip: {
                enabled: false // Disable hover popup
            },
            chart: {
                type: 'donut',
                background: 'transparent', // Ensure no background padding
                height: 130

            },
            series: [activeUsers, inactiveUsers],
            labels: ['Active Users', 'Inactive Users'],
            colors: ['#989898', '#fff'],
            legend: {
                show: false
            },
            dataLabels: {
                enabled: false,
                formatter: function (val, opts) {
                    return opts.w.globals.series[opts.seriesIndex] + ' Users';
                }
            },
            plotOptions: {
                pie: {
                    donut: {
                        size: '80%',
                        labels: {
                            show: true,
                            total: {
                                show: true,
                                label: 'Active',
                                color: '#fff',
                                formatter: function () {
                                    return activeUsers;
                                }
                            }
                        }
                    }
                }
            },
            stroke: {
                show: false // Remove the small area around the chart
            }
        };

        const chart = new ApexCharts(document.querySelector("#chart"), options);
        chart.render();



        // Issue chart
        const totalUIssues = 54;
        const solvedissues = 35;
        const unsolved = totalUIssues - solvedissues;

        const options2 = {
            tooltip: {
                enabled: false // Disable hover popup
            },
            chart: {
                type: 'donut',
                height: 130

            },
            series: [solvedissues, unsolved],
            labels: ['Solved', 'Remaining'],
            colors: ['#FFFFFF', '#6A8E97'], // Custom colors
            legend: {
                show: false // Hide legend
            },
            dataLabels: {
                colors: ['#fff'],
                enabled: false // Disable data labels on chart
            },
            plotOptions: {
                pie: {
                    donut: {
                        size: '80%',
                        labels: {
                            show: true,
                            total: {
                                show: true,
                                color: '#fff',
                                label: 'Solved',
                                formatter: function () {
                                    return solvedissues; // Show the solved ,issues count in the center
                                },
                                style: {
                                    fontSize: '16px', // Customize font size
                                    color: '#fff ', // Set text color to white
                                    fontWeight: 'bold' // Make text bold
                                }
                            }
                        }
                    }
                }
            },
            stroke: {
                show: false // Remove the small area around the chart
            }
        };

        const chart2 = new ApexCharts(document.querySelector("#chart45"), options2);
        chart2.render();

    </script>
     <script src="
     https://cdn.jsdelivr.net/npm/fullcalendar@6.1.15/index.global.min.js
     "></script> 
    <script src="<?php echo base_url(); ?>assets/plugins/fullcalendar/js/main.min.js"> </script>

    <!-- <script>
        document.addEventListener('DOMContentLoaded', function () {
            const calendarEl = document.getElementById('calendar');
            const titleEl = document.getElementById('custom-title');

            const calendar = new FullCalendar.Calendar(calendarEl, {
                themeSystem: 'bootstrap5',
                initialView: 'dayGridMonth', // Default view
                events: [
                    {
                        title: 'Meeting',
                        start: '2024-12-25T08:00:00',
                        color: '#67C694',
                        backgroundColor: '#67C694'
                    },
                    {
                        title: 'Workshop',
                        start: '2024-12-26T10:00:00',
                        end: '2024-12-27',
                        color: '#4686DB',
                        backgroundColor: '#4686DB'
                    }
                ],
                eventTimeFormat: {
                    hour: 'numeric',
                    minute: '2-digit',
                    meridiem: 'short' // Display time in 12-hour format with "am/pm"
                },
                dayCellDidMount: function (info) {
                    const dayEl = info.el;

                    // Highlight days with events
                    if (info.date.getDate() === 25 || info.date.getDate() === 26) {
                        dayEl.style.backgroundColor = '#4686DB'; // Light red background for event days
                    }
                },
                headerToolbar: false, // Disable default toolbar
                datesSet: function () {
                    titleEl.textContent = calendar.view.title; // Update custom title
                }
            });

            calendar.render();

            // Custom Toolbar Buttons
            document.getElementById('prev').addEventListener('click', () => {
                calendar.prev(); // Navigate to the previous view
            });

            document.getElementById('next').addEventListener('click', () => {
                calendar.next(); // Navigate to the next view
            });

            // View Switch Buttons
            document.getElementById('view-month').addEventListener('click', () => {
                calendar.changeView('dayGridMonth'); // Switch to Month view
                updateActiveButton('view-month');
            });

            document.getElementById('view-week').addEventListener('click', () => {
                calendar.changeView('timeGridWeek'); // Switch to Week view
                updateActiveButton('view-week');
            });

            document.getElementById('view-day').addEventListener('click', () => {
                calendar.changeView('timeGridDay'); // Switch to Day view
                updateActiveButton('view-day');
            });

            // Helper Function to Update Active Button
            function updateActiveButton(activeId) {
                document.querySelectorAll('.custom-toolbar .btn').forEach((btn) => {
                    btn.classList.remove('active');
                });
                document.getElementById(activeId).classList.add('active');
            }
        });

    </script> -->


    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const calendarEl = document.getElementById('calendar');
            const titleEl = document.getElementById('custom-title');

            const calendar = new FullCalendar.Calendar(calendarEl, {
                themeSystem: 'bootstrap5',
                initialView: 'dayGridMonth', // Default to Month View
                slotMinTime: "06:00:00", // Start of the time grid
                slotMaxTime: "22:00:00", // End of the time grid
                events: [
                    {
                        title: 'Case Club',
                        description: '202 Unit',
                        start: '2025-01-05T10:00:00', // Full date and time
                        allDay: false, // Ensure this is not an all-day event
                        color: '#FFA07A',
                    },
                    {
                        title: 'Meeting',
                        description: 'Client discussion',
                        start: '2025-01-22T14:00:00', // Full date and time
                        allDay: false,
                        color: '#87CEEB',
                    },
                    {
                        title: 'Team Workshop',
                        description: 'Skill development',
                        start: '2025-01-25T08:00:00', // Full date and time
                        allDay: false,
                        color: '#90EE90',
                    }
                ],
                eventTimeFormat: {
                    hour: 'numeric',
                    minute: '2-digit',
                    meridiem: 'short', // Display time in 12-hour format with "am/pm"
                },
                headerToolbar: false, // Disable default toolbar

                eventDidMount: function (info) {
                    const eventDate = info.event.start.toISOString().split('T')[0];
                    const dayCell = document.querySelector(`.fc-daygrid-day[data-date="${eventDate}"]`);
                    if (dayCell) {
                        dayCell.style.backgroundColor = '#77A7E4'; // Highlight color for event days
                    }
                },

                datesSet: function () {
                    titleEl.textContent = calendar.view.title; // Update custom title
                },

                eventContent: function (arg) {
                    const timeEl = document.createElement('div');
                    timeEl.classList.add('fc-event-time');
                    timeEl.innerHTML = arg.timeText;

                    const titleEl = document.createElement('div');
                    titleEl.classList.add('fc-event-title');
                    titleEl.innerHTML = `${arg.event.title}<br><small>${arg.event.extendedProps.description}</small>`;

                    // Combine elements into an array for rendering
                    return { domNodes: [timeEl, titleEl] };
                }
            });

            calendar.render();

            document.getElementById('prev').addEventListener('click', () => {
                calendar.prev();
            });

            document.getElementById('next').addEventListener('click', () => {
                calendar.next();
            });

            document.getElementById('view-month').addEventListener('click', () => {
                calendar.changeView('dayGridMonth');
                updateActiveButton('view-month');
            });

            document.getElementById('view-week').addEventListener('click', () => {
                calendar.changeView('listWeek');
                updateActiveButton('view-week');
            });

            function updateActiveButton(activeId) {
                document.querySelectorAll('.custom-toolbar .btn').forEach((btn) => {
                    btn.classList.remove('active');
                });
                document.getElementById(activeId).classList.add('active');
            }
        });
    </script>
<script src="https://cdn.tiny.cloud/1/ussauc9ttgnyp1hbjw2ltehhqjqfxhkp52ypbwihw0tmu3k2/tinymce/7/tinymce.min.js" referrerpolicy="origin"></script>
     <script>
        tinymce.init({
            selector: 'textarea',
            plugins: [
                // Core editing features
                'anchor', 'autolink', 'charmap', 'codesample', 'emoticons', 'image', 'link', 'lists', 'media', 'searchreplace', 'table', 'visualblocks', 'wordcount',
                // Your account includes a free trial of TinyMCE premium features
                // Try the most popular premium features until Feb 6, 2025:
                'checklist', 'mediaembed', 'casechange', 'export', 'formatpainter', 'pageembed', 'a11ychecker', 'tinymcespellchecker', 'permanentpen', 'powerpaste', 'advtable', 'advcode', 'editimage', 'advtemplate', 'ai', 'mentions', 'tinycomments', 'tableofcontents', 'footnotes', 'mergetags', 'autocorrect', 'typography', 'inlinecss', 'markdown', 'importword', 'exportword', 'exportpdf'
            ],
            toolbar: 'undo redo | blocks fontfamily fontsize | bold italic underline strikethrough | link image media table mergetags | addcomment showcomments | spellcheckdialog a11ycheck typography | align lineheight | checklist numlist bullist indent outdent | emoticons charmap | removeformat',
            tinycomments_mode: 'embedded',
            tinycomments_author: 'Author name',
            mergetags_list: [
                { value: 'First.Name', title: 'First Name' },
                { value: 'Email', title: 'Email' },
            ],
            ai_request: (request, respondWith) => respondWith.string(() => Promise.reject('See docs to implement AI Assistant')),
        });
    </script>
<script>
$(document).ready(function () {
    $('#adduser').on('submit', function (e) {
    e.preventDefault(); // prevent default form submission

    let isValid = true;
    let formData = {};

    // Loop through all input and select fields except checkboxes
    $(this).find('input:not([type="checkbox"]), select').each(function () {
        let value = $(this).val().trim();
        let name = $(this).attr('name');
        if (!value) {
            isValid = false;
            $(this).addClass('is-invalid');
        } else {
            $(this).removeClass('is-invalid');
            formData[name] = value;
        }
    });

    // Handle checkboxes separately
    formData['adminPrivileges'] = $('#admin_privileges').is(':checked');
    formData['disableFinances'] = $('#finance').is(':checked');

    if (!isValid) return;

    // Send AJAX request
    $.post('<?php echo base_url().'site/addUserData' ?>', formData, function (res) {
        console.log(res);
        let response = {};
        try {
            response = typeof res === 'object' ? res : JSON.parse(res);
        } catch (e) {
            Swal.fire('Error', 'Invalid server response.', 'error');
            return;
        }

        if (response.success) {
            Swal.fire({
                icon: 'success',
                title: 'Success!',
                text: response.message
            });

            // Reset form
            $('#adduser')[0].reset();
            $('#adduser .is-invalid').removeClass('is-invalid');

        } else {
            Swal.fire({
                icon: 'error',
                title: 'Error!',
                text: response.message
            });
        }
    });
});

    /*
    $('#adduser').on('submit', function (e) {
        e.preventDefault(); // prevent default form submission

        let isValid = true;
        let formData = {};

        // Loop through all input and select fields except checkboxes
        $(this).find('input:not([type="checkbox"]), select').each(function () {
            let value = $(this).val().trim();
            let name = $(this).attr('name');
            if (!value) {
                isValid = false;
                $(this).addClass('is-invalid'); // Bootstrap style (optional)
            } else {
                $(this).removeClass('is-invalid');
                formData[name] = value;
            }
        });

        // Handle checkboxes separately
        formData['admin_privileges'] = $('#admin_privileges').is(':checked');
        formData['finance'] = $('#finance').is(':checked');

        if (!isValid) {
          //  alert('Please fill all required fields.');
            return;
        }

        // ✅ Submit your data via AJAX or further logic here
        console.log('Form Data:', formData);
    //     const formElement = this;
    // const formData1 = new FormData(formElement); // Automatically grabs all input values

    // // Manually add checkbox values
    // formData1.append('admin_privileges', $('#admin_privileges').is(':checked') ? 'true' : 'false');
    // formData1.append('finance', $('#finance').is(':checked') ? 'true' : 'false');

        // Example:
        $.post('<?php echo base_url().'site/addUserData' ?>', formData, function(response) {
            console.log('Server response:', response);
        });
    });
    */
});
</script>
<?php if($this->uri->segment(2) == "editadmininfo"){ ?>
<script>
$(document).ready(function () {
    $('#editadmininfo').on('submit', function (e) {
        e.preventDefault(); // prevent default form submission  
       // alert("test");  
        // Get form values
        const name = $('#name').val();
        const id = $('#Userid').val();
        const password = $('#password').val();
        const companyName = $('#companeyName').val();
        const phone = $('#phone').val();
        if(password!=""){
            if (password.length < 6) {
            Swal.fire({
                icon: 'error',
                title: 'Validation Error',
                text: 'Password must be at least 6 characters long'
            });
            return false;
        }    
        }
        // Validation
        if (!name) {
            Swal.fire({
                icon: 'error',
                title: 'Validation Error',
                text: 'Please enter admin name'
            });
            return false;
        }

        if(!phone){
            Swal.fire({
                icon: 'error',
                title: 'Validation Error',
                text: 'Please enter Phone number'
            });
            return false;
        }
        if (!companyName) {
            Swal.fire({
                icon: 'error',
                title: 'Validation Error',
                text: 'Please enter company name'
            });
            return false;
        }

        // Prepare form data
        const formData = {
            name: name,
            phone: phone,
            password: password,
            companeyName: companyName,
            id: id
        };
        console.log("formData",formData);
       

        // Show loading state
        Swal.fire({
            title: 'Processing...',
            text: 'Please wait while we create the admin account',
            allowOutsideClick: false,
            showConfirmButton: false,
            willOpen: () => {
                Swal.showLoading();
            }
        });
        
        // Send AJAX request
        $.ajax({
            url: '<?php echo base_url().'site/updateadmininfo' ?>',
            type: 'POST',
            data: formData,
            success: function(response) {
                console.log(response);
                try {
                    const res = JSON.parse(response);
                    
                    if (res.success === true) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Success!',
                            text: 'Admin account created successfully',
                            confirmButtonText: 'OK'
                        }).then((result) => {
                            if (result.isConfirmed) {
                                // Reset form
                                $('#addadmininfo')[0].reset();
                                // Optionally redirect to admin list
                                // window.location.href = '<?php echo base_url('site/adminlist'); ?>';
                            }
                        });
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error!',
                            text: res.message || 'Failed to create admin account'
                        });
                    }
                } catch (error) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error!',
                        text: 'Something went wrong. Please try again.'
                    });
                }
            },
            error: function(xhr, status, error) {
                Swal.fire({
                    icon: 'error',
                    title: 'Error!',
                    text: 'Failed to communicate with server. Please try again.'
                });
            }
        });
    });
});
</script>
<?php } ?>

<?php if($this->uri->segment(2) == "addadmininfo"){ ?>
<script>
$(document).ready(function () {
    $('#addadmininfo').on('submit', function (e) {
        e.preventDefault(); // prevent default form submission  

        // Get form values
        const name = $('#name').val().trim();
        const email = $('#email').val().trim();
        const password = $('#password').val().trim();
        const companyName = $('#companeyName').val().trim();
        const phone = $('#phone').val().trim();
        
        // Validation
        if (!name) {
            Swal.fire({
                icon: 'error',
                title: 'Validation Error',
                text: 'Please enter admin name'
            });
            return false;
        }

        if (!email) {
            Swal.fire({
                icon: 'error',
                title: 'Validation Error',
                text: 'Please enter email address'
            });
            return false;
        }

        // Email format validation
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(email)) {
            Swal.fire({
                icon: 'error',
                title: 'Validation Error',
                text: 'Please enter a valid email address'
            });
            return false;
        }

        if (!password) {
            Swal.fire({
                icon: 'error',
                title: 'Validation Error',
                text: 'Please enter password'
            });
            return false;
        }

        // Password strength validation
        if (password.length < 6) {
            Swal.fire({
                icon: 'error',
                title: 'Validation Error',
                text: 'Password must be at least 6 characters long'
            });
            return false;
        }

        if (!companyName) {
            Swal.fire({
                icon: 'error',
                title: 'Validation Error',
                text: 'Please enter company name'
            });
            return false;
        }

        if(!phone){
            Swal.fire({
                icon: 'error',
                title: 'Validation Error',
                text: 'Please enter Phone number'
            });
            return false;
        }
        // Prepare form data
        const formData = {
            name: name,
            email: email,
            password: password,
            companeyName: companyName,
            phone: phone,
                };
        console.log("formData",formData);

        // Show loading state
        Swal.fire({
            title: 'Processing...',
            text: 'Please wait while we create the admin account',
            allowOutsideClick: false,
            showConfirmButton: false,
            willOpen: () => {
                Swal.showLoading();
            }
        });
        
        // Send AJAX request
        $.ajax({
            url: '<?php echo base_url().'site/addadmininfodata' ?>',
            type: 'POST',
            data: formData,
            success: function(response) {
                console.log(response);
                try {
                    const res = JSON.parse(response);
                    
                    if (res.success === true) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Success!',
                            text: 'Admin account created successfully',
                            confirmButtonText: 'OK'
                        }).then((result) => {
                            if (result.isConfirmed) {
                                // Reset form
                                $('#addadmininfo')[0].reset();
                                // Optionally redirect to admin list
                                // window.location.href = '<?php echo base_url('site/adminlist'); ?>';
                            }
                        });
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error!',
                            text: res.message || 'Failed to create admin account'
                        });
                    }
                } catch (error) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error!',
                        text: 'Something went wrong. Please try again.'
                    });
                }
            },
            error: function(xhr, status, error) {
                Swal.fire({
                    icon: 'error',
                    title: 'Error!',
                    text: 'Failed to communicate with server. Please try again.'
                });
            }
        });
    });
});
</script>
<?php } ?>

<?php if($this->uri->segment(2) == "addammenity"){ ?>
<script>
    //alert()
$(document).ready(function () {
    const fileInput = $('#imageUpload');
    const defaultImages = $('.default-image');
    const timeFields = $('#timeFields');

    // 🖼️ Default image selection
    defaultImages.on('change', function () {
        if ($(this).is(':checked')) {
            fileInput.val('').prop('disabled', true).prop('required', false);
        }
    });

    // 📁 File input change
    fileInput.on('change', function () {
        if (this.files.length > 0) {
            defaultImages.prop('checked', false);
            fileInput.prop('disabled', false).prop('required', true);
        }
    });

    // 💳 Payment toggle
    $('#paymentRequired').on('change', function () {
        if ($(this).is(':checked')) {
            $('#paymentFields').show();
            $('#price, #currency').prop('required', true);
        } else {
            $('#paymentFields').hide();
            $('#price, #currency').prop('required', false);
        }
    });

    // 👥 Capacity toggle
    $('#capacityLimit').on('change', function () {
        if ($(this).is(':checked')) {
            $('#capacityField').show();
            $('#maxPeople').prop('required', true);
        } else {
            $('#capacityField').hide();
            $('#maxPeople').prop('required', false);
        }
    });

    // 📝 Description counter
    $('#description').on('input', function () {
        $('#descCount').text(`${this.value.length}/2000`);
    });

    // 📆 Calendar type logic
    $('#calendarType').on('change', function () {
        const type = $(this).val();
        timeFields.html('');

        if (type === 'hourly' || type === 'once_day') {
            timeFields.html(`
                <label>Opening Time</label>
                <input type="time" id="openTime" name="openTime" class="form-control FormInput" required>
                <label class="mt-2">Closing Time</label>
                <input type="time" id="closeTime" name="closeTime" class="form-control FormInput mt-2" required>
            `);
        } else if (type === 'day_night') {
            timeFields.html(`
                <label>Day Opening Time</label>
                <input type="time" id="dayOpen" name="dayOpen" class="form-control FormInput" required>
                <label class="mt-2">Day Closing Time</label>
                <input type="time" id="dayClose" name="dayClose" class="form-control FormInput mt-2" required>
                <label class="mt-2">Night Opening Time</label>
                <input type="time" id="nightOpen" name="nightOpen" class="form-control FormInput mt-2" required>
                <label class="mt-2">Night Closing Time</label>
                <input type="time" id="nightClose" name="nightClose" class="form-control FormInput mt-2" required>
            `);
        } else if (type === 'custom_slots') {
            timeFields.html(`
                <div id="customSlots"></div>
                <button type="button" id="addSlot" class="btn btn-sm btn-secondary mt-2">+ Add Slot</button>
            `);
        }
    });

    // ➕ Add custom slot
    $(document).on('click', '#addSlot', function () {
        $('#customSlots').append(`
            <div class="row my-2">
                <div class="col-md-6">
                    <label>From</label>
                    <input type="time" name="fromTime[]" class="form-control FormInput" required>
                </div>
                <div class="col-md-6">
                    <label>To</label>
                    <input type="time" name="toTime[]" class="form-control FormInput" required>
                </div>
            </div>
        `);
    });

    // 🧠 Submit handler
    $('#reservationForm').on('submit', function (e) {
        e.preventDefault();

        // Required validations
        $('#price, #currency').prop('required', $('#paymentRequired').is(':checked'));
        $('#maxPeople').prop('required', $('#capacityLimit').is(':checked'));

        if (fileInput.val()) {
            defaultImages.prop('checked', false);
            fileInput.prop('required', true);
        } else if ($('.default-image:checked').length > 0) {
            fileInput.prop('required', false);
        } else {
            fileInput.prop('required', true);
        }

        // ✅ Native HTML5 validation
        if (this.checkValidity()) {
            this.submit(); // Or replace with AJAX
        } else {
            this.reportValidity();
        }
    });
});
</script>
<?php } ?>

<?php if($this->uri->segment(2) == "edit"){ ?>
<script>
                    $(document).ready(function () {
                        const fileInput = $('#imageUpload');
                        const defaultImages = $('.default-image');
                        const timeFields = $('#timeFields');
                        const form = $('#reservationForm');

                        // Initialize calendar type and time fields on page load
                        function initializeCalendarType() {
                           
                            const calendarType = $('#calendarType').val();
                           
                           

                            if (calendarType === 'hourly' || calendarType === 'once_day') {
                                const times = <?php echo json_encode($amenity['timeforapp'] ?? []); ?>;
                                const timeSlots = Object.keys(times);
                                console.log("timeSlots",timeSlots);
                                const [openTime, closeTime] = timeSlots[0]?.split('-') ?? ['', ''];
                                timeFields.html(`
                                    <label>Opening Time</label>
                                    <input type="time" id="openTime" name="openTime" class="form-control FormInput" 
                                        value="${convertTo24Hour(openTime)}" required>
                                    <label class="mt-2">Closing Time</label>
                                    <input type="time" id="closeTime" name="closeTime" class="form-control FormInput mt-2" 
                                        value="${convertTo24Hour(closeTime)}" required>
                                `);
                            } 
                            else if (calendarType === 'day_night') {
                                const times = <?php echo json_encode($amenity['timeforapp'] ?? []); ?>;
                                const timeSlots = Object.keys(times);
                                console.log("timeSlots",timeSlots);
                                const [dayOpen, dayClose] = timeSlots[0]?.split('-') ?? ['', ''];
                                const [nightOpen, nightClose] = timeSlots[1]?.split('-') ?? ['', ''];
                                
                                timeFields.html(`
                                    <label>Day Opening Time</label>
                                    <input type="time" id="dayOpen" name="dayOpen" class="form-control FormInput" 
                                        value="${convertTo24Hour(dayOpen)}" required>
                                    <label class="mt-2">Day Closing Time</label>
                                    <input type="time" id="dayClose" name="dayClose" class="form-control FormInput mt-2" 
                                        value="${convertTo24Hour(dayClose)}" required>
                                    <label class="mt-2">Night Opening Time</label>
                                    <input type="time" id="nightOpen" name="nightOpen" class="form-control FormInput mt-2" 
                                        value="${convertTo24Hour(nightOpen)}" required>
                                    <label class="mt-2">Night Closing Time</label>
                                    <input type="time" id="nightClose" name="nightClose" class="form-control FormInput mt-2" 
                                        value="${convertTo24Hour(nightClose)}" required>
                                `);
                            } 
                            else if (calendarType === 'custom_slots') {
                                timeFields.html(`
                                    <div id="customSlots"></div>
                                    <button type="button" id="addSlot" class="btn btn-sm btn-secondary mt-2">+ Add Slot</button>
                                `);
                                const times = <?php echo json_encode($amenity['timeforapp'] ?? []); ?>;
                                const timeSlots = Object.keys(times);
                                console.log("timeSlots",timeSlots);
                                
                                // Add existing custom slots
                                timeSlots.forEach(slot => {
                                    console.log("slot",slot);
                                    const [from, to] = slot.split('-');
                                    console.log("from",from);
                                    console.log("to",to);
                                    addCustomSlot(convertTo24Hour(from), convertTo24Hour(to));
                                });
                            }
                        }

                        function convertTo24Hour(time12h) {
    if (!time12h) return '';
    
    // Add minutes if not present
    if (!time12h.includes(':')) {
        time12h = time12h.replace(' ', ':00 ');
    }

    const [time, modifier] = time12h.split(' ');
    let [hours, minutes] = time.split(':');

    hours = parseInt(hours);
    
    if (modifier === 'PM' && hours < 12) {
        hours = hours + 12;
    }
    if (modifier === 'AM' && hours === 12) {
        hours = 0;
    }

    return `${hours.toString().padStart(2, '0')}:${minutes}`;
}


function convertTo12Hour(time24h) {
    if (!time24h) return '';
    
    let [hours, minutes] = time24h.split(':');
    hours = parseInt(hours);
    
    const modifier = hours >= 12 ? 'PM' : 'AM';
    hours = hours % 12 || 12;
    
    return `${hours}:${minutes} ${modifier}`;
}

// Function to add custom slot with proper time formatting
function addCustomSlot(fromTime = '', toTime = '') {
    const slotDiv = document.createElement('div');
    slotDiv.innerHTML = `
        <div class="mb-3">
            <label>From</label>
            <input type="time" name="fromTime[]" class="form-control FormInput" value="${fromTime}" required>
            <label>To</label>
            <input type="time" name="toTime[]" class="form-control FormInput mt-2" value="${toTime}" required>
            <button type="button" class="btn btn-sm btn-danger mt-2 remove-slot">Remove Slot</button>
        </div>
    `;
    document.getElementById('customSlots').appendChild(slotDiv);

    // Add remove button handler
    slotDiv.querySelector('.remove-slot').addEventListener('click', function() {
        slotDiv.remove();
    });
}

// Add click handler for add slot button
$(document).on('click', '#addSlot', function() {
    addCustomSlot();
});

                        // Call initialization on page load
                        initializeCalendarType();

                        // Calendar type change handler
                        $('#calendarType').on('change', function() {
                            const type = $(this).val();
                            timeFields.html('');

                            if (type === 'hourly' || type === 'once_day') {
                                timeFields.html(`
                                    <label>Opening Time</label>
                                    <input type="time" id="openTime" name="openTime" class="form-control FormInput" required>
                                    <label class="mt-2">Closing Time</label>
                                    <input type="time" id="closeTime" name="closeTime" class="form-control FormInput mt-2" required>
                                `);
                            } 
                            else if (type === 'day_night') {
                                timeFields.html(`
                                    <label>Day Opening Time</label>
                                    <input type="time" id="dayOpen" name="dayOpen" class="form-control FormInput" required>
                                    <label class="mt-2">Day Closing Time</label>
                                    <input type="time" id="dayClose" name="dayClose" class="form-control FormInput mt-2" required>
                                    <label class="mt-2">Night Opening Time</label>
                                    <input type="time" id="nightOpen" name="nightOpen" class="form-control FormInput mt-2" required>
                                    <label class="mt-2">Night Closing Time</label>
                                    <input type="time" id="nightClose" name="nightClose" class="form-control FormInput mt-2" required>
                                `);
                            } 
                            else if (type === 'custom_slots') {
                                timeFields.html(`
                                    <div id="customSlots"></div>
                                    <button type="button" id="addSlot" class="btn btn-sm btn-secondary mt-2">+ Add Slot</button>
                                `);
                            }
                        });

                        // Image validation and handling
                        defaultImages.on('change', function () {
                            if ($(this).is(':checked')) {
                                fileInput.val('').prop('disabled', true).prop('required', false);
                                $('#selectedImage').val($(this).val());
                            }
                        });

                        fileInput.on('change', function () {
                            if (this.files.length > 0) {
                                defaultImages.prop('checked', false);
                                fileInput.prop('disabled', false);
                                
                                // Validate file type
                                const file = this.files[0];
                                const validTypes = ['image/jpeg', 'image/png', 'image/gif'];
                                if (!validTypes.includes(file.type)) {
                                    Swal.fire({
                                        icon: 'error',
                                        title: 'Invalid File Type',
                                        text: 'Please select a valid image file (JPEG, PNG, or GIF)'
                                    });
                                    this.value = '';
                                    return;
                                }

                                // Validate file size (max 2MB)
                                if (file.size > 2 * 1024 * 1024) {
                                    Swal.fire({
                                        icon: 'error',
                                        title: 'File Too Large',
                                        text: 'Image size should not exceed 2MB'
                                    });
                                    this.value = '';
                                    return;
                                }
                            }
                        });

                        // Payment fields validation
                        $('#paymentRequired').on('change', function () {
                            const paymentFields = $('#paymentFields');
                            if ($(this).is(':checked')) {
                                paymentFields.show();
                                $('#price, #currency').prop('required', true);
                            } else {
                                paymentFields.hide();
                                $('#price, #currency').prop('required', false);
                            }
                        });

                        // Price validation
                        $('#price').on('input', function() {
                            this.value = this.value.replace(/[^0-9]/g, '');
                        });

                        // Capacity fields validation
                        $('#capacityLimit').on('change', function () {
                            const capacityField = $('#capacityField');
                            if ($(this).is(':checked')) {
                                capacityField.show();
                                $('#maxPeople').prop('required', true);
                            } else {
                                capacityField.hide();
                                $('#maxPeople').prop('required', false);
                            }
                        });

                        // Max people validation
                        $('#maxPeople').on('input', function() {
                            this.value = this.value.replace(/[^0-9]/g, '');
                            if (parseInt(this.value) > 1000) {
                                this.value = '1000';
                            }
                        });

                        // Description validation
                        $('#description').on('input', function () {
                            const maxLength = 2000;
                            if (this.value.length > maxLength) {
                                this.value = this.value.substring(0, maxLength);
                            }
                            $('#descCount').text(`${this.value.length}/${maxLength}`);
                        });

                        // Date validation
                        function validateDates() {
                            const startDate = new Date($('#startDate').val());
                            const endDate = new Date($('#endDate').val());
                            const today = new Date();
                            today.setHours(0, 0, 0, 0);

                            if (startDate < today) {
                                Swal.fire({
                                    icon: 'error',
                                    title: 'Invalid Start Date',
                                    text: 'Start date cannot be in the past'
                                });
                                return false;
                            }

                            if (endDate <= startDate) {
                                Swal.fire({
                                    icon: 'error',
                                    title: 'Invalid Date Range',
                                    text: 'End date must be after start date'
                                });
                                return false;
                            }

                            return true;
                        }

                        // Time validation
                        function validateTimes() {
                            const calendarType = $('#calendarType').val();
                            
                            if (calendarType === 'hourly' || calendarType === 'once_day') {
                                const openTime = $('#openTime').val();
                                const closeTime = $('#closeTime').val();
                                
                                if (!openTime || !closeTime || openTime >= closeTime) {
                                    Swal.fire({
                                        icon: 'error',
                                        title: 'Invalid Time Range',
                                        text: 'Closing time must be after opening time'
                                    });
                                    return false;
                                }
                            } 
                            else if (calendarType === 'day_night') {
                                const dayOpen = $('#dayOpen').val();
                                const dayClose = $('#dayClose').val();
                                const nightOpen = $('#nightOpen').val();
                                const nightClose = $('#nightClose').val();
                                
                                if (!dayOpen || !dayClose || dayOpen >= dayClose) {
                                    Swal.fire({
                                        icon: 'error',
                                        title: 'Invalid Day Time Range',
                                        text: 'Day closing time must be after opening time'
                                    });
                                    return false;
                                }
                                
                                if (!nightOpen || !nightClose || nightOpen >= nightClose) {
                                    Swal.fire({
                                        icon: 'error',
                                        title: 'Invalid Night Time Range',
                                        text: 'Night closing time must be after opening time'
                                    });
                                    return false;
                                }
                            }
                            else if (calendarType === 'custom_slots') {
                                const fromTimes = $('input[name="fromTime[]"]');
                                const toTimes = $('input[name="toTime[]"]');
                                
                                if (fromTimes.length === 0) {
                                    Swal.fire({
                                        icon: 'error',
                                        title: 'No Time Slots',
                                        text: 'Please add at least one time slot'
                                    });
                                    return false;
                                }
                                
                                for (let i = 0; i < fromTimes.length; i++) {
                                    if (!fromTimes[i].value || !toTimes[i].value || fromTimes[i].value >= toTimes[i].value) {
                                        Swal.fire({
                                            icon: 'error',
                                            title: 'Invalid Time Slot',
                                            text: 'End time must be after start time for all slots'
                                        });
                                        return false;
                                    }
                                }
                            }
                            
                            return true;
                        }

                        // Form submission
                        form.on('submit', function (e) {
                            e.preventDefault();

                            // Basic form validation
                            if (!this.checkValidity()) {
                                e.stopPropagation();
                                this.reportValidity();
                                return;
                            }

                            // Custom validations
                            if (!validateDates()) return;
                            if (!validateTimes()) return;

                            // Validate name
                            const name = $('#name').val().trim();
                            if (name.length < 3) {
                                Swal.fire({
                                    icon: 'error',
                                    title: 'Invalid Name',
                                    text: 'Name must be at least 3 characters long'
                                });
                                return;
                            }

                            // Validate description
                            const description = $('#description').val().trim();
                            if (description.length < 10) {
                                Swal.fire({
                                    icon: 'error',
                                    title: 'Invalid Description',
                                    text: 'Description must be at least 10 characters long'
                                });
                                return;
                            }

                            // Validate payment if required
                            if ($('#paymentRequired').is(':checked')) {
                                const price = parseInt($('#price').val());
                                if (!price || price <= 0) {
                                    Swal.fire({
                                        icon: 'error',
                                        title: 'Invalid Price',
                                        text: 'Please enter a valid price'
                                    });
                                    return;
                                }
                            }

                            // Validate capacity if enabled
                            if ($('#capacityLimit').is(':checked')) {
                                const maxPeople = parseInt($('#maxPeople').val());
                                if (!maxPeople || maxPeople <= 0) {
                                    Swal.fire({
                                        icon: 'error',
                                        title: 'Invalid Capacity',
                                        text: 'Please enter a valid capacity limit'
                                    });
                                    return;
                                }
                            }

                            // If all validations pass, show confirmation
                            Swal.fire({
                                title: 'Update Amenity?',
                                text: 'Are you sure you want to update this amenity?',
                                icon: 'question',
                                showCancelButton: true,
                                confirmButtonText: 'Yes, Update',
                                cancelButtonText: 'Cancel'
                            }).then((result) => {
                                if (result.isConfirmed) {
                                    // Submit the form
                                    this.submit();
                                }
                            });
                        });
                    });
                </script>
<?php } ?>

<?php if($this->uri->segment(2) == 'case') { ?>
<script>

let lastTimestamp = 0;

// Function to format date
function formatDate(timestamp) {
  const date = new Date(timestamp);
  return date.toLocaleString('en-US', {
    day: '2-digit',
    month: 'long',
    year: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
    hour12: true
  });
}

// Function to add a reply to the UI
function addReplyToUI(reply) {
var selectedusername = document.getElementById('chatusername').value;
var fromname = "";
var toname = "";
if("admin"== reply.fromId){
     fromname = "admin";
     toname = selectedusername;
}else{
    fromname = selectedusername;
    toname ="admin" ;
}

  const repliesContainer = document.getElementById('replies-container');
  
  const replyHtml = `
    <div class="card-body">
      <p class="ft1 text-black">${reply.subject || 'Reply'}</p>
      <p class="fc1 mb-0"><span class="fc2">${formatDate(reply.createdAt)}</span></p>
      <div class="my-2">
        <p class="fc1 mb-0"><span class="fc2">From:</span> ${fromname}</p>
        <p class="fc2">To: <span class="fc1">${toname}</span></p>
        <div class="my-2">
          <p class="fc2">${reply.note}</p>
        </div>
      </div>
      ${reply.fileUrl ? `
        <div class="mt-3">
          <a href="${reply.attachmentUrl}" target="_blank" class="text-decoration-none">
            <div class="d-flex align-items-center gap-2">
              <img src="<?php echo base_url(); ?>assets/images/atachP2.png" alt="File" width="24">
              <span class="text-primary">View Attachment</span>
            </div>
          </a>
        </div>
      ` : ''}
    </div>
    <hr>
  `;
  
  repliesContainer.insertAdjacentHTML('beforeend', replyHtml);
  repliesContainer.scrollTop = repliesContainer.scrollHeight;
  
  if (reply.createdAt > lastTimestamp) {
    lastTimestamp = reply.createdAt;
  }
}

// Function to fetch new replies
function fetchNewReplies() {
  $.ajax({
    url: '<?php echo base_url(); ?>site/fetchReplies',
    method: 'POST',
    data: {
      issueId: '<?php echo $id; ?>',
      lastTimestamp: lastTimestamp
    },
    success: function(response) {
        console.log(response);
      const data = JSON.parse(response);
      if (data.success && data.replies) {
        data.replies.forEach(reply => addReplyToUI(reply));
      }
    },
    complete: function() {
      // Poll again after 3 seconds
   //   setTimeout(fetchNewReplies, 3000);
    }
  });
}

// Handle file selection
document.getElementById('replyFile').addEventListener('change', function(e) {
  const fileName = e.target.files[0]?.name || '';
  document.getElementById('selectedFileName').textContent = fileName ? `Selected: ${fileName}` : '';
});

// Handle form submission
$('#replyForm').on('submit', function(e) {
  e.preventDefault();
  
  const formData = new FormData(this);
  formData.append('issueId', '<?php echo $id; ?>');
  formData.append('userId', '<?php echo $userId; ?>');
  
  // Get the reply text and file
 // const replyText = $('#replyText').val();
  const replyFile = $('#replyFile')[0].files[0];
  const replyText = tinymce.get('replyText').getContent().trim();
  alert(replyText);
if (!replyText) {
  alert('Please enter a reply message');
  return;
}

  // Validate reply text
  if (!replyText.trim()) {
    alert('Please enter a reply message');
    return;
  }
  
  // Add reply text and file to formData
  formData.append('replyText', replyText);
  if (replyFile) {
    formData.append('replyFile', replyFile);
  }
  
  $.ajax({
    url: '<?php echo base_url(); ?>site/sendReply',
    method: 'POST',
    data: formData,
    processData: false,
    contentType: false,
    success: function(response) {
      const data = JSON.parse(response);
      if (data.success) {
        // Clear form
        $('#replyForm')[0].reset();
        $('#selectedFileName').text('');
        
        // Add the new reply to the UI
        addReplyToUI(data.reply);
        
        // Show success message
        Swal.fire({
          icon: 'success',
          title: 'Success',
          text: 'Reply sent successfully'
        });
      } else {
        Swal.fire({
          icon: 'error',
          title: 'Error',
          text: data.error || 'Failed to send reply. Please try again.'
        });
      }
    },
    error: function() {
      Swal.fire({
        icon: 'error',
        title: 'Error',
        text: 'Failed to send reply. Please try again.'
      });
    }
  });
});

// Start fetching replies
fetchNewReplies();
</script>

<?php } ?>

<?php if($this->uri->segment(2) == 'addwarning') { ?>
<script>
$(document).ready(function() {
    // Character counter for comment
    $('#comment').on('input', function() {
        const maxLength = 10000;
        const currentLength = $(this).val().length;
        $('#noteCount').text(`${currentLength}/${maxLength}`);
        
        if (currentLength > maxLength) {
            $(this).val($(this).val().substring(0, maxLength));
        }
    });

    // File input change handler to show selected filename
    $('#file').on('change', function(e) {
        const file = this.files[0];
        if (file) {
            console.log('Selected File:', {
                name: file.name,
                type: file.type,
                size: file.size + ' bytes'
            });
        }
    });

    // Form data collection
    $('#addwarningform').on('submit', function(e) {
        e.preventDefault();
        const formData = new FormData(this);

  formData.append('warning_type', $('select[name="warning_type"]').val());
  formData.append('date', $('#date').val());
  formData.append('comment', tinymce.get('comment').getContent().trim());
  formData.append('file', $('#file')[0].files[0] ? $('#file')[0].files[0].name : '');
  formData.append('units', $('select[name="units"]').val());
  $.ajax({
    url: '<?php echo base_url(); ?>site/addwarningdata',
    method: 'POST',
    data: formData,
    processData: false,
    contentType: false,
    success: function(response) {
        const data = JSON.parse(response);
        if (data.success) {
            $('#addwarningform')[0].reset();
            tinymce.get('comment').setContent('');
            Swal.fire({
                icon: 'success',
                title: 'Success',
                text: 'Warning added successfully'      
            });
        } else {
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: data.message || 'Failed to add warning. Please try again.'
            });
        }
        console.log(response);
    },
    error: function() {
        console.log('Error');
    }
});
 
       
    });
});
</script>
<?php } ?>

<?php if($this->uri->segment(2) == 'addreservations') { ?>
<script>
$(document).ready(function() {
    // Handle date selection
    $(".selectAmenity").on('change', function() {
        const price = $(this).find(':selected').data('id'); // ✅ get data-id from selected option
    $("#price").val(price); // Set to an input field with id="price"
    $('#available_slot').html('<option value="">Select Time Slot</option>');
    console.log("m1",price)
    })
    $('#reservation_date').on('change', function() {
        const selectedDate = $(this).val();
        const amenityId = $('select[name="amenity"]').val();
        
        if (!selectedDate || !amenityId) {
            return;
        }

        // Show loading state
        $('#available_slots').html('<option value="">Loading slots...</option>');

        // Fetch available slots
        $.ajax({
            url: '<?php echo base_url(); ?>site/getAvailableSlots',
            method: 'POST',
            data: {
                date: selectedDate,
                amenityId: amenityId
            },
            success: function(response) {
                console.log(response);
                
                try {
                    const data = JSON.parse(response);
                    console.log("m1",data)
                    let options = '<option value="">Select Time Slot</option>';
                    
                    if (data.success && data.slots) {
                        // Add each available slot to options
                        data.slots.forEach(slot => {
                            options += `<option value="${slot.time}">${slot.time}</option>`;
                        });
                    } else {
                        options = '<option value="">No slots available</option>';
                    }
                    console.log("m2",options)
                    // Update the slots dropdown
                    $('#available_slots').html(options);
                    
                } catch (e) {
                    console.error('Error parsing response:', e);
                    $('#available_slots').html('<option value="">Error loading slots</option>');
                }
                    

            },
            error: function() {
                console.error('Failed to fetch slots');
                $('#available_slot').html('<option value="">Error loading slots</option>');
            }
        });
    });
$('#reservationForm').on('submit', function(e) {
    e.preventDefault();
    const formData = new FormData(this);
    formData.append('date', $('#reservation_date').val());
 // formData.append('comment', tinymce.get('note').getContent().trim());
  formData.append('units', $('select[name="unitId"]').val());
  formData.append('price', $('#price').val());
  formData.append('slot', $('#available_slots').val());
  formData.append('amenity', $('#amenity').val());
  formData.append('number_of_people', $('#number_of_people').val());

     console.log(formData);
    $.ajax({
        url: '<?php echo base_url(); ?>site/addreservationsdata',
        method: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        success: function(response) {
            console.log(response);
            const data = JSON.parse(response);
        if (data.success) {

            Swal.fire({
                icon: 'success',
                title: 'Success',
                text: 'Reservation added successfully'      
            });
            location.reload();
        } else {
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: data.message || 'Failed to add warning. Please try again.'
            });
        }
        location.reload();
         
        },
        error: function() {
            console.log('Error');
        }
    });
});


});
</script>
<?php } ?>
<?php if($this->uri->segment(2) == 'warnings' || $this->uri->segment(2) == 'viewwarning') { ?>
    <script>
$(document).ready(function() {
    let currentWarningId = '';

    // Store warning ID when solve button is clicked
    $('.solve-warning').on('click', function() {
        currentWarningId = $(this).data('warning-id');
    });

    // Handle confirm button click
    $('#confirmSolve').on('click', function() {
        if (currentWarningId) {
            window.location.href = '<?php echo base_url(); ?>site/solvewarning/' + currentWarningId;
        }
    });
});
</script>

<?php } ?>
<?php if($this->uri->segment(2) == 'addtemplte') { ?>
    <script>
$(document).ready(function() {
    

    // Form validation
    $('#templateForm').on('submit', function(e) {
        if (!tinymce.get('templateContent').getContent()) {
            e.preventDefault();
            alert('Please enter template content');
            return false;
        }
    });
});
</script> 
    <?php } ?>
    <?php if($this->uri->segment(2) == 'usetemplate1') { ?>
<script>
 
$(document).ready(function() {
    // Initialize TinyMCE if we're on the template page
   
    // Handle file uploads
    $('#attachments').on('change', function() {
        const fileList = $('#fileList');
        fileList.empty();
        
        Array.from(this.files).forEach(file => {
            const fileSize = (file.size / 1024 / 1024).toFixed(2);
            const fileItem = $(`
                <div class="alert alert-info d-flex justify-content-between align-items-center">
                    <span>${file.name} (${fileSize} MB)</span>
                    <button type="button" class="btn-close remove-file" data-filename="${file.name}"></button>
                </div>
            `);
            fileList.append(fileItem);
        });
    });

    // Remove individual files
    $(document).on('click', '.remove-file', function() {
        const filename = $(this).data('filename');
        const dt = new DataTransfer();
        const input = document.getElementById('attachments');
        const { files } = input;
        
        for (let i = 0; i < files.length; i++) {
            if (files[i].name !== filename) {
                dt.items.add(files[i]);
            }
        }
        
        input.files = dt.files;
        $(this).parent().remove();
    });

    // Handle recipients selection
    let selectedRecipients = new Set();
    
    $('.predefined-item').click(function() {
        const type = $(this).data('type');
        const value = $(this).data('value');
        const text = $(this).text();
        const recipientId = `${type}-${value}`;

        if (!selectedRecipients.has(recipientId)) {
            selectedRecipients.add(recipientId);
            const recipientTag = $(`
                <div class="recbox2 my-2 d-flex justify-content-between align-items-center" data-id="${recipientId}">
                    <span>${text}</span>
                    <button type="button" class="btn-close ms-2 remove-recipient" data-id="${recipientId}"></button>
                </div>
            `);
            $('#selectedRecipientsBox').append(recipientTag);
            updateSelectedRecipientsInput();
        }
    });

    // Remove individual recipient
    $(document).on('click', '.remove-recipient', function() {
        const recipientId = $(this).data('id');
        selectedRecipients.delete(recipientId);
        $(this).parent().remove();
        updateSelectedRecipientsInput();
    });

    // Clear all recipients
    $('#clearRecipients').click(function() {
        selectedRecipients.clear();
        $('#selectedRecipientsBox').empty();
        updateSelectedRecipientsInput();
    });

    function updateSelectedRecipientsInput() {
        $('#selectedRecipients').val(Array.from(selectedRecipients).join(','));
    }

    // Handle send time selection
    $('input[name="send_time"]').change(function() {
        if ($(this).val() === 'specificDate') {
            $('#dateTimePicker').show();
            $('#imed').hide();
            $('#scheduledTime').prop('required', true);
        } else {
            $('#dateTimePicker').hide();
            $('#imed').show();
            $('#scheduledTime').prop('required', false);
        }
    });

    

    // Handle drag and drop file uploads
    const dropZone = $('.brower2');
    
    dropZone.on('dragover', function(e) {
        e.preventDefault();
        $(this).addClass('drag-over');
    });

    dropZone.on('dragleave', function(e) {
        e.preventDefault();
        $(this).removeClass('drag-over');
    });

    dropZone.on('drop', function(e) {
        e.preventDefault();
        $(this).removeClass('drag-over');
        
        const files = e.originalEvent.dataTransfer.files;
        const input = document.getElementById('attachments');
        input.files = files;
        $(input).trigger('change');
    });
});
</script>

<script>
$(document).ready(function() {
    // Handle draft save
    $('#saveDraft').on('click', function() {
       
        const form = $('#messageForm');
        const formAction = '<?php echo base_url('site/draft'); ?>';
        submitForm(form, formAction, 'draft');
    });

    // Handle send now
    $('#sendNow').on('click', function() {
        alert();
        const form = $('#messageForm');
        const formAction = '<?php echo base_url('site/sendmessage'); ?>';
        submitForm(form, formAction, 'send');
    });

    function submitForm(form, action, type) {
        // Validate recipients
        if (selectedRecipients.size === 0) {
            alert('Please select at least one recipient');
            return false;
        }

        // Validate content
        if (!tinymce.get('editor').getContent()) {
            alert('Please enter message content');
            return false;
        }

        // Validate scheduled time if needed
        const sendTime = $('input[name="send_time"]:checked').val();
        if (sendTime === 'specificDate') {
            const scheduledTime = $('#scheduledTime').val();
            if (!scheduledTime) {
                alert('Please select a date and time for scheduled delivery');
                return false;
            }
        }

        // Update form action
        form.attr('action', action);
        
        // Add message type
        if($('#messageType').length === 0) {
            form.append('<input type="hidden" id="messageType" name="message_type" value="' + type + '">');
        } else {
            $('#messageType').val(type);
        }

        // Submit the form
        form.submit();
    }
});
</script>



<?php } ?>
<?php if($this->uri->segment(2) == 'usetemplate' || $this->uri->segment(2) == 'newmessage') { ?>
<script>
    $(document).ready(function() {
        // Initialize selected recipients set
        let selectedRecipients = new Set();
        
        // Handle recipient selection
        $('.predefined-item').on('click', function() {
            const type = $(this).data('type');
            const value = $(this).data('value');
            const text = $(this).text();
            const recipientId = `${type}-${value}`;
            
            if (!selectedRecipients.has(recipientId)) {
                selectedRecipients.add(recipientId);
                const recipientElement = $(`<div class="selected-recipient badge bg-primary me-2 mb-2" data-id="${recipientId}">${text} <i class="fa fa-times"></i></div>`);
                $('#selectedRecipientsBox').append(recipientElement);
                updateSelectedRecipientsInput();
            }
        });
        
        // Handle recipient removal
        $('#selectedRecipientsBox').on('click', '.selected-recipient', function() {
            const recipientId = $(this).data('id');
            selectedRecipients.delete(recipientId);
            $(this).remove();
            updateSelectedRecipientsInput();
        });
        
        // Clear all recipients
        $('#clearRecipients').on('click', function() {
            selectedRecipients.clear();
            $('#selectedRecipientsBox').empty();
            updateSelectedRecipientsInput();
        });
        
        // Update hidden input with selected recipients
        function updateSelectedRecipientsInput() {
            $('#selectedRecipients').val(Array.from(selectedRecipients).join(','));
        }
        
        // Toggle date/time picker based on send time selection
        $('input[name="send_time"]').on('change', function() {
            if ($(this).val() === 'specificDate') {
                $('#dateTimePicker').show();
                $('#imed').hide();
            } else {
                $('#dateTimePicker').hide();
                $('#imed').show();
            }
        });
        
        // Handle draft save
        $('#saveDraft').on('click', function() {
            const form = $('#messageForm');
            const formAction = '<?php echo base_url('site/savedraft'); ?>';
            submitForm(form, formAction, 'draft');
        });
        
        // Handle send now
        $('#sendNow').on('click', function() {
            const form = $('#messageForm');
            const formAction = '<?php echo base_url('site/sendmessage'); ?>';
            submitForm(form, formAction, 'send');
        });
        
        function submitForm(form, action, type) {
            // Validate recipients
            if (selectedRecipients.size === 0) {
                alert('Please select at least one recipient');
                return false;
            }
            
            // Validate content
            if (!tinymce.get('editor').getContent()) {
                alert('Please enter message content');
                return false;
            }
            
            // Validate subject
            if (!$('#subject').val().trim()) {
                alert('Please enter a message title');
                return false;
            }
            
            // Validate scheduled time if needed
            const sendTime = $('input[name="send_time"]:checked').val();
            if (sendTime === 'specificDate') {
                const scheduledTime = $('#scheduledTime').val();
                if (!scheduledTime) {
                    alert('Please select a date and time for scheduled delivery');
                    return false;
                }
            }
            
            // Update form action
            form.attr('action', action);
            
            // Add message type
            if($('#messageType').length === 0) {
                form.append('<input type="hidden" id="messageType" name="message_type" value="' + type + '">');
            } else {
                $('#messageType').val(type);
            }
            
            // Submit the form
            form.submit();
        }
        
        // Initialize TinyMCE if not already initialized
       
    });
    </script>


<?php } ?>




<!-- jQuery (required for DataTables) -->


<!-- DataTables JS -->
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>

<link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.4.1/css/buttons.dataTables.min.css">
<script src="https://cdn.datatables.net/buttons/2.4.1/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.print.min.js"></script>

<?php if($this->uri->segment(2) !== 'dashboard' && $this->uri->segment(2) !== 'messagecenter') { ?>
<script>
  $(document).ready(function () {
    const table = $('table').DataTable({
      dom: 'Brtip',
      buttons: [
        {
          extend: 'csvHtml5',
          text: 'Export CSV',
          className: 'btn btn-primary d-none',
          title: 'Exported List'
        }
      ],
      pageLength: 5,
      lengthChange: false,
      language: {
        paginate: {
          previous: "<img src='<?php echo base_url(); ?>/assets/images/cl.png'>",
          next: "<img src='<?php echo base_url(); ?>/assets/images/cr.png'>"
        }
      }
    });

    $('.form-Search').on('input', function () {
      table.search(this.value).draw();
    });

    $('.expButn').on('click', function () {
      $('.buttons-csv').click();
    });
  });
</script>
<?php } ?>



</body>


<!-- Mirrored from codervent.com/matoxi/demo/vertical-menu/index2.html by HTTrack Website Copier/3.x [XR&CO'2014], Tue, 09 Jan 2024 16:36:47 GMT -->

</html>