$(document).ready(function () {
    $(document).on('click', 'input', function () {
        this.focus();
        this.select();
    });
});

var basePath = '';
if (window.location.pathname.includes('/booking_accounting/')) {
    basePath = '/booking_accounting';
}

var baseUrl = `${window.location.origin}${basePath}/`;

var InvoicePrefix = {};
var User = {};

var daysNameShort = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
var daysNameFull = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
var monthsNameShort = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var monthsNameFull = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

$(document).ready(function () {
    $('.select2').select2();

    $(document).on('select2:open', (event) => {
        event.stopPropagation();
        setTimeout(() => {
            const searchField = document.querySelector('.select2-search__field');
            if (searchField) {
                searchField.focus();
            }
        }, 100);
    });

    var tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]');
    tooltipTriggerList.forEach(el => new bootstrap.Tooltip(el));
});

$.extend(true, $.fn.dataTable.defaults, {
    oLanguage: {
        sLengthMenu: "Show _MENU_ Entries",
    },
    aLengthMenu: [
        [10, 25, 50, 100, -1],
        [10, 25, 50, 100, "All"],
    ],
    iDisplayLength: 25,
    order: [],
    // bSort: false,
});

$.ajaxSetup({
    error: function (xhr, status, error) {
        var errorMessage = "An unknown error occurred.";

        if (xhr.status === 0) {
            errorMessage = "Network error: Please check your internet connection.";
        } else if (xhr.status === 404) {
            errorMessage = "Error 404: The requested resource was not found.";
        } else if (xhr.status === 500) {
            errorMessage = "Error 500: Internal server error occurred.";
        } else if (status === 'parsererror') {
            errorMessage = "Error: Failed to parse the response. The server may be returning an invalid JSON format.";
        } else {
            errorMessage = "Error " + xhr.status + ": " + error;
        }

        swal(errorMessage, {
            icon: "error",
        });

        // console.error("AJAX Error:", xhr, status, error);
    }
});

fetch(`${baseUrl}config/enum.php?json`)
    .then(res => res.json())
    .then(data => {
        InvoicePrefix = data.InvoicePrefix;
        //EventStatus = data.EventStatus;
        User = data.User;
    })
    .catch(err => console.error("Error fetching enums:", err));

var user_roles = {
    1: 'Super Admin',
    2: 'Admin',
    3: 'User'
};

var user_status = {
    0: 'DE-ACTIVE',
    1: 'ACTIVE'
};

function sAlert(title = '', text = '', icon = 'success') {
    swal({
        title: title,
        text: text,
        icon: icon,
    });
}

function sAlertDelete(reload = false) {
    if (reload) {
        swal({
            title: "Deleted!",
            text: "The item has been successfully deleted.",
            icon: "success",
        }).then(() => {
            location.reload();
        });
    } else {
        swal({
            title: "Deleted!",
            text: "The item has been successfully deleted.",
            icon: "success",
        });
    }
}

function sAlertConfirm(callback, action = '') {
    var normalizedAction = action.toLowerCase();
    var title = "Are you sure?";
    var text = "This action cannot be undone. Do you want to proceed?";

    if (normalizedAction === 'delete') {
        title = "Are you sure? Delete this record.";
        text = "Once deleted, this record cannot be recovered.";
    } else if (normalizedAction === 'update') {
        title = "Are you sure? Update this record.";
        text = "Changes will be saved permanently.";
    }

    swal({
        title: title,
        text: text,
        icon: "warning",
        buttons: true,
        dangerMode: true,
    }).then((willConfirm) => {
        if (willConfirm) {
            callback();
        }
    });
}

function sModalShow(sData, showPlace = "#modalDiv", modalName = "#modalModal") {
    $(showPlace).html("");
    $(showPlace).append(sData);
    $(modalName).modal("show");
}

function sModalHide(showPlace = "#modalDiv", modalName = "#modalModal") {
    $(modalName).modal("hide");
    $(showPlace).html("");
}

