<?php
header('Content-type: application/x-javascript');
require_once __DIR__ . '/../global.php';

if (1 === 2) {
    //Just for suggestion help <script> if not then page behave like txt page+

?>
    <script>
        <?php } ?>

        <?php
        $defaultCountry = 'pk';
        $countryCode = $_SESSION['country_code'] ?? null;

        if (!$countryCode) {
            $ip = $_SERVER['REMOTE_ADDR'];
            $countryCode = $defaultCountry;

            $geo = @file_get_contents("https://ipapi.co/{$ip}/json/");

            if ($geo !== false) {
                $data = json_decode($geo, true);
                if (!empty($data['country'])) {
                    $countryCode = strtolower($data['country']);
                }
            }

            $_SESSION['country_code'] = $countryCode;
        }
        ?>

        var userCountryCode = "<?php echo $countryCode; ?>";
        var iti;

        function initIntlTelInput(input) {
            if (input.dataset.intlInitialized === "true") return;
            iti = window.intlTelInput(input, {
                separateDialCode: true,
                initialCountry: userCountryCode,
            });
            input.dataset.intlInitialized = "true";

            input.addEventListener("countrychange", function() {
                const selectedCountry = iti.getSelectedCountryData();
                console.log("Changed to:", selectedCountry.iso2, selectedCountry.dialCode);
            });
        }

        function showAlert(message) {
            let alertBox = $("#alertMessage");
            $("#alertText").text(message);

            alertBox.addClass("show").css("display", "block");

            setTimeout(function() {
                alertBox.removeClass("show");
                setTimeout(() => alertBox.css("display", "none"), 500);
            }, 3000);
        }

        tinymce.init({
            selector: 'textarea#tinymice-editor',
            menubar: true,
            plugins: [
                'advlist', 'autolink',
                'lists', 'link', 'image', 'charmap', 'preview', 'code', 'anchor', 'searchreplace', 'visualblocks',
                'fullscreen', 'insertdatetime', 'directionality', 'fullscreen', 'table', 'wordcount'
            ],
            toolbar: 'undo redo | code fullscreen| formatpainter casechange blocks fontsize | bold italic forecolor backcolor | ' +
                'alignleft aligncenter alignright alignjustify | ' +
                'bullist numlist checklist outdent indent | removeformat | ltr rtl |a11ycheck table help',
            font_size_formats: '8pt 10pt 12pt 14pt 16pt 18pt 24pt 36pt 48pt',
            image_uploadtab: false,
            media_poster: false,
            media_alt_source: false,
        });

        function addEmailField() {
            const container = document.getElementById('extraEmails');
            const input = document.createElement('input');
            input.type = 'email';
            input.name = 'extra_emails[]';
            input.className = 'form-control';
            container.appendChild(input);
        }

        function addPhoneField() {
            const container = document.getElementById('extraPhones');
            const input = document.createElement('input');
            input.type = 'tel';
            input.name = 'extra_phones[]';
            input.className = 'form-control';
            container.appendChild(input);
        }

        $("#userAddForm").submit(function(e) {
            e.preventDefault();
            const form = document.getElementById('userAddForm');
            const formData = new FormData(form);

            formData.set('phone', iti.getNumber(intlTelInputUtils.numberFormat.E164));

            const extraPhones = document.querySelectorAll('input[name="extra_phones[]"]');
            formData.delete('extra_phones[]');

            extraPhones.forEach(function(input) {
                const instance = window.intlTelInputGlobals.getInstance(input);
                const formatted = instance.getNumber(intlTelInputUtils.numberFormat.E164);
                if (formatted) {
                    formData.append('extra_phones[]', formatted);
                }
            });

            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=addNewUser',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                dataType: "json",
                beforeSend: function() {
                    $("#spinner-overlay").fadeIn('slow');
                },
                success: function(response) {
                    showAlert(response.message);
                    if (response.status === "success") {
                        setTimeout(() => {
                            loadPage(response.redirect, 'View/Edit User');
                        }, 1000);
                    }
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseJSON);
                },
                complete: function() {
                    $("#spinner-overlay").fadeOut('slow');
                }
            });
        });

        $("#userEditForm").submit(function(e) {
            e.preventDefault();
            const form = document.getElementById('userEditForm');
            const formData = new FormData(form);

            formData.set('phone', iti.getNumber(intlTelInputUtils.numberFormat.E164));

            const extraPhones = document.querySelectorAll('input[name="extra_phones[]"]');
            formData.delete('extra_phones[]');

            extraPhones.forEach(function(input) {
                const instance = window.intlTelInputGlobals.getInstance(input);
                const formatted = instance.getNumber(intlTelInputUtils.numberFormat.E164);
                if (formatted) {
                    formData.append('extra_phones[]', formatted);
                }
            });

            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=editUser',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                dataType: "json",
                beforeSend: function() {
                    $("#spinner-overlay").fadeIn('slow');
                },
                success: function(response) {
                    showAlert(response.message);
                    if (response.status === "success") {
                        setTimeout(() => {
                            loadPage(response.redirect, 'ICRM');
                        }, 1000);
                    }
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseJSON);
                },
                complete: function() {
                    $("#spinner-overlay").fadeOut('slow');
                }
            });
        });

        $('#userReportForm').submit(function(e) {
            e.preventDefault();

            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=getUserReport',
                method: 'POST',
                data: $(this).serialize(),
                beforeSend: function() {
                    $("#spinner-overlay").fadeIn('slow');
                },
                success: function(response) {
                    $('#userReportResults').html(response);
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseText);
                },
                complete: function() {
                    $("#spinner-overlay").fadeOut('slow');
                }
            });
        });

        $("#staffAddForm").submit(function(e) {
            e.preventDefault();
            var formData = new FormData(this);
            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=addNewStaff',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                dataType: "json",
                beforeSend: function() {
                    $("#spinner-overlay").fadeIn('slow');
                },
                success: function(response) {
                    showAlert(response.message);
                    if (response.status === "success") {
                        $("#staffAddForm").trigger("reset");
                        $("#staffAddForm select[multiple]").val(null).trigger("change");
                    }
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseJSON);
                },
                complete: function() {
                    $("#spinner-overlay").fadeOut('slow');
                }
            });
        });

        $("#staffEditForm").submit(function(e) {
            e.preventDefault();
            var formData = new FormData(this);
            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=editStaff',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                dataType: "json",
                beforeSend: function() {
                    $("#spinner-overlay").fadeIn('slow');
                },
                success: function(response) {
                    showAlert(response.message);
                    if (response.status === "success") {
                        setTimeout(() => {
                            loadPage(response.redirect, 'View/Edit Staff');
                        }, 1000);
                    }
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseJSON);
                },
                complete: function() {
                    $("#spinner-overlay").fadeOut('slow');
                }
            });
        });

        function deleteStaff(ths) {
            var deleteStaffId = $(ths).attr('data-id');
            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=deleteStaff',
                type: 'POST',
                data: {
                    deleteStaffId: deleteStaffId
                },
                beforeSend: function() {
                    $("#spinner-overlay").fadeIn('slow');
                },
                success: function(response) {
                    if (response == '1') {
                        $(ths).closest('tr').hide(1000, function() {
                            $(this).remove();
                        });
                    } else if (response == '0') {
                        showAlert("Delete fail please try again.");
                    } else {
                        window.location.reload();
                    }
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseJSON);
                },
                complete: function() {
                    $("#spinner-overlay").fadeOut('slow');
                }
            });
        }

        $(".getStaffSalary").change(function() {
            var userId = $(this).val();
            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=getStaffSalary',
                type: 'POST',
                data: {
                    userId: userId
                },
                success: function(response) {
                    $("input#salary").val(response);
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseText);
                }
            });
        });

        var clickedButton = '';

        $("#staffSalaryForm button[type=submit]").click(function() {
            clickedButton = $(this).val();
        });

        $("#staffSalaryForm").submit(function(e) {
            e.preventDefault();

            const form = $(this).serializeArray();
            const params = new URLSearchParams();

            form.forEach(field => {
                params.append(field.name, field.value);
            });

            if (clickedButton) {
                params.append('action', clickedButton);
            }

            window.open('salaryslip?' + params.toString(), '_blank');
        });

        function formatDate(dateStr) {
            const date = new Date(dateStr);
            const day = date.getDate();
            const month = date.toLocaleString('default', {
                month: 'long'
            });
            const year = date.getFullYear();
            return `${day}-${month}-${year}`;
        }

        $("#staffReportForm").submit(function(e) {
            e.preventDefault();
            var formData = new FormData(this);
            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=getStaffReport',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                dataType: "json",
                beforeSend: function() {
                    $("#spinner-overlay").fadeIn('slow');
                },
                success: function(response) {
                    const fromDate = $("#fromdate").val();
                    const toDate = $("#todate").val();

                    const formattedFrom = formatDate(fromDate);
                    const formattedTo = formatDate(toDate);
                    if (response.allStaffReports) {
                        $(".AllStaffDataDiv").fadeIn('slow');
                        $(".DataDiv").hide();

                        response.allStaffReports.forEach(reportData => {
                            const summary = reportData.summary;
                            const report = reportData.report;

                            const reportCard = `
                                <div class="card mb-4">
                                    <div class="card-body">
                                        <h5>${summary.name}</h5>
                                        <div class="row my-3">
                                            <div class="col-3"><strong>Absents: </strong> ${summary.absents}</div>
                                            <div class="col-3"><strong>Lates: </strong> ${summary.lates}</div>
                                            <div class="col-3"><strong>Presents: </strong> ${summary.presents}</div>
                                            <div class="col-3"><strong>Missing Out Times: </strong> ${summary.missingOutTime}</div>
                                            <div class="col-3"><strong>Working Hours: </strong> ${summary.workHours}</div>
                                            <div class="col-3"><strong>Total Working Hours: </strong> ${summary.totalWorkingHours}</div>
                                            <div class="col-3"><strong>Total Working Days: </strong> ${summary.totalWorkingDays}</div>
                                        </div>
                                        <table class="table table-bordered">
                                            <thead>
                                                <tr>
                                                    <th>Date</th>
                                                    <th>In Time</th>
                                                    <th>Out Time</th>
                                                    <th>State</th>
                                                    <th>Msg</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                ${report.map(row => `
                                                    <tr>
                                                        <td>${row.date} (${row.day})</td>
                                                        <td>${row.inTime || '-'}</td>
                                                        <td>${row.outTime || '-'}</td>
                                                        <td>${row.status}</td>
                                                        <td>${row.message}</td>
                                                    </tr>
                                                `).join('')}
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            `;
                            $(".AllStaffDataDiv").append(reportCard);
                        });

                    } else {
                        $(".AllStaffDataDiv").hide();
                        $(".DataDiv").fadeIn('slow');


                        $(".DataDiv").find('h6').text(`Showing From: ${formattedFrom} To: ${formattedTo}`);

                        const summary = response.summary;
                        $(".DataDiv").find(".fullname").text(summary.name);
                        $(".DataDiv").find(".absents").text(summary.absents);
                        $(".DataDiv").find(".lates").text(summary.lates);
                        $(".DataDiv").find(".presents").text(summary.presents);
                        $(".DataDiv").find(".missingouttimes").text(summary.missingOutTime);
                        $(".DataDiv").find(".workinghours").text(summary.workHours);
                        $(".DataDiv").find(".totalWorkingDays").text(summary.totalWorkingDays);
                        $(".DataDiv").find(".totalWorkingHours").text(summary.totalWorkingHours);

                        const tbody = $(".DataDiv").find(".tbody-2");
                        tbody.empty();

                        response.report.forEach(row => {
                            const tr = `<tr>
                            <td>${row.date} (${row.day})</td>
                            <td>${row.inTime || '-'}</td>
                            <td>${row.outTime || '-'}</td>
                            <td>${row.status}</td>
                            <td>${row.message}</td>
                        </tr>`;
                            tbody.append(tr);
                        });
                    }
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseText);
                },
                complete: function() {
                    $("#spinner-overlay").fadeOut('slow');
                }
            });
        });

        $(document).on('click', '.checkInBtn', function() {
            var $btn = $(this);
            $btn.hide();

            var empId = $btn.data('empid');
            var date = $btn.data('date');

            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=checkInCheckOut',
                type: 'POST',
                data: {
                    action: 'checkin',
                    emp_id: empId,
                    date: date
                },
                success: function(response) {
                    location.reload();
                }
            });
        });

        $(document).on('click', '.checkOutBtn', function() {
            var empId = $(this).data('empid');
            var date = $(this).data('date');

            $('#checkout-emp-id').val(empId);
            $('#checkout-date').val(date);
        });

        $("#checkOutForm").submit(function(e) {
            e.preventDefault();
            var formData = new FormData(this);
            formData.set('msg', tinymce.get('tinymice-editor').getContent());

            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=checkInCheckOut',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                beforeSend: function() {
                    $("#spinner-overlay").fadeIn('slow');
                },
                success: function(response) {
                    showAlert(response);
                    if (response === "checked-out") {
                        setTimeout(() => {
                            location.reload();
                        }, 2000);
                    }
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseText);
                },
                complete: function() {
                    $("#spinner-overlay").fadeOut('slow');
                }
            });
        });

        function loadUsers() {
            $.get("<?php echo WEB_URL; ?>/ajax_call?page=fetchChatUsers", function(res) {
                var users = JSON.parse(res);
                var html = '';
                users.forEach(user => {
                    if (user.acc_image == '') {
                        userImage = "<?php echo WEB_URL . '/webImages/avatars/default.png'; ?>";
                    } else {
                        userImage = "<?php echo WEB_URL . '/images/'; ?>" + user.acc_image;
                    }
                    html += `<a href="javascript:;" class="list-group-item user-select" data-id="${user.acc_id}">
                            <div class="d-flex">
                                <img src="${userImage}" width="42" height="42" class="rounded-circle" />
                                <div class="ms-2">
                                    <h6 class="mb-0">${user.acc_name}</h6>
                                    <p class="mb-0 small text-muted">${user.last_message ?? ''}</p>
                                </div>
                            </div>
                        </a>`;
                });
                $("#chatList .list-group").html(html);
            });
        }

        var sender_id = '<?php echo $webClass->webUserId(); ?>';
        var receiver_id = null;

        function loadMessages() {
            if (!receiver_id) return;
            $.post("<?php echo WEB_URL; ?>/ajax_call?page=fetchMessages", {
                sender: sender_id,
                receiver: receiver_id
            }, function(res) {
                var messages = JSON.parse(res);
                let html = "";
                messages.forEach(msg => {
                    if (msg.sender_id == sender_id) {
                        html += `<div class="chat-content-rightside">
                                    <div class="d-flex ms-auto">
                                        <div class="flex-grow-1 me-2">
                                            <p class="mb-0 chat-time text-end">you, ${msg.created_at}</p>
                                            <p class="chat-right-msg">${msg.message}</p>
                                        </div>
                                    </div>
                                </div>`;
                    } else {
                        html += `<div class="chat-content-leftside">
                                    <div class="d-flex">
                                        <div class="flex-grow-1 me-2">
                                            <p class="mb-0 chat-time">${msg.receiverName} ${msg.created_at}</p>
                                            <p class="chat-left-msg">${msg.message}</p>
                                        </div>
                                    </div>
                                </div>`;
                    }
                });
                $(".chat-content").html(html);
            });
        }

        $(document).on('click', '.user-select', function() {
            $('.user-select').removeClass('active');
            $(this).addClass('active');
            receiver_id = $(this).data('id');
            $.post("<?php echo WEB_URL; ?>/ajax_call?page=fetchChatUserDetail", {
                userId: receiver_id
            }, function(res) {
                var chatUserData = JSON.parse(res);
                $("#chatWindow").find(".currentChatUser").text(chatUserData.acc_name);

                const now = new Date();
                const nowTime = now.getTime();

                const lastSeenStr = chatUserData.last_seen.replace(' ', 'T');
                const lastSeenDate = new Date(lastSeenStr);
                const lastSeenTime = lastSeenDate.getTime();

                let statusHtml = '';

                if (nowTime - lastSeenTime <= 60000) {
                    statusHtml = `<small class='bx bxs-circle me-1 chart-online'></small>Active Now`;
                } else {
                    const hours = lastSeenDate.getHours();
                    const minutes = String(lastSeenDate.getMinutes()).padStart(2, '0');
                    const ampm = hours >= 12 ? 'PM' : 'AM';
                    const displayHour = hours % 12 === 0 ? 12 : hours % 12;
                    const formattedTime = `${displayHour}:${minutes} ${ampm}`;

                    const isToday = now.toDateString() === lastSeenDate.toDateString();

                    const yesterday = new Date();
                    yesterday.setDate(now.getDate() - 1);
                    const isYesterday = yesterday.toDateString() === lastSeenDate.toDateString();

                    if (isToday) {
                        statusHtml = `<small class='bx bxs-circle me-1'></small>Last seen today at ${formattedTime}`;
                    } else if (isYesterday) {
                        statusHtml = `<small class='bx bxs-circle me-1'></small>Last seen yesterday at ${formattedTime}`;
                    } else {
                        const day = String(lastSeenDate.getDate()).padStart(2, '0');
                        const month = String(lastSeenDate.getMonth() + 1).padStart(2, '0');
                        const year = lastSeenDate.getFullYear();
                        statusHtml = `<small class='bx bxs-circle me-1'></small>Last seen on ${day}/${month}/${year} at ${formattedTime}`;
                    }
                }

                $(".lastStatus").html(statusHtml);
            });
            $("#chatWindow").fadeIn('slow');
            loadMessages();
        });

        loadUsers();
        setInterval(loadMessages, 3000);

        $('#chatInput').keypress(function(e) {
            if (e.which == 13 && receiver_id) {
                let message = $(this).val().trim();
                if (message.length === 0) return;

                $.post("<?php echo WEB_URL; ?>/ajax_call?page=sendMessage", {
                    sender: sender_id,
                    receiver: receiver_id,
                    message: message
                }, function(res) {
                    $('#chatInput').val('');
                    loadMessages();
                });
            }
        });

        var button = document.querySelector('#emoji-button');

        var picker = new EmojiButton();
        if (button) {
            button.addEventListener('click', () => {
                picker.togglePicker(button);

            });
        }

        picker.on('emoji', emoji => {
            document.querySelector('#chatInput').value += emoji;
        });

        $('#fileTrigger').on('click', function() {
            $('#fileInput').click();
        });

        $('#fileInput').on('change', function() {
            if (!receiver_id) return;

            let file = this.files[0];
            if (!file) return;

            let formData = new FormData();
            formData.append('file', file);
            formData.append('sender', sender_id);
            formData.append('receiver', receiver_id);

            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=sendFileMessage',
                method: 'POST',
                data: formData,
                contentType: false,
                processData: false,
                success: function(res) {
                    loadMessages();
                }
            });
        });

        $('#findChatBtn').on('click', function() {
            if ($('#chatSearchInput').length === 0) {
                $('.chat-content').before(`
                    <div class="chat-search-bar mb-2">
                        <input type="text" id="chatSearchInput" class="form-control form-control-sm" placeholder="Search in chat...">
                    </div>
                `);

                $('#chatSearchInput').focus();
            } else {
                $('#chatSearchInput').parent().remove();
                loadMessages();
            }
        });

        $(document).on('input', '#chatSearchInput', function() {
            var searchTerm = $(this).val().toLowerCase();

            if (searchTerm === '') {
                loadMessages();
                return;
            }

            $('.chat-content').find('.chat-content-leftside, .chat-content-rightside').each(function() {
                var messageText = $(this).find('p.chat-left-msg, p.chat-right-msg').text().toLowerCase();
                if (messageText.indexOf(searchTerm) !== -1) {
                    $(this).show();
                } else {
                    $(this).hide();
                }
            });
        });

        $(document).on('click', '.group-select', function() {
            let groupId = $(this).data('group-id');
            receiver_id = null;

            $.post("<?php echo WEB_URL; ?>/ajax_call?page=fetchGroupMessages", {
                group_id: groupId
            }, function(res) {
                let messages = JSON.parse(res);
                let html = "";
                messages.forEach(msg => {
                    let side = msg.sender_id == sender_id ? 'right' : 'left';
                    html += `
                        <div class="chat-content-${side}side">
                            <div class="d-flex ${side === 'right' ? 'ms-auto' : ''}">
                                <div class="flex-grow-1 me-2">
                                    <p class="mb-0 chat-time text-${side === 'right' ? 'end' : 'start'}">${msg.senderName} ${msg.created_at}</p>
                                    <p class="chat-${side}-msg">${msg.message}</p>
                                </div>
                            </div>
                        </div>`;
                });
                $(".chat-content").html(html);
                $("#chatWindow").fadeIn('slow');
                $(".currentChatUser").text("Group Chat");
                $(".lastStatus").html("");
            });
        });

        $("#createGroupForm").submit(function(e) {
            e.preventDefault();
            var formData = new FormData(this);
            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=createChatGroup',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                dataType: "json",
                beforeSend: function() {
                    $("#spinner-overlay").fadeIn('slow');
                },
                success: function(response) {
                    showAlert(response.message);
                    if (response.status === "success") {
                        setTimeout(() => {
                            window.location.reload();
                        }, 1000);
                    }
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseJSON);
                },
                complete: function() {
                    $("#spinner-overlay").fadeOut('slow');
                }
            });
        });

        $("#projectAddForm").submit(function(e) {
            e.preventDefault();
            var formData = new FormData(this);
            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=addNewProject',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                dataType: "json",
                beforeSend: function() {
                    $("#spinner-overlay").fadeIn('slow');
                },
                success: function(response) {
                    showAlert(response.message);
                    if (response.status === "success") {
                        $("#projectAddForm").trigger("reset");
                        $("#projectAddForm select[multiple]").val(null).trigger("change");
                        loadPage(response.redirect, 'View/Edit Project');
                    }
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseJSON);
                },
                complete: function() {
                    $("#spinner-overlay").fadeOut('slow');
                }
            });
        });

        var projectsGrid = document.getElementById('projectsGrid');
        if (projectsGrid) {
            new Sortable(projectsGrid, {
                animation: 150,
                onEnd: function(evt) {
                    const order = [];
                    document.querySelectorAll('#projectsGrid .list-group-item').forEach(el => {
                        order.push(el.getAttribute('data-id'));
                    });

                    fetch('<?php echo WEB_URL; ?>/ajax_call?page=updateProjectSort', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            order: order
                        })
                    }).then(res => res.json()).then(data => {
                        showAlert(data.message);
                    });
                }
            });
        }

        $('input[name="invoiceformat"]').on('change', function() {
            var invoiceFormat = $('input[name="invoiceformat"]:checked').val();

            if (invoiceFormat === "Imedia") {
                $('#invnumber').attr('readonly', true);
            } else {
                $('#invnumber').removeAttr('readonly');
            }
        });

        $(document).ready(function() {
            $('input[name="invoiceformat"]').trigger('change');
        });

        $("#invclientId").change(function() {
            var clientId = $(this).val();
            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=getClientCompanies',
                type: 'POST',
                data: {
                    clientId: clientId
                },
                success: function(response) {
                    var companies = JSON.parse(response);

                    var $companySelect = $("#invcompany");
                    $companySelect.empty();
                    $companySelect.append('<option value="">Select...</option>');

                    if (companies.length > 0) {
                        companies.forEach(function(company) {
                            $companySelect.append('<option value="' + company.company_name + '">' + company.company_name + '</option>');
                        });
                        $companySelect.prop('disabled', false);
                    } else {
                        $companySelect.prop('disabled', true);
                    }
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseText);
                }
            });
        });

        if ($(".getClientProjects").length > 0) {
            var clientId = $(".getClientProjects").val();
            if (clientId != '') {
                $.ajax({
                    url: '<?php echo WEB_URL; ?>/ajax_call?page=getClientProjects',
                    type: 'POST',
                    data: {
                        clientId: clientId
                    },
                    success: function(response) {
                        var projects = JSON.parse(response);

                        var $clientSelect = $(".showClientProjects");
                        $clientSelect.empty();
                        $clientSelect.append('<option value="">Select...</option>');

                        if (projects.length > 0) {
                            projects.forEach(function(project) {
                                $clientSelect.append('<option value="' + project.id + '">' + project.project_title + '</option>');
                            });
                            $clientSelect.prop('disabled', false);
                        } else {
                            $clientSelect.prop('disabled', true);
                        }
                    },
                    error: function(xhr, status, errorThrown) {
                        console.log(xhr.responseText);
                    }
                });
            }
        }

        $(".getClientProjects").change(function() {
            var clientId = $(this).val();
            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=getClientProjects',
                type: 'POST',
                data: {
                    clientId: clientId
                },
                success: function(response) {
                    var projects = JSON.parse(response);

                    var $clientSelect = $(".showClientProjects");
                    $clientSelect.empty();
                    $clientSelect.append('<option value="">Select...</option>');

                    if (projects.length > 0) {
                        projects.forEach(function(project) {
                            $clientSelect.append('<option value="' + project.id + '">' + project.project_title + '</option>');
                        });
                        $clientSelect.prop('disabled', false);
                    } else {
                        $clientSelect.prop('disabled', true);
                    }
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseText);
                }
            });
        });

        $("#invstatus").change(function() {
            var value = $(this).val();
            if (value == "7" || value == "8") {
                $("#recurrenceDiv").fadeIn('slow');
                $("#invprototalamountDiv").fadeIn('slow');
                $("#invrcvdamountDiv").fadeIn('slow');
            } else {
                $("#recurrenceDiv").fadeOut('slow');
                $("#invprototalamountDiv").fadeOut('slow');
                $("#invrcvdamountDiv").fadeOut('slow');
            }
        });

        $('#invtype').change(function(event) {
            val = $(this).val();
            billed_amount = parseFloat($('#invbilledamount').val());
            if (typeof(val) !== "undefined") {
                if (val == 'sales_tax') {
                    tax_amount = eval(billed_amount * 0.15);
                    sales_tax = eval(billed_amount + (billed_amount) * 0.15);
                } else if (val == 'normal') {
                    tax_amount = 0;
                    sales_tax = billed_amount;
                }
                $('#invtaxamount').val(tax_amount);
                $('#invtotalbillamount').val(sales_tax);
            } else {
                $('#invtotalbillamount').val(0);
            }
        });


        function updateTotalAmount(ths) {
            bil_amnt = $(ths).val();
            inv_for = parseFloat($('#invtype').val());

            if (inv_for == 'sales_tax') {
                tax_amount = bil_amnt * 0.13;
                sales_tax = bil_amnt + (bil_amnt) * 0.13;
            } else {
                tax_amount = 0;
                sales_tax = bil_amnt;
            }
            $('#invtaxamount').val(tax_amount);
            $('#invtotalbillamount').val(sales_tax);
        }

        function toggleVendorDetails(button) {
            const vendorDiv = document.querySelector('.showHideDiv');

            if (vendorDiv.style.display === 'none' || vendorDiv.style.display === '') {
                vendorDiv.style.display = 'block';
                button.textContent = 'Hide Vendor Details';
            } else {
                vendorDiv.style.display = 'none';
                button.textContent = 'Show Vendor Details';
            }
        }

        $("#invoiceCreateForm").submit(function(e) {
            e.preventDefault();
            var formData = new FormData(this);
            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=createInvoice',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                dataType: "json",
                beforeSend: function() {
                    $("#spinner-overlay").fadeIn('slow');
                },
                success: function(response) {
                    showAlert(response.message);
                    if (response.status === "success") {
                        loadPage(response.redirect, 'View/Edit Invoice')
                    }
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseJSON);
                },
                complete: function() {
                    $("#spinner-overlay").fadeOut('slow');
                }
            });
        });

        $("#invoiceEditForm").submit(function(e) {
            e.preventDefault();
            var formData = new FormData(this);
            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=editInvoice',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                dataType: "json",
                beforeSend: function() {
                    $("#spinner-overlay").fadeIn('slow');
                },
                success: function(response) {
                    showAlert(response.message);
                    if (response.status === "success") {
                        loadPage(response.redirect, 'View/Edit Invoice')
                    }
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseJSON);
                },
                complete: function() {
                    $("#spinner-overlay").fadeOut('slow');
                }
            });
        });

        $("#inquiryAddForm").submit(function(e) {
            e.preventDefault();
            var formData = new FormData(this);
            formData.set('phone', iti.getNumber(intlTelInputUtils.numberFormat.E164));
            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=addNewInquiry',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                dataType: "json",
                beforeSend: function() {
                    $("#spinner-overlay").fadeIn('slow');
                },
                success: function(response) {
                    showAlert(response.message);
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseJSON);
                },
                complete: function() {
                    $("#spinner-overlay").fadeOut('slow');
                }
            });
        });

        $("#ticketAddForm").submit(function(e) {
            e.preventDefault();
            var formData = new FormData(this);
            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=addNewTicket',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                dataType: "json",
                beforeSend: function() {
                    $("#spinner-overlay").fadeIn('slow');
                },
                success: function(response) {
                    showAlert(response.message);
                    if (response.status === "success") {
                        $("#ticketAddForm").trigger("reset");
                    }
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseJSON);
                },
                complete: function() {
                    $("#spinner-overlay").fadeOut('slow');
                }
            });
        });

        $("#ticketEditForm").submit(function(e) {
            e.preventDefault();
            var formData = new FormData(this);
            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=editTicket',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                dataType: "json",
                beforeSend: function() {
                    $("#spinner-overlay").fadeIn('slow');
                },
                success: function(response) {
                    showAlert(response.message);
                    if (response.status === "success") {
                        setTimeout(() => {
                            loadPage(response.redirect, response.title);
                        }, 1000);
                    }
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseJSON);
                },
                complete: function() {
                    $("#spinner-overlay").fadeOut('slow');
                }
            });
        });

        $("#eventAddForm").submit(function(e) {
            e.preventDefault();
            var formData = new FormData(this);
            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=addNewEvent',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                dataType: "json",
                beforeSend: function() {
                    $("#spinner-overlay").fadeIn('slow');
                },
                success: function(response) {
                    showAlert(response.message);
                    if (response.status === "success") {
                        setTimeout(() => {
                            $("#eventAddForm").trigger("reset");
                            loadPage(response.redirect, 'Calendar');
                        }, 1000);
                    }
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseJSON);
                },
                complete: function() {
                    $("#spinner-overlay").fadeOut('slow');
                }
            });
        });

        var calendarEl = document.getElementById('calendar');
        if (calendarEl) {
            var calendar = new FullCalendar.Calendar(calendarEl, {
                headerToolbar: {
                    left: 'prev,next today',
                    center: 'title',
                    right: 'dayGridMonth,timeGridWeek,timeGridDay'
                },
                initialView: 'dayGridMonth',
                editable: false,
                dayMaxEvents: true,
                events: <?php echo $crm->calendarEvents(); ?>,

                eventDidMount: function(info) {
                    let event = info.event;
                    let el = info.el;

                    el.setAttribute('id', event.id);
                    el.setAttribute('data-type', event.extendedProps.type);
                    if (event.extendedProps.click) {
                        el.setAttribute('onclick', event.extendedProps.click);
                    }

                    let dsc = event.extendedProps.detail ? '<br><span>detail :</span> ' + event.extendedProps.detail : '';
                    let due = event.extendedProps.due_date ? '<br><span>Due Date :</span> ' + event.extendedProps.due_date : '';
                    let demo = event.extendedProps.demo_date ? '<br><span>Demo Date :</span> ' + event.extendedProps.demo_date : '';

                    let tooltipHTML = `<div class="tooltiptopicevent">
                        <div>
                            <span><strong>title :</strong></span> ${event.title}
                            <br><span><strong>Category :</strong></span> ${event.extendedProps.category || ''}
                            ${due}
                            <br><span><strong>status :</strong></span> ${event.extendedProps.status || ''}
                            ${dsc}
                            ${demo}
                            <div class="bottom-bar" style="background-color: ${event.backgroundColor || '#ffc107'}"></div>
                        </div>
                    </div>`;


                    el.addEventListener('mouseenter', function(e) {
                        const tooltip = $(tooltipHTML).css({
                            position: 'absolute',
                            top: e.pageY + 10,
                            left: e.pageX + 20,
                            display: 'none',
                            zIndex: 10001
                        });

                        $("body").append(tooltip);
                        tooltip.fadeIn(500).fadeTo(10, 1.9);

                        el.addEventListener('mousemove', function(e) {
                            tooltip.css({
                                top: e.pageY + 10,
                                left: e.pageX + 20
                            });
                        });

                        el.addEventListener('mouseleave', function() {
                            tooltip.remove();
                        }, {
                            once: true
                        });
                    });
                }
            });

            calendar.render();
        }

        function editEventForm(ths, id) {
            $('#eventEditModal').modal('show');

            $('#eventEditModal .modal-body').html('<div>Loading...</div>');

            $.ajax({
                url: 'eventedit',
                type: 'GET',
                data: {
                    id: id
                },
                success: function(response) {
                    $('#eventEditModal .modal-body').html(response);
                },
                error: function(xhr) {
                    $('#eventEditModal .modal-body').html('<div class="text-danger">Failed to load event data.</div>');
                }
            });
        }

        $('#eventSearch').on('keyup', function() {
            var search = $(this).val().toLowerCase();
            $('.event-box').each(function() {
                var title = $(this).data('title');
                $(this).toggle(title.includes(search));
            });
        });

        $('#eventUserSelect').on('change', function() {
            var selectedUser = $(this).val();
            $('.event-box').each(function() {
                var boxUser = $(this).data('user');
                $(this).toggle(selectedUser === '' || selectedUser == boxUser);
            });
        });

        $(document).on("submit", "#eventEditForm", function(e) {
            e.preventDefault();
            var formData = new FormData(this);
            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=editEvent',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                dataType: "json",
                beforeSend: function() {
                    $("#spinner-overlay").fadeIn('slow');
                },
                success: function(response) {
                    showAlert(response.message);
                    if (response.status === "success") {
                        $('#eventEditModal').modal('hide');
                        loadPage('calendar', 'Calendar');
                    }
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseJSON);
                },
                complete: function() {
                    $("#spinner-overlay").fadeOut('slow');
                }
            });
        });

        function deleteEvent(ths) {
            var deleteEventId = $(ths).attr('data-id');
            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=deleteEvent',
                type: 'POST',
                data: {
                    deleteEventId: deleteEventId
                },
                beforeSend: function() {
                    $("#spinner-overlay").fadeIn('slow');
                },
                success: function(response) {
                    if (response == '1') {
                        $(ths).closest('.col-4').hide(1000, function() {
                            $(this).remove();
                        });
                    } else if (response == '0') {
                        showAlert("Delete fail please try again.");
                    } else {
                        window.location.reload();
                    }
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseJSON);
                },
                complete: function() {
                    $("#spinner-overlay").fadeOut('slow');
                }
            });
        }

        $("#expenseAddForm").submit(function(e) {
            e.preventDefault();
            var formData = new FormData(this);
            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=addNewDailyExpense',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                dataType: "json",
                beforeSend: function() {
                    $("#spinner-overlay").fadeIn('slow');
                },
                success: function(response) {
                    showAlert(response.message);
                    if (response.status === "success") {
                        $("#expenseAddForm").trigger("reset");
                    }
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseJSON);
                },
                complete: function() {
                    $("#spinner-overlay").fadeOut('slow');
                }
            });
        });

        $("#expenseEditForm").submit(function(e) {
            e.preventDefault();
            var formData = new FormData(this);
            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=editExpense',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                dataType: "json",
                beforeSend: function() {
                    $("#spinner-overlay").fadeIn('slow');
                },
                success: function(response) {
                    showAlert(response.message);
                    if (response.status === "success") {
                        setTimeout(() => {
                            loadPage(response.redirect, 'View/Edit Expense');
                        }, 1000);
                    }
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseJSON);
                },
                complete: function() {
                    $("#spinner-overlay").fadeOut('slow');
                }
            });
        });

        function deleteDailyExpense(ths) {
            var deleteExpenseId = $(ths).attr('data-id');
            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=deleteDailyExpense',
                type: 'POST',
                data: {
                    deleteExpenseId: deleteExpenseId
                },
                beforeSend: function() {
                    $("#spinner-overlay").fadeIn('slow');
                },
                success: function(response) {
                    if (response == '1') {
                        $(ths).closest('tr').hide(1000, function() {
                            $(this).remove();
                        });
                    } else if (response == '0') {
                        showAlert("Delete fail please try again.");
                    } else {
                        window.location.reload();
                    }
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseJSON);
                },
                complete: function() {
                    $("#spinner-overlay").fadeOut('slow');
                }
            });
        }

        $("#designationAddForm").submit(function(e) {
            e.preventDefault();
            var formData = new FormData(this);
            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=addNewDesignation',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                dataType: "json",
                beforeSend: function() {
                    $("#spinner-overlay").fadeIn('slow');
                },
                success: function(response) {
                    showAlert(response.message);
                    if (response.status === "success") {
                        $("#designationAddForm").trigger("reset");
                    }
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseJSON);
                },
                complete: function() {
                    $("#spinner-overlay").fadeOut('slow');
                }
            });
        });

        $("#designationEditForm").submit(function(e) {
            e.preventDefault();
            var formData = new FormData(this);
            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=editDesignation',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                dataType: "json",
                beforeSend: function() {
                    $("#spinner-overlay").fadeIn('slow');
                },
                success: function(response) {
                    showAlert(response.message);
                    if (response.status === "success") {
                        setTimeout(() => {
                            loadPage(response.redirect, 'Manage Designations');
                        }, 1000);
                    }
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseJSON);
                },
                complete: function() {
                    $("#spinner-overlay").fadeOut('slow');
                }
            });
        });

        function deleteDesignation(ths) {
            var deleteDesignationId = $(ths).attr('data-id');
            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=deleteDesignation',
                type: 'POST',
                data: {
                    deleteDesignationId: deleteDesignationId
                },
                beforeSend: function() {
                    $("#spinner-overlay").fadeIn('slow');
                },
                success: function(response) {
                    if (response == '1') {
                        $(ths).closest('tr').hide(1000, function() {
                            $(this).remove();
                        });
                    } else if (response == '0') {
                        showAlert("Delete fail please try again.");
                    } else {
                        window.location.reload();
                    }
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseJSON);
                },
                complete: function() {
                    $("#spinner-overlay").fadeOut('slow');
                }
            });
        }

        $("#projecttypeAddForm").submit(function(e) {
            e.preventDefault();
            var formData = new FormData(this);
            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=addNewProjectType',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                dataType: "json",
                beforeSend: function() {
                    $("#spinner-overlay").fadeIn('slow');
                },
                success: function(response) {
                    showAlert(response.message);
                    if (response.status === "success") {
                        $("#projecttypeAddForm").trigger("reset");
                    }
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseJSON);
                },
                complete: function() {
                    $("#spinner-overlay").fadeOut('slow');
                }
            });
        });

        $("#projectTypeEditForm").submit(function(e) {
            e.preventDefault();
            var formData = new FormData(this);
            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=editProjectType',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                dataType: "json",
                beforeSend: function() {
                    $("#spinner-overlay").fadeIn('slow');
                },
                success: function(response) {
                    showAlert(response.message);
                    if (response.status === "success") {
                        setTimeout(() => {
                            loadPage(response.redirect, 'Manage Project Type');
                        }, 1000);
                    }
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseJSON);
                },
                complete: function() {
                    $("#spinner-overlay").fadeOut('slow');
                }
            });
        });

        function deleteProjectType(ths) {
            var deleteProjectTypeId = $(ths).attr('data-id');
            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=deleteProjectType',
                type: 'POST',
                data: {
                    deleteProjectTypeId: deleteProjectTypeId
                },
                beforeSend: function() {
                    $("#spinner-overlay").fadeIn('slow');
                },
                success: function(response) {
                    if (response == '1') {
                        $(ths).closest('tr').hide(1000, function() {
                            $(this).remove();
                        });
                    } else if (response == '0') {
                        showAlert("Delete fail please try again.");
                    } else {
                        window.location.reload();
                    }
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseJSON);
                },
                complete: function() {
                    $("#spinner-overlay").fadeOut('slow');
                }
            });
        }

        $("#invoicestatusAddForm").submit(function(e) {
            e.preventDefault();
            var formData = new FormData(this);
            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=addNewInvoiceStatus',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                dataType: "json",
                beforeSend: function() {
                    $("#spinner-overlay").fadeIn('slow');
                },
                success: function(response) {
                    showAlert(response.message);
                    if (response.status === "success") {
                        $("#invoicestatusAddForm").trigger("reset");
                    }
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseJSON);
                },
                complete: function() {
                    $("#spinner-overlay").fadeOut('slow');
                }
            });
        });

        $("#invoicestatusEditForm").submit(function(e) {
            e.preventDefault();
            var formData = new FormData(this);
            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=editInvoiceStatus',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                dataType: "json",
                beforeSend: function() {
                    $("#spinner-overlay").fadeIn('slow');
                },
                success: function(response) {
                    showAlert(response.message);
                    if (response.status === "success") {
                        setTimeout(() => {
                            loadPage(response.redirect, 'Manage Invoice Statuses');
                        }, 1000);
                    }
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseJSON);
                },
                complete: function() {
                    $("#spinner-overlay").fadeOut('slow');
                }
            });
        });

        function deleteInvoiceStatus(ths) {
            var deleteInvoiceStatusId = $(ths).attr('data-id');
            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=deleteInvoiceStatus',
                type: 'POST',
                data: {
                    deleteInvoiceStatusId: deleteInvoiceStatusId
                },
                beforeSend: function() {
                    $("#spinner-overlay").fadeIn('slow');
                },
                success: function(response) {
                    if (response == '1') {
                        $(ths).closest('tr').hide(1000, function() {
                            $(this).remove();
                        });
                    } else if (response == '0') {
                        showAlert("Delete fail please try again.");
                    } else {
                        window.location.reload();
                    }
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseJSON);
                },
                complete: function() {
                    $("#spinner-overlay").fadeOut('slow');
                }
            });
        }

        $("#projectstatusAddForm").submit(function(e) {
            e.preventDefault();
            var formData = new FormData(this);
            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=addNewProjectStatus',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                dataType: "json",
                beforeSend: function() {
                    $("#spinner-overlay").fadeIn('slow');
                },
                success: function(response) {
                    showAlert(response.message);
                    if (response.status === "success") {
                        $("#projectstatusAddForm").trigger("reset");
                    }
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseJSON);
                },
                complete: function() {
                    $("#spinner-overlay").fadeOut('slow');
                }
            });

        });

        $("#projectstatusEditForm").submit(function(e) {
            e.preventDefault();
            var formData = new FormData(this);
            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=editProjectStatus',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                dataType: "json",
                beforeSend: function() {
                    $("#spinner-overlay").fadeIn('slow');
                },
                success: function(response) {
                    showAlert(response.message);
                    if (response.status === "success") {
                        setTimeout(() => {
                            loadPage(response.redirect, 'Manage Project Status');
                        }, 1000);
                    }
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseJSON);
                },
                complete: function() {
                    $("#spinner-overlay").fadeOut('slow');
                }
            });
        });

        function deleteProjectStatus(ths) {
            var deleteProjectStatusId = $(ths).attr('data-id');
            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=deleteProjectStatus',
                type: 'POST',
                data: {
                    deleteProjectStatusId: deleteProjectStatusId
                },
                beforeSend: function() {
                    $("#spinner-overlay").fadeIn('slow');
                },
                success: function(response) {
                    if (response == '1') {
                        $(ths).closest('tr').hide(1000, function() {
                            $(this).remove();
                        });
                    } else if (response == '0') {
                        showAlert("Delete fail please try again.");
                    } else {
                        window.location.reload();
                    }
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseJSON);
                },
                complete: function() {
                    $("#spinner-overlay").fadeOut('slow');
                }
            });
        }

        $("#projectcategoriesAddForm").submit(function(e) {
            e.preventDefault();
            var formData = new FormData(this);
            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=addNewProjectCategory',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                dataType: "json",
                beforeSend: function() {
                    $("#spinner-overlay").fadeIn('slow');
                },
                success: function(response) {
                    showAlert(response.message);
                    if (response.status === "success") {
                        $("#projectcategoriesAddForm").trigger("reset");
                    }
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseJSON);
                },
                complete: function() {
                    $("#spinner-overlay").fadeOut('slow');
                }
            });
        });

        $("#projectcategoriesEditForm").submit(function(e) {
            e.preventDefault();
            var formData = new FormData(this);
            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=editProjectCategory',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                dataType: "json",
                beforeSend: function() {
                    $("#spinner-overlay").fadeIn('slow');
                },
                success: function(response) {
                    showAlert(response.message);
                    if (response.status === "success") {
                        setTimeout(() => {
                            loadPage(response.redirect, 'Manage Project Categories');
                        }, 1000);
                    }
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseJSON);
                },
                complete: function() {
                    $("#spinner-overlay").fadeOut('slow');
                }
            });
        });

        function deleteProjectCategory(ths) {
            var deleteProjectCategoryId = $(ths).attr('data-id');
            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=deleteProjectCategory',
                type: 'POST',
                data: {
                    deleteProjectCategoryId: deleteProjectCategoryId
                },
                beforeSend: function() {
                    $("#spinner-overlay").fadeIn('slow');
                },
                success: function(response) {
                    if (response == '1') {
                        $(ths).closest('tr').hide(1000, function() {
                            $(this).remove();
                        });
                    } else if (response == '0') {
                        showAlert("Delete fail please try again.");
                    } else {
                        window.location.reload();
                    }
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseJSON);
                },
                complete: function() {
                    $("#spinner-overlay").fadeOut('slow');
                }
            });
        }

        $("#serviceAddForm").submit(function(e) {
            e.preventDefault();
            var formData = new FormData(this);
            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=addNewService',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                dataType: "json",
                beforeSend: function() {
                    $("#spinner-overlay").fadeIn('slow');
                },
                success: function(response) {
                    showAlert(response.message);
                    if (response.status === "success") {
                        $("#serviceAddForm").trigger("reset");
                    }
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseJSON);
                },
                complete: function() {
                    $("#spinner-overlay").fadeOut('slow');
                }
            });
        });

        $("#serviceEditForm").submit(function(e) {
            e.preventDefault();
            var formData = new FormData(this);
            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=editService',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                dataType: "json",
                beforeSend: function() {
                    $("#spinner-overlay").fadeIn('slow');
                },
                success: function(response) {
                    showAlert(response.message);
                    if (response.status === "success") {
                        setTimeout(() => {
                            loadPage(response.redirect, 'Manage Inquiry Services');
                        }, 1000);
                    }
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseJSON);
                },
                complete: function() {
                    $("#spinner-overlay").fadeOut('slow');
                }
            });
        });

        function deleteService(ths) {
            var deleteServiceId = $(ths).attr('data-id');
            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=deleteService',
                type: 'POST',
                data: {
                    deleteServiceId: deleteServiceId
                },
                beforeSend: function() {
                    $("#spinner-overlay").fadeIn('slow');
                },
                success: function(response) {
                    if (response == '1') {
                        $(ths).closest('tr').hide(1000, function() {
                            $(this).remove();
                        });
                    } else if (response == '0') {
                        showAlert("Delete fail please try again.");
                    } else {
                        window.location.reload();
                    }
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseJSON);
                },
                complete: function() {
                    $("#spinner-overlay").fadeOut('slow');
                }
            });
        }

        $("#expensecategoryAddForm").submit(function(e) {
            e.preventDefault();
            var formData = new FormData(this);
            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=addNewExpenseCategory',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                dataType: "json",
                beforeSend: function() {
                    $("#spinner-overlay").fadeIn('slow');
                },
                success: function(response) {
                    showAlert(response.message);
                    if (response.status === "success") {
                        $("#expensecategoryAddForm").trigger("reset");
                    }
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseJSON);
                },
                complete: function() {
                    $("#spinner-overlay").fadeOut('slow');
                }
            });
        });

        $("#expensecategoryEditForm").submit(function(e) {
            e.preventDefault();
            var formData = new FormData(this);
            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=editExpenseCategory',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                dataType: "json",
                beforeSend: function() {
                    $("#spinner-overlay").fadeIn('slow');
                },
                success: function(response) {
                    showAlert(response.message);
                    if (response.status === "success") {
                        setTimeout(() => {
                            loadPage(response.redirect, 'Manage Expense Categories');
                        }, 1000);
                    }
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseJSON);
                },
                complete: function() {
                    $("#spinner-overlay").fadeOut('slow');
                }
            });
        });

        function deleteExpenseCategory(ths) {
            var deleteExpenseCategoryId = $(ths).attr('data-id');
            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=deleteExpenseCategory',
                type: 'POST',
                data: {
                    deleteExpenseCategoryId: deleteExpenseCategoryId
                },
                beforeSend: function() {
                    $("#spinner-overlay").fadeIn('slow');
                },
                success: function(response) {
                    if (response == '1') {
                        $(ths).closest('tr').hide(1000, function() {
                            $(this).remove();
                        });
                    } else if (response == '0') {
                        showAlert("Delete fail please try again.");
                    } else {
                        window.location.reload();
                    }
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseJSON);
                },
                complete: function() {
                    $("#spinner-overlay").fadeOut('slow');
                }
            });
        }

        $("#ticketcategoryAddForm").submit(function(e) {
            e.preventDefault();
            var formData = new FormData(this);
            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=addNewTicketCategory',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                dataType: "json",
                beforeSend: function() {
                    $("#spinner-overlay").fadeIn('slow');
                },
                success: function(response) {
                    showAlert(response.message);
                    if (response.status === "success") {
                        $("#ticketcategoryAddForm").trigger("reset");
                    }
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseJSON);
                },
                complete: function() {
                    $("#spinner-overlay").fadeOut('slow');
                }
            });
        });

        $("#ticketcategoryEditForm").submit(function(e) {
            e.preventDefault();
            var formData = new FormData(this);
            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=editTicketCategory',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                dataType: "json",
                beforeSend: function() {
                    $("#spinner-overlay").fadeIn('slow');
                },
                success: function(response) {
                    showAlert(response.message);
                    if (response.status === "success") {
                        setTimeout(() => {
                            loadPage(response.redirect, 'Manage Ticket Categories');
                        }, 1000);
                    }
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseJSON);
                },
                complete: function() {
                    $("#spinner-overlay").fadeOut('slow');
                }
            });
        });

        function deleteTicketCategory(ths) {
            var deleteTicketCategoryId = $(ths).attr('data-id');
            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=deleteTicketCategory',
                type: 'POST',
                data: {
                    deleteTicketCategoryId: deleteTicketCategoryId
                },
                beforeSend: function() {
                    $("#spinner-overlay").fadeIn('slow');
                },
                success: function(response) {
                    if (response == '1') {
                        $(ths).closest('tr').hide(1000, function() {
                            $(this).remove();
                        });
                    } else if (response == '0') {
                        showAlert("Delete fail please try again.");
                    } else {
                        window.location.reload();
                    }
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseJSON);
                },
                complete: function() {
                    $("#spinner-overlay").fadeOut('slow');
                }
            });
        }

        $("#saturdayAddForm").submit(function(e) {
            e.preventDefault();
            if (!$("input[name='date[]']:checked").length) {
                showAlert("Please select at least one Saturday.");
                return;
            }
            var formData = new FormData(this);
            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=saturdaysOffAdd',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                dataType: "json",
                beforeSend: function() {
                    $("#spinner-overlay").fadeIn('slow');
                },
                success: function(response) {
                    showAlert(response.message);
                    if (response.status === "success") {
                        setTimeout(() => {
                            $("#saturdayAddForm").trigger("reset");
                            loadPage(response.redirect, 'saturdays');
                        }, 1000);
                    }
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseJSON);
                },
                complete: function() {
                    $("#spinner-overlay").fadeOut('slow');
                }
            });
        });

        function deleteSaturday(ths) {
            var deleteSaturdayId = $(ths).attr('data-id');
            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=deleteSaturday',
                type: 'POST',
                data: {
                    deleteSaturdayId: deleteSaturdayId
                },
                beforeSend: function() {
                    $("#spinner-overlay").fadeIn('slow');
                },
                success: function(response) {
                    if (response == '1') {
                        $(ths).closest('tr').hide(1000, function() {
                            $(this).remove();
                        });
                    } else if (response == '0') {
                        showAlert("Delete fail please try again.");
                    } else {
                        window.location.reload();
                    }
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseJSON);
                },
                complete: function() {
                    $("#spinner-overlay").fadeOut('slow');
                }
            });
        }

        $("#changePasswordForm").submit(function(e) {
            e.preventDefault();
            var formData = new FormData(this);
            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=updatePassword',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                dataType: "json",
                beforeSend: function() {
                    $("#spinner-overlay").fadeIn('slow');
                },
                success: function(response) {
                    showAlert(response.message);
                    if (response.status === "success") {
                        setTimeout(() => {
                            window.location.href = 'logout';
                        }, 1000);
                    }
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseJSON);
                },
                complete: function() {
                    $("#spinner-overlay").fadeOut('slow');
                }
            });
        });

        function addNote(button, noteType) {
            var targetId = $(button).attr('data-id');
            $('#noteTargetId').val(targetId);
            $('#noteTargetType').val(noteType);
            $('#noteText').val('');
            if ($("#viewNotesModal")) {
                $("#viewNotesModal").modal('hide');
            }
            $('#addNoteModal').modal('show');
        }

        function viewNotes(button, noteType) {
            var targetId = $(button).attr('data-id');
            var description = $(button).attr('data-desc');
            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=getNotes',
                type: 'POST',
                data: {
                    target_type: noteType,
                    target_id: targetId
                },
                beforeSend: function() {
                    $('#notesContent').html('<div class="text-center">Loading notes...</div>');
                    if (noteType == "client" || noteType == "lead") {
                        $('#viewNotesModal').find(".modal-dialog").removeClass("modal-dialog-centered");
                        $('#viewNotesModal').find(".modal-dialog").addClass("modal-fullscreen");
                    } else if ($('#viewNotesModal').find("modal-dialog-centered")) {
                        $('#viewNotesModal').find(".modal-dialog").removeClass("modal-fullscreen");
                        $('#viewNotesModal').find(".modal-dialog").addClass("modal-dialog-centered");
                    }
                    $('#viewNotesModal').modal('show');
                },
                success: function(response) {
                    $('#ticketDesc').html(description);
                    $('#notesContent').html(response);
                },
                error: function(xhr) {
                    console.log(xhr.responseText);
                    $('#notesContent').html('<div class="text-danger">Failed to load notes.</div>');
                }
            });
        }

        $("#addNoteForm").submit(function(e) {
            e.preventDefault();

            var noteText = $('#noteText').val().trim();
            var noteTextEmail = $('#noteTextEmail').val().trim();
            var targetId = $('#noteTargetId').val();
            var targetType = $('#noteTargetType').val();

            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=addNote',
                type: 'POST',
                data: {
                    note_text: noteText,
                    note_text_email: noteTextEmail,
                    target_type: targetType,
                    target_id: targetId
                },
                dataType: "json",
                beforeSend: function() {
                    $("#spinner-overlay").fadeIn('slow');
                },
                success: function(response) {
                    showAlert(response.message);
                    if (response.status === "success") {
                        setTimeout(() => {
                            $('#addNoteModal').modal('hide');
                        }, 1000);
                    }
                },
                error: function(xhr, status, errorThrown) {
                    console.log(xhr.responseText);
                },
                complete: function() {
                    $("#spinner-overlay").fadeOut('slow');
                }
            });
        });

        function fetchNotifications() {
            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=getNotifications',
                method: 'GET',
                dataType: 'json',
                success: function(data) {
                    $('#notification-count').text(data.length);
                    let html = '';

                    if (data.length === 0) {
                        html = '<div class="px-3 py-2">No new notifications</div>';
                    } else {
                        data.forEach(function(item) {
                            html += `<div>
                            <a href="${item.link}" class="dropdown-item border-bottom py-2" data-id="${item.id}">
                            <div class="d-flex align-items-center gap-3">
                                <div class="">
                                    <h5 class="notify-title">${item.title}</h5>
                                    <p class="mb-0 notify-desc">${item.message}</p>
                                    <p class="mb-0 notify-time">${item.created_at}</p>
                                </div>
                            </div>
                            </a>
                        </div>`;
                        });
                    }

                    $('#notification-list').html(html);
                }
            });
        }

        fetchNotifications();
        setInterval(fetchNotifications, 15000);

        $(document).on('click', '.notification-link', function() {
            const id = $(this).data('id');
            $.post('<?php echo WEB_URL; ?>/ajax_call?page=markNotificationRead', {
                id
            });
        });

        $('#search').on('input', function() {
            let query = $(this).val().trim();

            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=searchAll',
                method: 'POST',
                data: {
                    search: query
                },
                success: function(response) {
                    $('.search-popup').show();
                    $('.search-content').html(response);
                }
            });
        });

        $('#searchMobile').on('input', function() {
            let query = $(this).val().trim();

            $.ajax({
                url: '<?php echo WEB_URL; ?>/ajax_call?page=searchAll',
                method: 'POST',
                data: {
                    search: query
                },
                success: function(response) {
                    $('.search-popup').show();
                    $('.search-content').html(response);
                }
            });
        });

        var usersStatusChart = document.getElementById("usersStatusChart");
        if (usersStatusChart) {
            fetch("<?php echo WEB_URL; ?>/ajax_call?page=getChartsData")
                .then(res => res.json())
                .then(data => {
                    // === USER STATUS CHART ===
                    var statusData = data.statusData;
                    var statusMap = {
                        "1": "Active",
                        "0": "Inactive",
                        null: "Unknown",
                        undefined: "Unknown"
                    };
                    var statusLabels = statusData.map(item => statusMap[item.status] || 'Unknown');
                    var statusSeries = statusData.map(item => parseInt(item.count));

                    var statusOptions = {
                        series: statusSeries,
                        chart: {
                            foreColor: "#9ba7b2",
                            type: 'pie',
                            height: 380
                        },
                        labels: statusLabels,
                        fill: {
                            type: 'gradient',
                            gradient: {
                                shade: 'dark',
                                gradientToColors: ['#ee0979', '#17ad37', '#ec6ead', '#00c6fb'],
                                shadeIntensity: 1,
                                type: 'vertical',
                                opacityFrom: 1,
                                opacityTo: 1
                            },
                        },
                        colors: ["#ff6a00", "#98ec2d", "#3494e6", "#005bea"],
                        legend: {
                            position: 'bottom',
                            show: !0
                        },
                        responsive: [{
                            breakpoint: 480,
                            options: {
                                chart: {
                                    width: 200
                                },
                                legend: {
                                    position: 'bottom'
                                }
                            }
                        }]
                    };

                    new ApexCharts(document.querySelector("#usersStatusChart"), statusOptions).render();


                    // === USER TYPE CHART ===
                    var typeData = data.typeData;
                    var typeMap = {
                        "2": "Manager",
                        "3": "Lead",
                        "4": "Client",
                        "5": "Employee",
                        "0": "Unknown",
                        null: "Unknown",
                        undefined: "Unknown"
                    };
                    var typeLabels = typeData.map(item => typeMap[item.acc_type] || 'Unknown');
                    var typeSeries = typeData.map(item => parseInt(item.count));

                    var typeOptions = {
                        series: typeSeries,
                        chart: {
                            foreColor: "#9ba7b2",
                            type: 'donut',
                            height: 380
                        },
                        labels: typeLabels,
                        fill: {
                            type: 'gradient',
                            gradient: {
                                shade: 'dark',
                                gradientToColors: ['#ee0979', '#17ad37', '#ec6ead', '#00c6fb'],
                                shadeIntensity: 1,
                                type: 'vertical',
                                opacityFrom: 1,
                                opacityTo: 1
                            },
                        },
                        colors: ["#ff6a00", "#98ec2d", "#3494e6", "#005bea"],
                        legend: {
                            position: 'bottom',
                            show: !0
                        },
                        responsive: [{
                            breakpoint: 480,
                            options: {
                                chart: {
                                    width: 200
                                },
                                legend: {
                                    position: 'bottom'
                                }
                            }
                        }]
                    };

                    new ApexCharts(document.querySelector("#usersTypeChart"), typeOptions).render();

                    // === STAFF BY DESIGNATION CHART ===
                    var staffData = data.staffData;

                    var staffLabels = staffData.map(item => item.designation || 'Unknown');
                    var staffSeries = staffData.map(item => parseInt(item.staff_count));

                    var staffOptions = {
                        series: [{
                            name: 'Staff Count',
                            data: staffSeries
                        }],
                        chart: {
                            foreColor: "#9ba7b2",
                            type: 'bar',
                            height: 380,
                            zoom: {
                                enabled: false
                            }
                        },
                        fill: {
                            type: 'gradient',
                            gradient: {
                                shade: 'dark',
                                gradientToColors: ['#ffd200', '#00c6fb', '#7928ca'],
                                shadeIntensity: 1,
                                type: 'vertical',
                                stops: [0, 100, 100, 100]
                            },
                        },
                        colors: ['#ff6a00', "#005bea", "#ff0080"],
                        xaxis: {
                            categories: staffLabels,
                            title: {
                                text: 'Designations'
                            }
                        },
                        yaxis: {
                            title: {
                                text: 'Number of Staff'
                            }
                        },
                        legend: {
                            position: 'top'
                        },
                        plotOptions: {
                            bar: {
                                horizontal: false,
                                borderRadius: 4,
                                borderRadiusApplication: 'around',
                                borderRadiusWhenStacked: 'last',
                                columnWidth: '45%',
                            }
                        },
                        stroke: {
                            show: !0,
                            width: 4,
                            colors: ["transparent"]
                        },
                        grid: {
                            show: true,
                            borderColor: 'rgba(0, 0, 0, 0.15)',
                            strokeDashArray: 4,
                        },
                        tooltip: {
                            theme: "dark",
                        },
                    };

                    new ApexCharts(document.querySelector("#staffByDesignationChart"), staffOptions).render();

                    // === DAILY EXPENSE TREND CHART ===
                    var expenseData = data.expenseData || [];
                    var expenseLabels = expenseData.map(item => item.expense_date);
                    var expenseSeries = expenseData.map(item => parseFloat(item.total_expense));

                    var expenseOptions = {
                        series: [{
                            name: 'Total Expense',
                            data: expenseSeries
                        }],
                        chart: {
                            foreColor: "#9ba7b2",
                            type: 'line',
                            height: 350,
                            zoom: {
                                enabled: false
                            },
                            dropShadow: {
                                enabled: !0,
                                top: 3,
                                left: 14,
                                blur: 4,
                                opacity: .12,
                                color: "#fc185a"
                            }
                        },
                        stroke: {
                            curve: 'smooth'
                        },
                        fill: {
                            type: 'gradient',
                            gradient: {
                                shade: 'dark',
                                gradientToColors: ['#7928ca'],
                                shadeIntensity: 1,
                                type: 'vertical',
                                opacityFrom: 1,
                                opacityTo: 1
                            },
                        },
                        colors: ["#ff0080"],
                        grid: {
                            show: true,
                            borderColor: 'rgba(0, 0, 0, 0.15)',
                            strokeDashArray: 4,
                        },
                        xaxis: {
                            categories: expenseLabels,
                            title: {
                                text: 'Date'
                            },
                            labels: {
                                rotate: -45
                            }
                        },
                        yaxis: {
                            title: {
                                text: 'Amount (PKR)'
                            }
                        },
                        markers: {
                            size: 4,
                            colors: ['#FFA726'],
                            strokeColors: '#fff',
                            strokeWidth: 2
                        },
                        tooltip: {
                            theme: "dark",
                            y: {
                                formatter: function(val) {
                                    return "Rs. " + val.toLocaleString();
                                }
                            }
                        }
                    };

                    new ApexCharts(document.querySelector("#dailyExpenseChart"), expenseOptions).render();

                    // === PROJECT STATUS CHART ===
                    var projectStatusData = data.projectStatusData || [];
                    var projectStatusLabels = projectStatusData.map(item => item.status || 'Unknown');
                    var projectStatusSeries = projectStatusData.map(item => parseInt(item.total));

                    var projectStatusOptions = {
                        series: [{
                            name: 'Projects',
                            data: projectStatusSeries
                        }],
                        chart: {
                            foreColor: "#9ba7b2",
                            type: 'bar',
                            height: 380,
                            zoom: {
                                enabled: false
                            }
                        },
                        fill: {
                            type: 'gradient',
                            gradient: {
                                shade: 'dark',
                                gradientToColors: ['#00c6fb', '#7928ca', '#ffd200'],
                                shadeIntensity: 1,
                                type: 'vertical',
                                stops: [0, 100, 100, 100]
                            },
                        },
                        colors: ["#005bea", "#ff0080", '#ff6a00'],
                        xaxis: {
                            categories: projectStatusLabels,
                            title: {
                                text: 'Project Status'
                            }
                        },
                        yaxis: {
                            title: {
                                text: 'Number of Projects'
                            }
                        },
                        legend: {
                            position: 'top'
                        },
                        plotOptions: {
                            bar: {
                                horizontal: false,
                                borderRadius: 4,
                                borderRadiusApplication: 'around',
                                borderRadiusWhenStacked: 'last',
                                columnWidth: '45%',
                            }
                        },
                        stroke: {
                            show: !0,
                            width: 4,
                            colors: ["transparent"]
                        },
                        grid: {
                            show: true,
                            borderColor: 'rgba(0, 0, 0, 0.15)',
                            strokeDashArray: 4,
                        },
                        tooltip: {
                            theme: "dark",
                        }
                    };

                    new ApexCharts(document.querySelector("#projectsStatusChart"), projectStatusOptions).render();

                    // === PROJECT TYPE CHART ===
                    var projectTypesData = data.projectTypesData || [];
                    var projectTypeLabels = projectTypesData.map(item => item.type || 'Unknown');
                    var projectTypeSeries = projectTypesData.map(item => parseInt(item.total));

                    var projectTypeOptions = {
                        series: projectTypeSeries,
                        chart: {
                            foreColor: "#9ba7b2",
                            type: 'donut',
                            height: 380
                        },
                        labels: projectTypeLabels,
                        fill: {
                            type: 'gradient',
                            gradient: {
                                shade: 'dark',
                                gradientToColors: ['#ee0979', '#17ad37', '#ec6ead', '#00c6fb'],
                                shadeIntensity: 1,
                                type: 'vertical',
                                opacityFrom: 1,
                                opacityTo: 1
                            },
                        },
                        colors: ["#ff6a00", "#98ec2d", "#3494e6", "#005bea"],
                        legend: {
                            position: 'bottom',
                            show: !0
                        },
                        responsive: [{
                            breakpoint: 480,
                            options: {
                                chart: {
                                    width: 200
                                },
                                legend: {
                                    position: 'bottom'
                                }
                            }
                        }],
                    };

                    new ApexCharts(document.querySelector("#projectsTypeChart"), projectTypeOptions).render();

                    // === MEMBER PROJECT LOAD CHART ===
                    var memberProjectsData = data.memberProjectsData || [];
                    var memberLabels = memberProjectsData.map(item => item.team_member || 'Unknown');
                    var memberSeries = memberProjectsData.map(item => parseInt(item.total_projects));

                    var memberProjectsOptions = {
                        series: [{
                            name: 'Projects Assigned',
                            data: memberSeries
                        }],
                        chart: {
                            foreColor: "#9ba7b2",
                            type: 'bar',
                            height: 380,
                            zoom: {
                                enabled: false
                            }
                        },
                        fill: {
                            type: 'gradient',
                            gradient: {
                                shade: 'dark',
                                gradientToColors: ['#7928ca', '#ffd200', '#00c6fb'],
                                shadeIntensity: 1,
                                type: 'vertical',
                                stops: [0, 100, 100, 100]
                            },
                        },
                        colors: ["#ff0080", '#ff6a00', "#005bea"],
                        xaxis: {
                            categories: memberLabels,
                            title: {
                                text: 'Team Members'
                            },
                            labels: {
                                rotate: -45
                            }
                        },
                        yaxis: {
                            title: {
                                text: 'Number of Projects'
                            }
                        },
                        plotOptions: {
                            bar: {
                                horizontal: false,
                                borderRadius: 4,
                                borderRadiusApplication: 'around',
                                borderRadiusWhenStacked: 'last',
                                columnWidth: '45%',
                            }
                        },
                        stroke: {
                            show: !0,
                            width: 4,
                            colors: ["transparent"]
                        },
                        legend: {
                            position: 'top'
                        },
                        grid: {
                            show: true,
                            borderColor: 'rgba(0, 0, 0, 0.15)',
                            strokeDashArray: 4,
                        },
                        tooltip: {
                            theme: "dark",
                        }
                    };

                    new ApexCharts(document.querySelector("#memberProjectsChart"), memberProjectsOptions).render();

                    // === TICKETS BY STATUS CHART ===
                    var ticketStatusData = data.ticketStatusData || [];
                    var ticketStatusLabels = ticketStatusData.map(item => item.status || 'Unknown');
                    var ticketStatusSeries = ticketStatusData.map(item => parseInt(item.count));

                    var ticketStatusOptions = {
                        series: [{
                            name: 'Tickets',
                            data: ticketStatusSeries
                        }],
                        chart: {
                            foreColor: "#9ba7b2",
                            type: 'bar',
                            height: 380,
                            zoom: {
                                enabled: false
                            }
                        },
                        fill: {
                            type: 'gradient',
                            gradient: {
                                shade: 'dark',
                                gradientToColors: ['#ee0979', '#00c6fb', '#7928ca'],
                                shadeIntensity: 1,
                                type: 'vertical',
                                stops: [0, 100, 100, 100]
                            },
                        },
                        colors: ['#ff6a00', "#005bea", "#ff0080"],
                        xaxis: {
                            categories: ticketStatusLabels,
                            title: {
                                text: 'Ticket Status'
                            },
                            labels: {
                                rotate: -45
                            }
                        },
                        yaxis: {
                            title: {
                                text: 'Number of Tickets'
                            }
                        },
                        plotOptions: {
                            bar: {
                                horizontal: false,
                                borderRadius: 4,
                                borderRadiusApplication: 'around',
                                borderRadiusWhenStacked: 'last',
                                columnWidth: '45%',
                            }
                        },
                        stroke: {
                            show: !0,
                            width: 4,
                            colors: ["transparent"]
                        },
                        grid: {
                            show: true,
                            borderColor: 'rgba(0, 0, 0, 0.15)',
                            strokeDashArray: 4,
                        },
                        tooltip: {
                            theme: "dark",
                        },
                        legend: {
                            position: 'top'
                        }
                    };

                    new ApexCharts(document.querySelector("#ticketsByStatus"), ticketStatusOptions).render();

                    // === TICKET BY CATEGORIES CHART ===
                    var ticketCategoryData = data.ticketsByCategoryData;

                    var statusLabels = ticketCategoryData.map(item => item.category || 'Unknown');
                    var statusSeries = ticketCategoryData.map(item => parseInt(item.count));

                    var statusOptions = {
                        series: statusSeries,
                        chart: {
                            foreColor: "#9ba7b2",
                            type: 'pie',
                            height: 380
                        },
                        labels: statusLabels,
                        fill: {
                            type: 'gradient',
                            gradient: {
                                shade: 'dark',
                                gradientToColors: ['#ee0979', '#17ad37', '#ec6ead', '#00c6fb'],
                                shadeIntensity: 1,
                                type: 'vertical',
                                opacityFrom: 1,
                                opacityTo: 1
                            },
                        },
                        colors: ["#ff6a00", "#98ec2d", "#3494e6", "#005bea"],
                        legend: {
                            position: 'bottom',
                            show: !0
                        },
                        responsive: [{
                            breakpoint: 480,
                            options: {
                                chart: {
                                    width: 200
                                },
                                legend: {
                                    position: 'bottom'
                                }
                            }
                        }]
                    };

                    new ApexCharts(document.querySelector("#ticketsByCategoriesChart"), statusOptions).render();

                    // === TICKETS CREATED OVER TIME ===
                    var ticketOverTimeData = data.ticketsCreatedOverTime || [];
                    var ticketDateLabels = ticketOverTimeData.map(item => item.created_date);
                    var ticketCountSeries = ticketOverTimeData.map(item => parseInt(item.total));

                    var ticketOverTimeOptions = {
                        series: [{
                            name: 'Tickets Created',
                            data: ticketCountSeries
                        }],
                        chart: {
                            foreColor: "#9ba7b2",
                            type: 'line',
                            height: 350,
                            zoom: {
                                enabled: false
                            },
                            dropShadow: {
                                enabled: !0,
                                top: 3,
                                left: 14,
                                blur: 4,
                                opacity: .12,
                                color: "#fc185a"
                            }
                        },
                        stroke: {
                            curve: 'smooth'
                        },
                        fill: {
                            type: 'gradient',
                            gradient: {
                                shade: 'dark',
                                gradientToColors: ['#7928ca'],
                                shadeIntensity: 1,
                                type: 'vertical',
                                opacityFrom: 1,
                                opacityTo: 1
                            },
                        },
                        colors: ["#ff0080"],
                        grid: {
                            show: true,
                            borderColor: 'rgba(0, 0, 0, 0.15)',
                            strokeDashArray: 4,
                        },
                        xaxis: {
                            categories: ticketDateLabels,
                            title: {
                                text: 'Date'
                            },
                            labels: {
                                rotate: -45
                            }
                        },
                        yaxis: {
                            title: {
                                text: 'Number of Tickets'
                            }
                        },
                        markers: {
                            size: 4,
                            colors: ['#FF5722'],
                            strokeColors: '#fff',
                            strokeWidth: 2
                        },
                        tooltip: {
                            theme: "dark",
                            y: {
                                formatter: function(val) {
                                    return val + " tickets";
                                }
                            }
                        },
                    };

                    new ApexCharts(document.querySelector("#ticketsCreatedOvertimeChart"), ticketOverTimeOptions).render();

                    // === UPCOMING EVENTS TIMELINE CHART ===
                    var eventsData = data.upcomingEventsOvertime || [];
                    var eventDateLabels = eventsData.map(item => item.due_date);
                    var eventCountSeries = eventsData.map(item => parseInt(item.total_events));

                    var upcomingEventsOptions = {
                        series: [{
                            name: 'Events Due',
                            data: eventCountSeries
                        }],
                        chart: {
                            foreColor: "#9ba7b2",
                            type: 'line',
                            height: 350,
                            zoom: {
                                enabled: false
                            },
                            dropShadow: {
                                enabled: !0,
                                top: 3,
                                left: 14,
                                blur: 4,
                                opacity: .12,
                                color: "#fc185a"
                            },
                        },
                        stroke: {
                            curve: 'smooth'
                        },
                        fill: {
                            type: 'gradient',
                            gradient: {
                                shade: 'dark',
                                gradientToColors: ['#7928ca'],
                                shadeIntensity: 1,
                                type: 'vertical',
                                opacityFrom: 1,
                                opacityTo: 1
                            },
                        },
                        colors: ["#ff0080"],
                        grid: {
                            show: true,
                            borderColor: 'rgba(0, 0, 0, 0.15)',
                            strokeDashArray: 4,
                        },
                        xaxis: {
                            categories: eventDateLabels,
                            title: {
                                text: 'Due Date'
                            },
                            labels: {
                                rotate: -45
                            }
                        },
                        yaxis: {
                            title: {
                                text: 'Number of Events'
                            }
                        },
                        markers: {
                            size: 4,
                            colors: ['#008FFB'],
                            strokeColors: '#fff',
                            strokeWidth: 2
                        },
                        tooltip: {
                            theme: "dark",
                            y: {
                                formatter: function(val) {
                                    return val + " events";
                                }
                            }
                        },
                    };

                    new ApexCharts(document.querySelector("#upcomingEventsOvertime"), upcomingEventsOptions).render();

                    // === EVENTS BY CATEGORY CHART ===
                    var eventsByCategoryData = data.eventsByCategoryData || [];
                    var eventCategoryLabels = eventsByCategoryData.map(item => item.category || 'Uncategorized');
                    var eventCategorySeries = eventsByCategoryData.map(item => parseInt(item.total));

                    var eventsByCategoryOptions = {
                        series: eventCategorySeries,
                        chart: {
                            foreColor: "#9ba7b2",
                            type: 'donut',
                            height: 380
                        },
                        labels: eventCategoryLabels,
                        fill: {
                            type: 'gradient',
                            gradient: {
                                shade: 'dark',
                                gradientToColors: ['#ee0979', '#17ad37', '#ec6ead', '#00c6fb'],
                                shadeIntensity: 1,
                                type: 'vertical',
                                opacityFrom: 1,
                                opacityTo: 1
                            },
                        },
                        colors: ["#ff6a00", "#98ec2d", "#3494e6", "#005bea"],
                        legend: {
                            position: 'bottom',
                            show: !0
                        },
                        responsive: [{
                            breakpoint: 480,
                            options: {
                                chart: {
                                    width: 200
                                },
                                legend: {
                                    position: 'bottom'
                                }
                            }
                        }]
                    };

                    new ApexCharts(document.querySelector("#eventsByCategoryChart"), eventsByCategoryOptions).render();

                    // === INVOICES BY STATUS CHART ===
                    const invoiceStatusData = data.invoiceStatusData || [];

                    const invoiceStatusMap = {
                        "3": "Pending",
                        "4": "Due",
                        "5": "Overdue",
                        "6": "Cancelled",
                        "7": "Full Paid",
                        "8": "Partial Paid",
                        "0": "Unknown"
                    };

                    const invoiceStatusLabels = invoiceStatusData.map(item => invoiceStatusMap[item.status] || 'Unknown');
                    const invoiceStatusCounts = invoiceStatusData.map(item => parseInt(item.count));

                    const invoiceStatusOptions = {
                        series: [{
                            name: 'Invoices',
                            data: invoiceStatusCounts
                        }],
                        chart: {
                            foreColor: "#9ba7b2",
                            type: 'bar',
                            height: 380,
                            zoom: {
                                enabled: false
                            }
                        },
                        fill: {
                            type: 'gradient',
                            gradient: {
                                shade: 'dark',
                                gradientToColors: ['#3494e6'],
                                shadeIntensity: 1,
                                type: 'vertical',
                                stops: [0, 100, 100, 100]
                            },
                        },
                        colors: ['#ec6ead'],
                        xaxis: {
                            categories: invoiceStatusLabels,
                            title: {
                                text: 'Invoice Status'
                            }
                        },
                        yaxis: {
                            title: {
                                text: 'Number of Invoices'
                            }
                        },
                        plotOptions: {
                            bar: {
                                horizontal: false,
                                borderRadius: 4,
                                borderRadiusApplication: 'around',
                                borderRadiusWhenStacked: 'last',
                                columnWidth: '45%',
                            }
                        },
                        stroke: {
                            show: !0,
                            width: 4,
                            colors: ["transparent"]
                        },
                        grid: {
                            show: true,
                            borderColor: 'rgba(0, 0, 0, 0.15)',
                            strokeDashArray: 4,
                        },
                        tooltip: {
                            theme: "dark",
                        },
                        legend: {
                            position: 'top'
                        }
                    };

                    new ApexCharts(document.querySelector("#invoiceStatusChart"), invoiceStatusOptions).render();
                })
                .catch(err => {
                    console.error("Chart data load error:", err);
                });
        }

        <?php
        if (1 === 2) { //
        ?>
    </script>
<?php } // 
?>