function capitalizeFirstLetter(str) {
    if (!str) return str; // handle empty string or null
    return str.charAt(0).toUpperCase() + str.slice(1);
}

function sEmail(email) {
    var emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
    return emailRegex.test(email);
}

function sCurrencySymbol(beforeSpace = true, afterSpace = true) {
    var symbol = '&#2547;';
    var currencySymbol = symbol;

    if (beforeSpace) {
        currencySymbol = '&nbsp;' + currencySymbol;
    }

    if (afterSpace) {
        currencySymbol = currencySymbol + '&nbsp;';
    }

    return currencySymbol;
}

function getCookie(name) {
    var match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
    if (match) return match[2];
}

function Permission(roleRequired = 1) {
    if (!User || !User.DesignationCode) return false;

    const userRole = User.DesignationCode.toString();
    const requiredRole = roleRequired.toString();

    return userRole === '1' || userRole === requiredRole;
}

function sDate(date, standardDateFormat = false, daysName = false) {
    var formattedDate = new Date(date);

    var day = formattedDate.getDate().toString().padStart(2, '0');
    var monthNumber = (formattedDate.getMonth() + 1).toString().padStart(2, '0');

    var dayName = daysNameShort[formattedDate.getDay()];
    var monthName = monthsNameShort[formattedDate.getMonth()];
    var year = formattedDate.getFullYear();

    if (daysName) {
        return `${dayName}, ${day}-${monthName}-${year}`;
    } else {
        return (standardDateFormat) ? `${year}-${monthNumber}-${day}` : `${day}-${monthName}-${year}`;
    }
}

function sTime(date, use12HourFormat = true, hideSecond = true) {
    var formattedDate = new Date(date);

    var hours = formattedDate.getHours();
    var minutes = formattedDate.getMinutes().toString().padStart(2, '0');
    var seconds = formattedDate.getSeconds().toString().padStart(2, '0');

    var period = '';
    if (use12HourFormat) {
        period = hours >= 12 ? ' PM' : ' AM';
        hours = hours % 12 || 12;
        hours = hours.toString().padStart(2, '0');
    } else {
        hours = hours.toString().padStart(2, '0');
    }

    return `${hours}:${minutes}${hideSecond ? '' : ':' + seconds}${period}`;
}

function CheckPrint(tableId = "dataTable") {
    var table = $('#' + tableId).DataTable();

    if (table.rows().count() === 0) {
        swal("No data available to print", {
            icon: "warning",
        });
        return false;
    }

    return true;
}

function loadSelect2(selects, dropdownParentSelector = null) {
    if (Array.isArray(selects) && selects.length > 0) {
        selects.forEach(function (select) {
            if (!$(select).hasClass("select2-hidden-accessible")) {
                let select2Options = {};
                if (dropdownParentSelector) {
                    select2Options.dropdownParent = $(dropdownParentSelector);
                }
                $(select).select2(select2Options);
            }
        });
    }
}

function sStatus(statusCode) {
    var statusClass = statusCode == 1 ? 'text-success' : 'text-danger';
    var statusText = user_status[statusCode];
    return `<div class="text-center"><span class="fw-bold ${statusClass}"> ${statusText} </span></div>`;
}

function sInt(value) {
    if (value === null || value === undefined) {
        return 0;
    }

    value = String(value).trim();

    if (!/^\d+$/.test(value)) {
        return 0;
    }
    return parseInt(value, 10);
}

function AdditionalTime(input) {
    var parts = input.split('|');
    if (parts.length !== 2) return "";

    var hours = parts[0];
    var amount = parts[1];

    return {
        hours: hours + (hours > 1 ? ' hours' : ' hour'),
        amount: amount
    };
}

function ParseAddOns(input) {
    if (!input) return [];

    return input.split(',').map(item => {
        const parts = item.split('|');
        if (parts.length !== 2) return null;

        return {
            name: parts[0].trim(),
            amount: parts[1].trim()
        };
    }).filter(item => item !== null);
}

function sTakaFormat(amount, paisa = false) {
    amount = parseFloat(amount).toFixed(2);
    let [number, decimal] = amount.split('.');
    let len = number.length;

    let formatted;
    if (len > 3) {
        let last3 = number.slice(-3);
        let restUnits = number.slice(0, -3);
        restUnits = restUnits.replace(/\B(?=(\d{2})+(?!\d))/g, ",");
        formatted = restUnits + ',' + last3;
    } else {
        formatted = number;
    }

    if (paisa) {
        return formatted + '.' + decimal;
    } else {
        return formatted;
    }
}

function sNumberToWords(number) {
    const words = {
        0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four',
        5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine',
        10: 'ten', 11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen',
        15: 'fifteen', 16: 'sixteen', 17: 'seventeen', 18: 'eighteen', 19: 'nineteen',
        20: 'twenty', 30: 'thirty', 40: 'forty', 50: 'fifty',
        60: 'sixty', 70: 'seventy', 80: 'eighty', 90: 'ninety'
    };

    const units = ['', 'hundred', 'thousand', 'lakh', 'crore'];

    if (isNaN(number)) return false;

    number = parseFloat(number).toFixed(2);
    let [intPart, decPart] = number.split('.').map(Number);

    let str = [];
    let divider = [10000000, 100000, 1000, 100, 1];
    let words_order = ['crore', 'lakh', 'thousand', 'hundred', ''];

    divider.forEach((value, idx) => {
        let quotient = Math.floor(intPart / value);
        intPart %= value;

        if (quotient) {
            if (quotient < 21) {
                str.push(words[quotient] + ' ' + words_order[idx]);
            } else {
                let tens = Math.floor(quotient / 10) * 10;
                let unit = quotient % 10;
                str.push(words[tens] + (unit ? ' ' + words[unit] : '') + ' ' + words_order[idx]);
            }
        }
    });

    let taka = str.filter(Boolean).join(' ').replace(/\s+/g, ' ').trim();

    if (!taka) {
        taka = 'zero';
    }

    let paisa = '';
    if (decPart) {
        if (decPart < 21) {
            paisa = words[decPart];
        } else {
            let tens = Math.floor(decPart / 10) * 10;
            let unit = decPart % 10;
            paisa = words[tens] + (unit ? ' ' + words[unit] : '');
        }
    }

    let result = taka.charAt(0).toUpperCase() + taka.slice(1);
    if (paisa) {
        result += ' and ' + paisa.charAt(0).toUpperCase() + paisa.slice(1) + ' Paisa';
    }
    result += ' Taka Only';

    return result;
}

var sDateTimeDefaults = {
    format: "d-M-Y",
    defaultSelect: false,
    timepicker: false,
    minDate: 0
};

function sDateTime(selector, options = {}) {
    $(selector).each(function (index) {
        var $input = $(this);

        // Skip if already initialized
        if ($input.data('sdatetime-initialized')) return;

        // Ensure the input has a unique ID
        if (!$input.attr('id')) {
            $input.attr('id', 'sdatetime_' + index);
        }

        var inputId = $input.attr('id');

        // Merge passed options with global defaults
        var mergedOptions = $.extend({}, sDateTimeDefaults, options);

        // Initialize datetimepicker with passed options
        $input.datetimepicker(mergedOptions);

        // Create calendar icon
        const $calendarIcon = $(`
            <span class="input-group-text calendar-trigger" data-target="${inputId}">
                <i class="bi bi-calendar3"></i>
            </span>
        `);

        // Insert icon after the input
        $input.after($calendarIcon);

        // Bind icon click to open calendar
        $calendarIcon.on('click', function () {
            $('#' + $(this).data('target')).datetimepicker('show');
        });

        // Mark as initialized
        $input.data('sdatetime-initialized', true);
    });
}
