<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <link rel="stylesheet" href="{{ asset('header/header.css') }}">
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="shortcut icon" href="{{ asset('images/favicon.png') }}">
    <title>Magiclink - RN</title>

    <style>
input:-webkit-autofill {
    background-color: #F5F5F5 !important;
    color: #000 !important;
    -webkit-box-shadow: 0 0 0px 1000px #F5F5F5 inset !important;
    transition: background-color 5000s ease-in-out 0s;
}
input.input-error {
  background-color: #FDE9E8 !important;
  color: #EF6966 !important;
  border: 2px solid #EF6966 !important;
}

/* Autofill override */
input.input-error:-webkit-autofill {
  -webkit-box-shadow: 0 0 0 1000px #FDE9E8 inset !important;
  -webkit-text-fill-color: #EF6966 !important;
  border: 2px solid #EF6966 !important;
}



        .shareUPCDropdown {
            height: 150px;
            overflow: auto;
            width: auto;
            scrollbar-width: thin !important;
            border-radius: 0;
            padding: 0;

        }
        body {
            font-family: Roboto, RobotoDraft, Helvetica, Arial, sans-serif !important;
            background-color: #efebf8;
        }

        .pad {
            padding: 5px 20px;
        }

        a {
            // text-decoration: none;
        }

        p {
            text-align: justify;
            font-size: 15px;
            font-family: system-ui
        }

        input:focus-visible {
            border: none;
            outline: none;
        }

        input[type="radio"] {
            width: 18px;
            height: 18px;
            filter: hue-rotate(45deg);
            cursor: pointer;
        }

        .uncheck_btn {
            float: right;
            margin: 20px 0;
            background: none;
            border: none;
            padding: 10px;
            border-radius: 7px;
            display: none;
        }

        .uncheck_btn:hover {
            background: #f0f0f0;
        }

        .success {
            background-color: #5a39b6;
            color: #fff;
            padding: 10px 25px;
            border-radius: 5px;
            border: none;
            filter: drop-shadow(0px 2px 2px black);
        }

        .top_bg {
            /* background-image: url('https://magiclink.rn-test.com/images/banner.png');
            background-size: cover;
            max-height: 23vw;
            max-width: 90vw;
            height: 160px;
            width: 640px; */
        }

        .cont1 {
            background-color: #fff;
            border: 1px solid #dfdfdf;
            margin-top: 12px;
            border-top: 11px solid #1345AC;
        }

        .cont2 {
            background-color: #fff;
            border: 1px solid #dfdfdf;
            margin-top: 12px;
            overflow: hidden;
        }

  .btn {
    background-color: #1345AC;
    color: #fff;
    width: 130px;
    height: 50px;
    border: none;
    cursor: pointer;
    font-weight: bold;
  }

  .btn:hover {
    background-color: #ffffff;
    color: #1345AC;
    border: 2px solid #1345AC;
  }

        select {
            cursor: pointer !important;
        }

        #form3,
        #form2,
        #form2nd,
        #form3rd,
        #success {
            display: none;
        }

        .headings p {
            margin: auto 0;
            font-weight: 400;
        }

        .headings div {
            height: 40px;
        }


        .badge_right_menu {
            color: white;
            transform: scale(1.8);
            line-height: normal;
            width: 13rem;
            margin-left: 34px;
        }

        .badge_right_menu ion-icon {
            cursor: pointer;
        }

        .top_user_inert {
            display: none;
            position: fixed;
            background-color: #fff;
            border: 1px solid #ccc;
            padding: 22px;
            /* max-width: 400px; */
            box-shadow: 0px 5px 10px rgba(0, 0, 0, 0.2);
            z-index: 99;
            /* width: max-content; */
            width: 25rem;
            border-radius: 8px;
            right: 2.5rem;
            top: 4.5rem;
        }

        .top_user_open {
            display: block;
            animation: slideDown 0.3s ease-in-out;
        }

        .top_user_inert .user_head {
            display: flex;
        }

        .top_user_inert .user_head .logout_head {
            width: 20%;
            display: flex;
            justify-content: end;
        }

        .top_user_inert .user_head .logout_head ion-icon {
            height: 24px;
            width: 24px;
            cursor: pointer;
        }

        .top_user_inert .split_head {
            // width: 80%;
            width: 100%;
            display: flex;
            height: 70px;
        }

        .top_user_inert .user_head .split_head div {
            /*            width: 19%;*/
            margin-right: 14px;
            position: relative;
        }

        .top_user_inert .user_head .split_head div img {
            width: 100% !important;
        }

        .top_user_inert .user_head .split_head div p {
            margin: 1px;
            font-weight: 700;
            margin-bottom: 0;
        }

        .top_user_inert .user_head .split_head div .unqiue {
            font-size: 11px;
            color: #7e7e7e;
        }

        .top_user_inert .user_head .split_head div .sub_time {
            font-size: 11px;
            background: #0080002e;
            padding: 2px 9px;
            border-radius: 31px;
            color: green;
            width: max-content;
        }

        .top_user_inert .user_body {
            padding: 1.5rem 0rem 1rem 0;
            position: relative;
            /* height: 200px;
            overflow-x: auto; */
        }

        .top_user_inert .user_body .out_of_card_first {
            padding: 1rem;
            border: 1px solid #dfdfdf;
            border-radius: 8px;
            display: flex;
            justify-content: space-between;
        }

        .top_user_inert .user_body .out_of_card_first ion-icon {
            /*            transform: scale(2);*/
        }

        .top_user_inert .user_head .split_head div .status_res {
            height: 14px;
            width: 14px;
            background: green;
            border: 2px solid #fff;
            border-radius: 50%;
            position: absolute;
            right: -8px;
            bottom: 5px;
            /* cursor: pointer; */
        }

        /* .top_user_inert .user_head .split_head div .status_res:hover {
        background-color: #bbb !important;
    } */

        /* .top_user_inert .user_head .split_head div .status_res:hover::before {
        content: "^";
        display: flex;
        align-items: center;
        justify-content: center;
        margin: -10px 0 0;
        transform: rotate(180deg);
    } */

        .top_user_inert .user_head .split_head .popup_status {
            position: absolute;
            height: max-content;
            width: 5rem;
            background: #fff;
            border-radius: 4px;
            top: 74px;
            left: 71px;
            z-index: 9999;
            border: 1px solid #ddd;
            display: none;
            box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
        }

        .top_user_inert .user_head .split_head .popup_status p {
            font-size: small;
            font-weight: 400;
            text-align: center;
            display: flex;
            justify-content: space-around;
            padding: 4px;
            margin: 0;
            cursor: pointer;
        }

        .top_user_inert .user_head .split_head .popup_status p:hover {
            background-color: #ddd;
        }

        .top_user_inert .user_head .split_head div .status_res div {
            border: 3px solid #fff;
            border-radius: 50%;
            position: relative;
            right: -2px;
            bottom: -2px;
            display: none;
        }

        .top_user_inert .user_body .dont_dis_card_sec {
            padding: 1rem;
            border: 1px solid #dfdfdf;
            border-radius: 8px;
            display: flex;
            justify-content: space-between;
            margin-top: 8px;
        }

        .top_user_inert .user_body .dont_dis_card_sec .moon_circle_in {
            background: #ff9a03;
            padding: 2px;
            border: 2px solid #ff9a03;
            display: flex;
            align-items: center;
            border-radius: 50%;
            height: 26px;
            width: 26px;
            position: relative;
        }

        /*    .top_user_inert .user_body .dont_dis_card_sec .moon_circle_in div {
            border-right: 2px solid;
            height: 1.3rem;
            transform: rotate(-45deg);
            position: absolute;
            left: 10px;
            border-color: #000000;
            top: 1px;
        }*/
        .top_user_inert .user_body .dont_dis_card_sec .moon_circle_in span {
            background: white;
            width: 2px;
            height: 21px;
            transform: rotate(-45deg);
            position: absolute;
            left: 9px;
            top: 1px;
            border: 1px solid #ff9a03;
            padding-right: 2px;
            display: none;
            border-bottom: none;
            border-top: none;
            border-radius: 11px;
        }

        .top_user_inert .option_out {
            display: flex;
            justify-content: end;
        }

        .top_user_inert .option_out .logout_outline {
            display: flex;
            align-items: center;
            gap: 2px;
            cursor: pointer;
        }

        .top_user_inert .option_out .logout_outline ion-icon {
            color: black;
            transform: scale(1.2);
        }

        .top_user_inert .option_out .logout_outline span {
            color: black;
        }

        .top_user_inert .user_body .schedule_timeset {
            padding: 1rem;
            border: 1px solid #dfdfdf;
            border-radius: 8px;
            display: flex;
            justify-content: space-between;
            margin-top: 8px;
        }

        .top_user_inert .user_body .schedule_timeset .moon_circle_in {
            background: #ff9a03;
            padding: 3px;
            border: 2px solid #ff9a03;
            display: flex;
            align-items: center;
            border-radius: 50%;
            height: 26px;
            width: 26px;
            justify-content: center;
            position: relative;
        }

        .top_user_inert .user_body .schedule_timeset .moon_circle_in #jUF221fvd {
            height: 8px;
            width: 8px;
            position: absolute;
            background: #ff9a03;
            display: flex;
            justify-content: center;
            border-radius: 50%;
            align-items: center;
            color: white;
            top: 1px;
            left: 13px;
            font-size: 8px;
        }

        .top_user_inert .user_body .schedule_timeset .moon_circle_in img {
            width: 18px;
            height: 24px;
        }

        .top_user_inert .user_body .schedule_timeset input {
            background: #cfcfcf47;
            border: none;
            border-radius: 7px;
            width: 44%;
            color: #212121;
            font-size: small;
            padding: 3px;
            font-size: 12px;
        }

        .top_user_inert .user_body .schedule_timeset span {
            font-size: 12px;
            padding: 0 2px;
        }

        /* switch */
        .user_head_uni_switch .bell_switch {
            position: relative;
            display: inline-block;
            width: 36px;
            /*            height: 22px;*/
            height: 29px;
        }

        .user_head_uni_switch .bell_switch input {
            display: none;
        }

        .user_head_uni_switch .bell_switch label {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #ccc;
            border-radius: 34px;
            cursor: pointer;
            transition: background-color 0.3s;
            margin-bottom: 0.5rem;
        }

        .user_head_uni_switch .bell_switch input:checked+label {
            background-color: #2196F3;
        }

        .user_head_uni_switch .bell_switch label:before {
            position: absolute;
            content: "";
            height: 13px;
            width: 13px;
            left: 4px;
            bottom: 4px;
            background-color: white;
            border-radius: 50%;
            transition: transform 0.3s;
        }

        .user_head_uni_switch .bell_switch input:checked+label:before {
            transform: translateX(16px);
        }

        .top_user_inert .user_head .split_head div .sub_time {
            display: block;
        }

        .top_user_inert .user_head .split_head div .sub_time_do {
            // padding: 2px 9px;
            // border-radius: 31px;
            // font-size: 11px;
            // background: #ff9a033d;
            // color: #ff9a03;
            // width: max-content;
            display: none;
        }

        .top_user_inert .user_head .split_head div .sub_time_out {
            // padding: 2px 9px;
            // border-radius: 31px;
            // font-size: 11px;
            // background: #ffc4c4;
            // color: #ff4e4e;
            // width: max-content;
            display: none;
        }

        .admin_box {
            display: none;
        }

        .shareUPCDropdown {
            display: block;
            background: #F5F5F5;
                width: 250px !important;
        }

        .shareUPCDropdown .dropdown-item {
  height: 50px;
  padding: 14px 40px 14px 20px;
  background: #F5F5F5;
  font-family: Arial;
  font-size: 14px;
  border: none;
  box-sizing: border-box;
  appearance: none;
  -webkit-appearance: none;
  -moz-appearance: none;
  cursor: pointer;
  width:100%;
        }

        .shareUPCDropdown .dropdown-item:hover {
             background: #fafafa !important;
        }

        .shareUPCDropdown .dropdown-item:last-child {
  padding: 14px 40px 14px 20px;
            border-bottom: 0;
        }
    </style>
    <style>
        .error-message {
            color: red;
            font-size: 14px;
        }
    </style>
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <script>



document.addEventListener("DOMContentLoaded", function () {
    const backLink = document.getElementById("backToFormLink");
    if (backLink) {
        backLink.addEventListener("click", function (e) {
            e.preventDefault();

            fetch("{{ route('clear.flash') }}", {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': '{{ csrf_token() }}',
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({})
            })
            .then(response => response.json())
            .then(data => {
                if(data.status === 'cleared') {
                    // Redirect or reload the page without flash message
                    window.location.href = "{{ url()->current() }}";
                }
            })
            .catch(err => {
                console.error('Error clearing session:', err);
                // fallback reload anyway
                window.location.href = "{{ url()->current() }}";
            });
        });
    }
});



       document.addEventListener('DOMContentLoaded', () => {
    const form = document.getElementById('myForm');

    form.addEventListener('submit', async (event) => {
        event.preventDefault(); // Stop the form from submitting immediately

        const isValid = await success(); // Run your async validation
//alert(isValid);
        if (isValid) {
            form.submit();
        }

    })
});
       
async function success() {
    const containers = document.querySelectorAll('#main-container .container');
    const userId = $('input[name="userid"]').val();

    let allValid = true;
    let allISRCs = [];
    for (const container of containers) {
        const id = container.dataset.id;
        const upcInput = document.getElementById(`upcInput-${id}`);
        const selectedUPC = upcInput.value.trim();
        const isrcinput = document.getElementById(`isrc-${id}`);
        const selectedISRC = isrcinput?.textContent?.trim() || '';

        // === UPC EMPTY CHECK ===
        if (!selectedUPC) {
            upcInput.style.background = "#FDE9E8";
            upcInput.style.border = "2px solid #EF6966";
            upcInput.style.color = "#EF6966";
            $('#reason' + id).css('display', 'block');
            $('#reasontext' + id).text('Please fill in this field.');
            $('#optionsContainer' + id).css('display', 'none');
            allValid = false;
        } else {
            const validationResult = await validateUPC(selectedUPC, userId);

            if (!validationResult.isValid && validationResult.reason === 'not_found') {
                upcInput.style.background = "#FDE9E8";
                upcInput.style.border = "2px solid #EF6966";
                upcInput.style.color = "#EF6966";
                $('#reason' + id).css('display', 'block');
                $('#reasontext' + id).text('Invalid UPC. Please select a valid UPC.');
                $('#optionsContainer' + id).css('display', 'none');
                allValid = false;
            } else {
                upcInput.style.background = "#F5F5F5";
                upcInput.style.border = "none";
                upcInput.style.color = "black";
                $('#reason' + id).css('display', 'none');
            }
        }

        allISRCs.push(selectedISRC);
        
        // === NEW SHARE VALIDATION ===
        const shareValid = await isAtLeastOneNewShareFilled(id);
        if (shareValid === null) {
            $('#share' + id).css('display', 'block');
            $(`#sharetext${id}`).text('Please add at least one new share.');
            allValid = false;
        } else if (!shareValid) {
            allValid = false;
        }
    }



    const isrcCounts = {};
allISRCs.forEach(isrc => {
    if (isrc) {
        isrcCounts[isrc] = (isrcCounts[isrc] || 0) + 1;
    }
});

let duplicateFound = false;

containers.forEach(container => {
    const id = container.dataset.id;
    const isrcDiv = document.getElementById(`isrc-${id}`);
    const selectedISRC = isrcDiv?.textContent?.trim() || '';

    if (isrcCounts[selectedISRC] > 1) {
        // Show inline error message
        $(`#isrcreason${id}`).css('display', 'block');
        $(`#isrcresontext${id}`).text('Duplicate ISRCs are not allowed. Please select a different ISRC.');
        duplicateFound = true;
    }
});

if (duplicateFound) {
    return false;
}
    

    return allValid;
}

async function isAtLeastOneNewShareFilled(containerId) {
    const inputs = document.querySelectorAll(`#additional-inputs-${containerId} .coverform_input${containerId}`);
    if (inputs.length === 0) return null;

    $(`#shareUPCDropdown${containerId}`).css('display','none');
    let totalPercent = 0;
    let hasFilledGroup = true;

    for (let index = 0; index < inputs.length; index++) {
        const group = inputs[index];
        const textInputs = group.querySelectorAll('input');
        const [userIdInput, userNameInput, percentInput] = textInputs;

        const isUserIdFilled = userIdInput.value.trim() !== '';
        const isUserNameFilled = userNameInput.value.trim() !== '';
        const isPercentFilled = percentInput.value.trim() !== '';

        // const percentValue = parseFloat(percentInput.value) || 0;
        // totalPercent += percentValue;



        // const percentValue = parseFloat(percentInput.value) || 0;
        // totalPercent += percentValue;

        const percentStr = percentInput.value.trim();
        const percentValue = parseFloat(percentStr);
        const isPercentValidNumber = !isNaN(percentValue) && isFinite(percentValue);

        if (isPercentFilled && isPercentValidNumber) {
            totalPercent += percentValue;
        }

//console.log('index',index);

        $(`#newreason${index+1}${containerId}`).hide();
        $(`#usernewreason${index+1}${containerId}`).hide();
        $(`#pernewreason${index+1}${containerId}`).hide();

        if (!isUserIdFilled) {
            userIdInput.style.background = "#FDE9E8";
            userIdInput.style.border = "2px solid #EF6966";
            userIdInput.style.color = "#EF6966";
            $(`#newreason${index+1}${containerId}`).show().text('Please fill in this field.');
            //$(`#searchIcon${index+1}${containerId}`).css('right','22px');
            hasFilledGroup = false;
        } else {
            userIdInput.style.background = "#F5F5F5";
            userIdInput.style.border = "none";
            userIdInput.style.color = "black";
        }

        if (!isUserNameFilled) {
            userNameInput.style.background = "#FDE9E8";
            userNameInput.style.border = "2px solid #EF6966";
            userNameInput.style.color = "#EF6966";
            $(`#usernewreason${index+1}${containerId}`).show().text('Please fill in this field.');
            hasFilledGroup =  false;
        } else {
            userNameInput.classList.remove('input-error');
            userNameInput.style.background = "#F5F5F5";
            userNameInput.style.border = "none";
            userNameInput.style.color = "black";
        }

        if (!isPercentFilled || !isPercentValidNumber) {
            percentInput.style.background = "#FDE9E8";
            percentInput.style.border = "2px solid #EF6966";
            percentInput.style.color = "#EF6966";
            if(!isPercentFilled){
                $(`#pernewreason${index+1}${containerId}`).show().text('Please fill in this field.');

               
            }else{
                $(`#pernewreason${index+1}${containerId}`).show().text('Please enter a valid number.');
            }
           return false;
        } else {
            percentInput.style.background = "#F5F5F5";
            percentInput.style.border = "none";
            percentInput.style.color = "black";
        }

        if (userIdInput.value || userNameInput.value) {
            try {
                const response = await ajaxPost("{{ route('getupcDetails11') }}", {
                    query: userIdInput.value,
                    query2: userNameInput.value
                });

                if (response.errorMessage) {
        window.location.reload();
        return false; 
    }

            } catch (error) {
                console.error("AJAX error:", error);
                return false;
            }
        }

        // // At least one fully filled group
        // if (isUserIdFilled && isUserNameFilled && isPercentFilled) {
        //     hasFilledGroup = true;
        // }
    }

   // alert(`Total Percent: ${totalPercent}`);
    if (totalPercent != 100) {
   
        $(`#newshare${containerId}`).show().text('Entered new share percentages do not total 100%'); 
console.log(inputs);

        for (let index = 0; index < inputs.length; index++) {
            const group = inputs[index];
            console.log(group);
            const percentInput = group.querySelectorAll('input')[2]; // 3rd input
            console.log(percentInput);
            percentInput.style.background = "#FDE9E8";
            percentInput.style.border = "2px solid #EF6966";
            percentInput.style.color = "#EF6966";
        }

        return false;
    }

    return hasFilledGroup;
}
function ajaxPost(url, data) {
    return new Promise((resolve, reject) => {
        $.ajax({
            type: "POST",
            url: url,
            headers: {
                'X-CSRF-TOKEN': '{{ csrf_token() }}',
                'X-Requested-With': 'XMLHttpRequest'
            },
            data: data,
            success: resolve,
            error: reject
        });
    });
}



        function validateUPC(selectedUPC, userId) {
    return new Promise((resolve, reject) => {
        $.ajax({
            type: "POST",
            url: "{{ route('getupcDetails1') }}",
            headers: {
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            },
            data: {
                query: 'two',
                upc: selectedUPC,
                user_id: userId
            },
            success: function (response) {


                if (!response.upcs || response.upcs.length === 0) {
                    resolve({ isValid: false, reason: 'not_found' });
                }  else {
                    resolve({ isValid: true });
                }

                // else if (response.validation === 'false') {
                //     if(response.validation == 'redCrAbuseCount'){
                //         resolve({ isValid: false, reason: 'redCrAbuseCount' });
                //     }else{
                //         resolve({ isValid: false, reason: 'redCopyrightCount' });
                //     }

                // }
                // if (response.upcs && response.upcs.length > 0 && response.validation == 'true') {
                //     resolve(true);
                // } else {
                //     resolve(false);
                // }
            },
            error: function () {
                reject(false); // or handle error case differently
            }
        });
    });
}

    </script>

</head>

<body>

    <div class="main_container">
        <div class="header_container">
            <div>
                <div
                    style="display:none;position: fixed;right: 4%;bottom: 12%;z-index: 11;height:70%;width:18%;background-color:#fff;border-radius: 12px;box-shadow: 0px 0px 9px 3px #dddddd42;">
                    <div
                        style="height: 4rem;background-color:#124dfe;border-radius: 12px 12px 0 0;display: flex;padding-left: 12px;align-items: center;justify-content: space-between;">
                        <div style="background: #fff;padding: 10px;display: flex;border-radius: 50%;">
                            <img src="{{ asset('images/robot.svg') }}" alt="logo"
                                style="height: 24px;width: 24px;" />
                        </div>
                    </div>
                    <div>
                        bottom
                    </div>
                </div>

                <div class="s_navigation">
                    <div class="select-none p-4">
                        <a href="" id="max-logo" class="flex items-center gap-2">
                            <img src="https://magiclink.rn-test.com/images/rn-logo-white.svg" alt="routenote-logo">
                            <div class="w-full flex flex-col items-end">
                                <h3 class="font-medium text-xl font-sans !text-white" style="font-family: Arial;">Smart Hub</h3>
                                <span class="font-sans text-[9px] font-medium text-red-500" style="font-family: Arial;">Powered by AI</span>
                            </div>
                        </a>
                        <div class="headflex hidden" id="min-logo">
                            <a href="">
                                <img src="https://magiclink.rn-test.com/images/rn-logo-white.svg" alt="routenote-logo" style="height: 52px;">
                            </a>
                        </div>
                    </div>

                    <div class="flex notification">
                        <div class="notification2">
                            <i class="fa fa-bell bell-img" style="font-size:24px;color:white;" id="bellon_1"></i>
                            <i class="fa fa-bell-slash fa-ban" id="belloff_1"
                                style="font-size:24px;color:white; display:none;"></i>
                            <!--span class="badge" id="badge"><?php //echo count(json_decode($fetc_value));
                            ?></span-->

                            <div class="dropdown-content1 notificationflow" id="dropdownContent">
                                <div class="notify_head">
                                    <h5 class="noti_title" id="noti_title" style="display:none;">Notifications</h5>
                                    <h5 class="noti_title" id="noti_title_" style="display:none;">No notification
                                        found..!</h5>
                                    <div class="close-icon"></div>
                                </div>
                            </div>
                        </div>

                        <div class="top_user_inert" id="user_dropdownContent">
                            <div class="user_head">
                                <div class="split_head">
                                    <div style="width: 22%;"><img src="{{ asset('images/user.svg') }}"
                                            style="width: 18%;">
                                        <div class="status_res" id="status_res" onclick="status_mal_change()">
                                            <div id="offline_status"></div>
                                        </div>
                                    </div>

                                    <div class="popup_status">
                                        <p onclick="getstatus(this)" data-value="0"><span>
                                                <ion-icon name="checkmark-outline" id="Active0"></ion-icon>
                                            </span>Active</p>
                                        <p onclick="getstatus(this)" data-value="1"><span>
                                                <ion-icon name="checkmark-outline" id="Away1"
                                                    style="visibility: hidden;">
                                                </ion-icon>
                                            </span>Away</p>
                                    </div>
                                    <div>
                                        <p><?php //echo ucfirst($_SESSION["User"]);
                                        ?></p>
                                        <div class="unqiue">@<?php //echo ucfirst($_SESSION["Username"]);
                                        ?></div>
                                        <div style="display:flex;">

                                            <div class="sub_time">Available until <span id="user_time_zon"></span></div>
                                            <div class="sub_time_out"><img
                                                    src="{{ asset('images/notifications-off-circle-outline.svg') }}"
                                                    style="width: 24px !important;height: 32px;margin-right: -10px;">
                                            </div>
                                            <div class="sub_time_do"><img
                                                    src="{{ asset('images/dash-circle-fill.svg') }}"
                                                    style="width: 20.3px!important;height: 26px;margin-top: 2.5px;">
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="logout_head">
                                    <ion-icon name="log-out-outline"
                                        Onclick="window.onbeforeunload = null;window.location.href = '<?php //echo $site_url;
                                        ?>/login?action=login&user=<?php //echo $_SESSION["User_id"];
                                        ?>'">
                                    </ion-icon>
                                </div>
                            </div>
                            <div class="user_body">
                                <div class="out_of_card_first">
                                    <!-- <ion-icon id="notify_on_outline" name="notifications-circle-outline" style="display: none;"></ion-icon> -->
                                    <!-- <ion-icon id="notify_off_outline" name="notifications-off-circle-outline" ></ion-icon> -->
                                    <img src="{{ asset('images/notifications-circle-outline.svg') }}"
                                        id="notify_on_outline" style="width: 32px;height: 32px;">

                                    <img src="{{ asset('images/notifications-off-circle-outline.svg') }}"
                                        id="notify_off_outline" style="display: none;width: 32px;height: 32px;">
                                    <div style="width: 71%;margin-top: -7px;">
                                        <div style="font-weight: 600;">Out of office</div>
                                        <div style="font-size: small;">Mute notifications and unassign new messages
                                        </div>
                                    </div>
                                    <div class="user_head_uni_switch">
                                        <div class="bell_switch">
                                            <input type="checkbox" id="autosuggest_0" onclick="bell_circle(this)"
                                                <?php //if( $sql_status_check_result['schedule_act'] == 1) {echo "disabled";}
                                                ?>>
                                            <label for="autosuggest_0"></label>
                                        </div>
                                    </div>
                                </div>
                                <div class="dont_dis_card_sec">
                                    <div style="display: flex;gap: 17px;">
                                        <div class="moon_circle_in">
                                            <!-- <box-icon name='moon' style="display: none;"></box-icon> -->
                                            <box-icon name='moon' type='solid' color="#fff"
                                                id="JHTVhfgd56"></box-icon>
                                            <span id="vgFCTUT34"></span>
                                            <!-- <div><span></span></div> -->
                                        </div>
                                        <div style="margin-top: -7px;">
                                            <div style="font-weight: 600;">Do not disturb</div>
                                            <div style="font-size: small;">Mute notifications</div>
                                        </div>
                                    </div>
                                    <div class="user_head_uni_switch">
                                        <div class="bell_switch">
                                            <input type="checkbox" id="autosuggest_1" onclick="moon_circle(this)"
                                                <?php //if( $sql_status_check_result['schedule_act'] == 1) {echo "disabled";}
                                                ?>>
                                            <label for="autosuggest_1"></label>
                                        </div>
                                    </div>
                                </div>
                                <div class="schedule_timeset">
                                    <div style="display: flex;justify-content: space-between;width: 100%;">
                                        <div style="display: flex;gap: 17px;width: 80%;">
                                            <div class="moon_circle_in"><img
                                                    src="{{ asset('images/time-outline.svg') }}" /><span
                                                    id="jUF221fvd">z</span></div>
                                            <div style="width: inherit;">
                                                <div style="font-weight: 600;">Schedule</div>
                                                <div style="width: max-content;display: initial;">
                                                    <input type="time" id="starttime_sche" name="time"
                                                        value="<?php //echo $sche_HJjk2[0];
                                                        ?>">
                                                    <span> to </span>
                                                    <input type="time" id="endtime_sche" name="time"
                                                        value="<?php //echo $sche_HJjk2[1];
                                                        ?>">
                                                </div>
                                            </div>
                                        </div>
                                        <div class="user_head_uni_switch">
                                            <div class="bell_switch">
                                                <input type="checkbox" id="autosuggest_2"
                                                    onclick="sche_circle(this)">
                                                <label for="autosuggest_2"></label>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                        </div>
                        <div class="badge_right_menu flex items-center justify-center" id="badge_right_menu" style="position: relative;"><span
                                style="font-size: 9px;    font-family: Arial;">
                                {{ $users->name }}
                            </span>&nbsp;
                            <a href="{{ route('formlogout', ['key' => $key, 'name' => 'revenueshareforms']) }}"><svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" class="cursor-pointer" style="fill: rgba(255, 255, 255, 1);transform: rotate(180deg);msFilter:progid:DXImageTransform.Microsoft.BasicImage(rotation=2);">
                        <path d="M16 13v-2H7V8l-5 4 5 4v-3z"></path>
                        <path d="M20 3h-9c-1.103 0-2 .897-2 2v4h2V5h9v14h-9v-4H9v4c0 1.103.897 2 2 2h9c1.103 0 2-.897 2-2V5c0-1.103-.897-2-2-2z">
                        </path>
                    </svg></a>
                        </div>

                    </div>


                </div>

            </div>
        </div>

    </div>

    <div class="full_container_start" style="width: 100%;overflow: scroll;height: 80vh;">
        <div style="">
            <div style="">
                @if (session('success'))
                    <div class="top_bg">
                    <img style="width:100%" src="{{ asset('images/banner.png') }}" >
                    </div>

                    <div style="
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;padding-top:24px;">

                        <br>
                        <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"  height="83px" width="1038.99px">
    <title>Notification/Success</title>
    <g id="RouteNote-UI-Kit" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
        <g id="RouteNote-UI-KIt" transform="translate(-146, -11988)">
            <g id="06.-Notifications-🚦" transform="translate(87, 11833)">
                <g id="Alerts" transform="translate(59, 117.2578)">
                    <g id="Notification/Success" transform="translate(0, 38)">
                        <rect id="Rectangle" stroke="#75DD7D" fill="#EBFAEC" x="0.5" y="0.5" width="1019" height="82"></rect>
                        <text id="Lorem-ipsum-dolor-si" font-family="ArialMT, Arial" font-size="14" font-weight="normal" line-spacing="22" fill="#000000">
                            <tspan x="18.9893617" y="55">Thanks for submitting your revenue sharing request! This has been received successfully and you will be contacted via email soon with any updates. </tspan>
                        </text>
                        <text id="Success-Heading!" font-family="Arial-BoldMT, Arial" font-size="16" font-weight="bold" line-spacing="21" fill="#75DD7D">
                            <tspan x="18.0851064" y="30.1648352">Success!</tspan>
                        </text>
                    </g>
                </g>
            </g>
        </g>
    </g>
</svg>
                        <!--div style="left: 287px;position: relative;">
                            <img src="{{ asset('images/tick.png') }}" style="width: 81px; height: 81px;">
                        </div>

                        <h2 style="font-weight: 600;position: relative;font-size: x-large;"> {{ session('success') }}</h2> -->
                        <div>
                            <br>

                            @elseif (session('error'))
                    <div class="top_bg">
                    <img style="width:100%" src="{{ asset('images/banner.png') }}" >
                    </div>

                    <div style="
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;padding-top:24px;">

                        <br>
      
<!-- Container div to simulate the SVG box -->
<div style="
    position: relative;
    width: 1039px;
    height: 86px;
    border: 1px solid #FDA400;
    background-color: #FFF2D9;
    box-sizing: border-box;
    font-family: Arial, sans-serif;
    padding: 15px 20px;
    color: #000000;
    ">

    <!-- Warning heading -->
    <div style="
        font-weight: bold;
        font-size: 16px;
        color: #FDA400;
        margin-bottom: 8px;
        ">
        Warning Heading!
    </div>

    <!-- Warning message with inline link -->
    <div style="font-size: 14px; line-height: 22px;">
        There was a problem, please ensure all details are correct and try again&nbsp;
        <a href="#" id="backToFormLink" style="
        font-weight: 600;
            color: #1354AC;
            text-decoration: underline;
            cursor: pointer;
            ">
            Go back to the form
        </a>
    </div>

</div>

                        <!--div style="left: 287px;position: relative;">
                            <img src="{{ asset('images/tick.png') }}" style="width: 81px; height: 81px;">
                        </div>

                        <h2 style="font-weight: 600;position: relative;font-size: x-large;"> {{ session('success') }}</h2> -->
                        <div>
                            <br>

                        @elseif($data == '0')
                            <div class="top_bg">
                            <img style="width:100%"  src="{{ asset('images/banner.png') }}" >
                            </div>

                            <div style="
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;padding-top:24px;">
                                <br>
                                <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"  height="83px" width="1038.99px">
    <title>Notification/Success</title>
    <g id="RouteNote-UI-Kit" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
        <g id="RouteNote-UI-KIt" transform="translate(-146, -11988)">
            <g id="06.-Notifications-🚦" transform="translate(87, 11833)">
                <g id="Alerts" transform="translate(59, 117.2578)">
                    <g id="Notification/Success" transform="translate(0, 38)">
                        <rect id="Rectangle" stroke="#75DD7D" fill="#EBFAEC" x="0.5" y="0.5" width="1019" height="82"></rect>
                        <text id="Lorem-ipsum-dolor-si" font-family="ArialMT, Arial" font-size="14" font-weight="normal" line-spacing="22" fill="#000000">
                            <tspan x="18.9893617" y="55">Thanks for submitting your revenue sharing request! This has been received successfully and you will be contacted via email soon with any updates. </tspan>
                        </text>
                        <text id="Success-Heading!" font-family="Arial-BoldMT, Arial" font-size="16" font-weight="bold" line-spacing="21" fill="#75DD7D">
                            <tspan x="18.0851064" y="30.1648352">Success!</tspan>
                        </text>
                    </g>
                </g>
            </g>
        </g>
    </g>
</svg>
                                <!-- <div style="left: 287px;position: relative;">
                                    <img src="{{ asset('images/tick.png') }}" style="width: 81px; height: 81px;">
                                </div>

                                <h2 class="" style="font-weight: 600;position: relative;font-size: x-large;"> Thanks for submitting your revenue sharing request! This has been received successfully and you will be contacted via email soon with any updates.
                                </h2> -->
                                <div>
                                    <br>
                                @else
                                    <div class="top_bg">
                                    <img style="width:100%"  src="{{ asset('images/banner.png') }}" >
                                    </div>
                                    <form id="myForm" action="{{ route('revenueformsubmit') }}" method="GET" style="align-content: baseline;
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;">
                                        @csrf
                                        <div id="form1" style="width: 1019px;">
                                            <div class="cont1 space-y-2">
                                                <div class="pad space-y-4">
                                                    <h1 class="text-2xl font-semibold mt-3" style="font-family: Arial, sans-serif; font-size: 24px; font-weight: bold; color: #1345AC;">Revenue Share Request Form
                                                    </h1>
                                                    <p style="font-family: Arial; font-size: 14px;">

                                                    The percentage share of your release will depend on the distribution plan you have selected. For free releases, the account holder will automatically get 85% of total earnings, while Premium releases will get 100%.
 <br> <br>
 Account holders are able to split their percentages between multiple parties using this revenue share request form.
 <br> <br>
 Revenue shares submitted before the 20th of each month will be applied to the following month. Revenue shares submitted on or after the 20th will be applied in two months time.  <br>
 For example, a share submitted on 17th January will be in place for February earnings run, whereas a share submitted on 25th January will be in place for March earnings run.
                                                    </p>
                                                </div>


                                                <hr>
                                                <div class="pad">
                                                    <span style="color: red; font-family: Arial; font-size: 14px;">* Indicates required question</span>
                                                </div>
                                            </div>

                                            <div class="cont2" style="padding: 25px;">

                                                <div>
                                                    <p style="margin-bottom: 18px;font-family: Arial; font-size: 16px; color: #1345AC; font-weight: bold;">Email <span style="color: red">*</span></p>
                                                    <input type="hidden" name="email1"
                                                        value="{{$users->mail}}"> <input type="hidden" name="key"
                                                        value="{{$key}}">
<input
  type="text"
  disabled
  name="email"
  id="email"
  placeholder="Your Answer"
  value="{{ $users->mail }}"
  style="
  color:#CCCCCC;
    width: 250px;
    height: 50px;
    padding: 14px 20px 12px 20px;
    border: none;
    font-family: Arial;
    font-size: 14px;
    background: #FAFAFA;
    box-sizing: border-box;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;"
>

</div>
                                                <div id="email-error"></div>
<br>
                                                <div>
                                                    <p style="margin-bottom: 18px;font-family: Arial; font-size: 16px; color: #1345AC; font-weight: bold;">User ID <span style="color: red">*</span></p><input
                                                        type="hidden" name="userid" value="{{ $users->uid }}">

                                                    <input type="text" disabled class=""
                                                        placeholder=" Your Answer"
                                                        style="
    width: 250px;
    height: 50px;
    padding: 14px 20px 12px 20px;
    border: none;
    font-family: Arial;
    font-size: 14px;
    color:#CCCCCC; background: #FAFAFA;
    box-sizing: border-box;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;"


                                                        value="{{ $users->uid }}">
                                                </div>
                                                <div id="email-error"></div>
                                                <br>
                                                <div>
                                                    <p style="margin-bottom: 18px;font-family: Arial; font-size: 16px; color: #1345AC; font-weight: bold;">User Name
                                                        <span style="color: red">*</span>
                                                    </p>

                                                    <input type="hidden" name="username1"
                                                        value="{{$users->name}}">
                                                    <input type="text" disabled name="username" id="username"
                                                        class="" placeholder=" Your Answer"
                                                        style="
    width: 250px;
    height: 50px;
    padding: 14px 20px 12px 20px;
    border: none;
    font-family: Arial;
    font-size: 14px;
    color:#CCCCCC; background: #FAFAFA;
    box-sizing: border-box;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;"


                                                        value=" {{$users->name}}">
                                                </div>
                                                <div id="username-error"></div>
                                                <br>
                                                <div class="cont2" style="padding: 0px 10px 0 0;border: none;"
                                                    id="input_fields_container">

                                                    <input type="hidden" id="click">
                                                    <input type="hidden" name="addupcdetails" value="">

                                                    <div id="input_fields_container">
                                                        <input type="hidden" name="hid-vls" id="hid-vls" value="">

                                                        {{-- <div class="space-y-8">
                                                            <div class="flex items-center gap-4">
                                                                <div class="flex items-center">
                                                                    <span>Add UPC</span>
                                                                    <span style="color: red">*</span>
                                                                    <img src="{{ asset('images/add_circle_outline.svg') }}"
                                                                        onclick="addTextField()" alt="add"
                                                                        class="add_img">
                                                                </div>
                                                                <div class="flex flex-col relative">
                                                                    <label>UPC</label>
                                                                    <input type="text" id="upcInput0"
                                                                        placeholder="Start typing UPC" onchange="generateJSON(0)"
                                                                        oninput="filterOptions(0)" autocomplete="off"
                                                                        class="select_btn input-field0">
                                                                        <div id="optionsContainer0" class="options-container top-16"></div>
                                                                </div>
                                                                <div class="flex flex-col">
                                                                    <label>ISRC</label>
                                                                    <select name="isrc" id="isrc0" onchange="generateJSON(0)"
                                                                        class="select_btn input-field0"></select>
                                                                </div>
                                                            </div>
                                                            <div class="space-y-4">
                                                                <div class="flex items-center">
                                                                    <span>Revenue Share To </span>
                                                                    <span style="color: red">*</span>
                                                                    <img src="{{ asset('images/add_circle_outline.svg') }}"
                                                                        onclick="addMoreFields(0)" alt="add"
                                                                        class="add_img">
                                                                </div>
                                                                <div class="input-group mb-3">
                                                                    <div class="user_detailss" style="">
                                                                        <span>UserID: <strong>{{ $users->uid }} </strong></span>
                                                                        <span>UserName: <strong>{{ $users->name }} </strong></span>
                                                                        <span>Percentage: <strong id="remaining-percentage">100%</strong></span>
                                                                    </div>
                                                                </div>
                                                                <div id="input_more_add0"></div>
                                                            </div>
                                                        </div> --}}
                                                        {{-- <button type="button" id="add-container">Add New Container</button> --}}

                                                        <div id="main-container"></div>

                                                        <script>
                                                            let totalPercentageLeft = 100;
                                                            let defaultTotalValue1 = 100;
                                                            document.addEventListener('DOMContentLoaded', () => {
                                                                let containerIdCounter = 0;

                                                                let rowCount = 0;
                                                                let defaultTotalValue2 = 100;

                                              

                                                                function createContainer() {
                                                                    containerIdCounter++;

                                                                    // Create container elements
                                                                    const container = document.createElement('div');
                                                                    container.classList.add('container', 'p-2');
                                                                    container.setAttribute('data-id', containerIdCounter);
                                                                    container.innerHTML = `
${containerIdCounter == 1 ? '' : '<div class="remove-container-btn remove-btn cursor-pointer" style="width:50%"><img src="/images/remove.svg" alt="add"  class="add_img2 w-6 h-6" style="max-width: none !important;"></div>'}
                                                                        <div class="mt-8 space-y-5">
                                                                            <div class="flex gap-5">
                                                                                <!--div class="flex items-center">
                                                                                    <span>Add UPC</span>
                                                                                    <span style="color: red">*</span>

                                                                                </div-->
<div class="flex flex-col relative">
  <label for="upcInput-${containerIdCounter}" style="    margin-bottom: 18px;font-family: Arial; font-size: 16px; color: #1345AC; font-weight: bold;">
    UPC:<span style="color: red">*</span>
  </label>

  <input
    type="text"
    id="upcInput-${containerIdCounter}"
    oninput="filterOptions(${containerIdCounter})"
    placeholder="Search UPC..."
    autocomplete="off"
    style="
      background: #F5F5F5;
      width: 250px;
      height: 50px;
      padding: 14px 20px 12px 20px;
      border: none;
      font-family: Arial;
      font-size: 14px;
      color: black;
      box-sizing: border-box;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;"
  >

    <img src="https://magiclink.rn-test.com/images/Search.svg"
         alt="Search"
         style="position: absolute; top: 67px; right: 15px; transform: translateY(-50%); width: 20px; height: 20px;" />

  <div
    id="optionsContainer${containerIdCounter}"
    class="options-container top-16"
    style="
      background: #F5F5F5;
      width: 250px;
      font-family: Arial;
      font-size: 14px;
      box-sizing: border-box;
      top: 92px;">
  </div>


  <div id="reason${containerIdCounter}" style="margin-top:20px;color: rgb(239, 105, 102);
display:none;font-size: 14px;"><span id="reasontext${containerIdCounter}">Invalid UPC. Please select a valid UPC.</span></div>
</div>


<div class="flex flex-col">
  <label for="isrc-${containerIdCounter}" style="    margin-bottom: 18px;font-family: Arial; font-size: 16px; color: #1345AC; font-weight: bold;">
    ISRC:
  </label>

  <div class="custom-select-wrapper" id="selectWrapper-${containerIdCounter}" tabindex="0">
    <div class="custom-select" id="isrc-${containerIdCounter}">Select an option</div>

    <img src="https://magiclink.rn-test.com/images/Down.svg" class="custom-select-icon" alt="Arrow" />

    <div class="custom-options custom-options-${containerIdCounter}" style="display: none;">
      <!-- JS will dynamically fill these -->
    </div>
  </div>
  <div id="isrcreason${containerIdCounter}" style="margin-top:20px;color: rgb(239, 105, 102);
display:none;font-size: 14px;"><span id="isrcresontext${containerIdCounter}">Invalid ISRC. Please select a valid ISRC.</span></div>
</div>
</div>


<style>
  .custom-select-wrapper {
    position: relative;
    width: 250px;
    font-family: Arial;
  }

  .custom-select {
    width: 100%;
    height: 50px;
    padding: 14px 40px 14px 20px;
    background: #F5F5F5;
    font-size: 14px;
    border: none;
    cursor: pointer;
    user-select: none;
  }

  .custom-select-icon {
    position: absolute;
    width: 15px;
    height: 10px;
    right: 20px;
    top: 50%;
    transform: translateY(-50%);
    transition: transform 0.3s ease;
    pointer-events: none;
  }

  .custom-select-wrapper.open .custom-select-icon {
    transform: translateY(-50%) rotate(180deg);
  }

  .custom-options {
    position: absolute;
    top: 100%;
    left: 0;
    width: 250px;
    background-color: #F5F5F5;
    z-index: 10;
    max-height: 200px;
    overflow-y: auto;
    display: none;
  }

  .custom-option {
    padding: 14px 40px 14px 20px;
    cursor: pointer;
    font-size: 14px;
  }

  .custom-option:hover {
    background-color: #FAFAFA;
  }
</style>

                                                                            </div>
                                                                            ${containerIdCounter == 1 ? '<div style="display:flex; font-family: Arial; font-size: 18px; color: #1345AC; font-weight: bold;margin-top:1.25rem;"> <label for="">Add Another UPC: &nbsp;&nbsp;</label> <img src="/images/Add.svg" alt="add" id="add-container" class="add_img w-6 h-6"></div>':''}


                                                                            <div class="space-y-4">
                                                                                <div style="margin-top: 10px !important;" class="flex items-center">
                                                               <span style="font-weight: bold;color: #1345ac;font-family: Arial; font-size: 16px;">Revenue Share To</span>
                                                                                </div>
                                                                                <h4 id="exit${containerIdCounter}" class="ml-4 font-medium text-gray-600" style="display:none;font-size: 14px;color: #1345ac;font-weight: bold;font-family: Arial;margin-bottom: 15px;">Existing Share:</h4>
                                                                                <div class="input-group mb-3">
                                                                                    <div class="user_detailss${containerIdCounter}" style="">
                                                                                    </div>
                                                                                </div>
																				 <div class="flex items-center">
                                                                                <h4 class="ml-4 font-medium text-gray-600" style="font-family: Arial; font-size: 14px; color: #1345AC; font-weight: bold;margin-bottom: 15px;">New Share:<span style="color: red">*</span></h4>

                                                                                    <data-container-id="${containerIdCounter}" alt="add" class="add-inputs add_img1 w-6 h-6"></div>
                                                                                <div id="additional-inputs-${containerIdCounter}" class="additional-inputs space-y-2" style="margin:0 !important"></div>
                                                                                <div id="newshare${containerIdCounter}" style="display:none;color:#EF6966;"></div>
                                                                            </div>
                                                                            <div id="share${containerIdCounter}" style="margin-top: 20px; color: rgb(239, 105, 102); display: none; font-size: 14px;"><span id="sharetext${containerIdCounter}">Please add atleast one new share.</span></div>
                                                                        </div>
                                                                        <input type="hidden" id="json-input-${containerIdCounter}" name="json-input-${containerIdCounter}">
                                                                    `;


                                                                    document.getElementById('main-container').appendChild(container);



                                                                    const nameInput = document.getElementById(`upcInput-${containerIdCounter}`);
                                                                    const genderSelect = document.getElementById(`isrc-${containerIdCounter}`);
                                                                    const additionalInputsContainer = document.getElementById(`additional-inputs-${containerIdCounter}`);
                                                                    const jsonInput = document.getElementById(`json-input-${containerIdCounter}`);
                                                                    const addInputsButton = container.querySelector('.add-inputs');

                                                                    const removeContainerButton = container.querySelector('.remove-container-btn');
                                                                    const RnRevenname = ["Userid", "Username", "Percentage"];
                                                                    const RnRevenname1 = ["Username", "%"];
                                                                    function updateJson() {
                                                                        const jsonData = {
                                                                            UPCid: nameInput.value,
                                                                            ISRC: genderSelect.textContent,
                                                                            RevenueShareTo: [] // Initialize as empty
                                                                        };


                                                                        const currentInputs = Array.from(additionalInputsContainer.querySelectorAll('input'));
                                                                        for (let i = 0; i < currentInputs.length; i += 3) {
                                                                            const group = {};
                                                                            for (let j = 0; j < 3; j++) {
                                                                                if (currentInputs[i + j]) {
                                                                                    group[RnRevenname[j] + `${i + j + 1}`] = currentInputs[i + j].value;
                                                                                
                                                                                };
                                                                            };
                                                                            jsonData.RevenueShareTo.push(group);
                                                                        };
                                                                         console.log('jsonData', jsonData)
                                                                        jsonInput.value = JSON.stringify(jsonData);
                                                                        document.getElementById('hid-vls').value = document.querySelectorAll('#main-container .container').length;
                                                                    };

                                                                    function updateAllShares() {
                                                                        const percentages = document.querySelectorAll(`coverform_input${containerIdCounter} input[name="percentage${cnt}[]"`);
                                                                        percentages.forEach(input => {
                                                                            updatePercentage(input, defaultTotalValue1 - getSumOfPreviousPercentages());
                                                                        });
                                                                    }

                                                                    function updatePercentage1(input, maxPercentage, cnt) {
                                                                        const percentage = parseFloat(input.value || 0);
                                                                        if (percentage > maxPercentage) {
                                                                            input.value = maxPercentage;
                                                                        }
                                                                      //  updateRemainingPercentage2(input, cnt);
                                                                        // updateAllShares();
                                                                    }
                                                                    let droplist = 0;
                                                                    addAdditionalInputs(containerIdCounter);

                                                                    function addAdditionalInputs(containerId) {

                                                                        droplist++;
                                                                        const inputGroup = document.createElement('div');
                                                                        $('#share' + containerId).css('display', 'none');
                                                                        $(`#newreason${droplist}${containerId}`).hide();
        $(`#usernewreason${droplist}${containerId}`).hide();
        $(`#pernewreason${droplist}${containerId}`).hide();
        $(`#newshare${containerId}`).hide();
    
 

                                                                        inputGroup.classList.add(`coverform_input${containerId}`, 'input-group', 'flex', 'items-top', 'gap-4');

const mainnn = document.createElement('div');
mainnn.style.position = 'relative';
mainnn.style.width = '27%';


// Input field
const UsernewInput = document.createElement('input');
UsernewInput.type = 'text';
UsernewInput.placeholder = "Userid";
UsernewInput.classList.add('select_btn', `list${droplist}`);
UsernewInput.setAttribute('name', "shareUPC[]");
UsernewInput.setAttribute('autocomplete', "off");
//UsernewInput.required = true;
UsernewInput.setAttribute('oninput', `RevenupdateNameField(this, ${droplist}, ${containerId})`);
UsernewInput.style.paddingRight = '27px';
UsernewInput.style.width = '250px';
UsernewInput.style.height = '50px';
if(droplist == 1)
{
    UsernewInput.disabled = true;
    UsernewInput.value = "<?php echo htmlspecialchars($users->uid, ENT_QUOTES, 'UTF-8'); ?>";
}
mainnn.appendChild(UsernewInput);

// SVG icon
if(droplist > 1)
{
//const arrowIcon = document.createElement('img');
// arrowIcon.src = "https://magiclink.rn-test.com/images/Search.svg";
// arrowIcon.alt = "Arrow";
// arrowIcon.id = `searchIcon${containerId}`; // <-- Set ID here

// arrowIcon.style.width = '20px';
// arrowIcon.style.height = '20px';
// arrowIcon.style.position = 'absolute';
// arrowIcon.style.right = '22px';
// arrowIcon.style.top = '25px';
// arrowIcon.style.transform = 'translateY(-50%)';
// arrowIcon.style.pointerEvents = 'none';
// mainnn.appendChild(arrowIcon);
}



// Dropdown container
const mainspan = document.createElement('span');
mainspan.classList.add('dropdown-menu', 'shareUPCDropdown', 'w-max');
mainspan.style.display = 'none';
mainspan.setAttribute('id', `shareUPCDropdown${droplist}`);
mainnn.appendChild(mainspan);


const reasonDiv = document.createElement('div');
reasonDiv.id = `newreason${droplist}${containerId}`;
reasonDiv.style.marginTop = '20px';
reasonDiv.style.color = 'rgb(239, 105, 102)';
reasonDiv.style.lineHeight='1.4' ;
reasonDiv.style.fontSize = '14px';
reasonDiv.style.width = '94%';

reasonDiv.style.display = 'none'; // Hide by default

const reasonSpan = document.createElement('span');
reasonSpan.textContent = 'Please fill in this field';

reasonDiv.appendChild(reasonSpan);

// Append reason div to mainnn
mainnn.appendChild(reasonDiv);


// Append to main group
inputGroup.appendChild(mainnn);



// ▼▼▼ Show dropdown only when user types something ▼▼▼
UsernewInput.addEventListener('input', () => {
  const val = UsernewInput.value.trim();
  if (val !== "") {
    toggleDropdown(true);
  } else {
    toggleDropdown(false);
  }
});

// ▼▼▼ Hide dropdown after blur ▼▼▼
UsernewInput.addEventListener('blur', () => {
  setTimeout(() => toggleDropdown(false), 200);
});

function toggleDropdown(show) {

}

// Keep your updateJson logic
UsernewInput.addEventListener('input', updateJson);


for (let i = 0; i < 2; i++) {
    // Create wrapper div
    const inputWrapper = document.createElement('div');
    inputWrapper.style.position = 'relative';
    inputWrapper.style.width = '26.5%';


    // Create input
    const newInput = document.createElement('input');
    newInput.type = 'text';
    newInput.placeholder = RnRevenname1[i];
    newInput.classList.add('select_btn');
    newInput.style.width = '250px';
    newInput.style.height = '50px';
    newInput.addEventListener('input', updateJson);

    newInput.addEventListener('input', function () {
        const inputstext = document.querySelectorAll(`input[name="percentage${containerId}[]"]`);
 
 inputstext.forEach(input => {
input.style.background = '#F5F5F5';
input.style.border = 'none';
input.style.color = 'black';
});


        $(`#newshare${containerId}`).hide();
    
        console.log('droplist',droplist);
        newInput.style.background = '#F5F5F5';
        newInput.style.border = 'none';
        newInput.style.color = 'black';
        $(newInput).removeClass('input-error');

        $(`#usernewreason${droplist}${containerId}`).hide();
        $(`#pernewreason${droplist}${containerId}`).hide();

    });


    let errorDivId = '';

    if (RnRevenname1[i] === "Username") {
        newInput.setAttribute('name', "sharename[]");
       
        if(droplist == 1)
{
    newInput.disabled = true;
    newInput.value = "<?php echo htmlspecialchars($users->name, ENT_QUOTES, 'UTF-8'); ?>";
}
        errorDivId = `usernewreason${droplist}${containerId}`;
      
    }
    

    if (RnRevenname1[i] === "%") {
        newInput.setAttribute('name', `percentage${containerId}[]`);
       
        errorDivId = `pernewreason${droplist}${containerId}`;
        newInput.addEventListener('input', function () {
            updatePercentage1(this, totalPercentageLeft, containerId);
        });
    }

    // Create error message div
    const errorDiv = document.createElement('div');
    errorDiv.id = errorDivId;
    errorDiv.textContent = 'Please fill in this field.';
    errorDiv.style.marginTop = '20px';
    errorDiv.style.color = '#EF6966';
    errorDiv.style.fontSize = '14px';
    errorDiv.style.display = 'none'; // Hidden by default
    errorDiv.style.width = '80%';
   
    // Append input and error to wrapper
    inputWrapper.appendChild(newInput);
    inputWrapper.appendChild(errorDiv);

    // Append wrapper to the parent group
    inputGroup.appendChild(inputWrapper);
}




const controlButtons = document.createElement('div');
controlButtons.classList.add('flex', 'items-center', 'gap-2');

const addButton = document.createElement('img');
addButton.src = '/images/Add.svg';
addButton.alt = 'add';
addButton.classList.add('add_img', 'w-6', 'h-6', 'relative', 'top-[9px]');
addButton.style.maxWidth = 'none';
addButton.dataset.containerId = containerId;
addButton.style.cursor = 'pointer';

addButton.addEventListener('click', function () {
  const containerId = this.dataset.containerId;
  addAdditionalInputs(containerId);
});


if(droplist > 1)
{
const removeButton = document.createElement('div');
removeButton.classList.add(
  'remove-container-btn',
  'remove-btn',
  'cursor-pointer'
);

// Create the <img> element
const img = document.createElement('img');
img.src = '/images/remove.svg';
img.alt = 'remove';
img.classList.add('add_img', 'w-6', 'h-6','relative', 'top-[9px]');
img.setAttribute("style", "max-width: none !important;");

// Append the image to the div
removeButton.appendChild(img);

// Set the click event
removeButton.addEventListener('click', () => {
  inputGroup.remove();
  updateJson();
});
inputGroup.appendChild(removeButton);
}

const addButtonWrapper = document.createElement('div');
addButtonWrapper.classList.add('cursor-pointer');
addButtonWrapper.appendChild(addButton);

controlButtons.appendChild(addButtonWrapper);

inputGroup.appendChild(controlButtons);

                                                                      
                                                                        additionalInputsContainer.appendChild(inputGroup);
                                                                        updateJson();
                                                                    };
                                                                    nameInput.addEventListener('input', updateJson);
                                                                    genderSelect.addEventListener('change', updateJson);

                                                                  //  addInputsButton.addEventListener('click', addAdditionalInputs);
                                                                  addInputsButton.addEventListener('click', function(e) {
  const containerId = this.dataset.containerId; // e.g. "2"
  console.log('container id:', containerId);
  addAdditionalInputs(containerId);
});

                                                                    $(removeContainerButton).click(function() {
                                                                        container.remove();
                                                                        document.getElementById('hid-vls').value = document.querySelectorAll('#main-container .container').length;
                                                                    });
                                                                    updateJson(); // Initial JSON update
                                                                };

                                                                // document.getElementById('add-container').addEventListener('click', createContainer);
                                                                 createContainer();

                                                                 document.addEventListener('click', function(e) {
    if (e.target && e.target.id === 'add-container') {
        createContainer();
    }


});

                                                            });












                                                            // ---------------------------------------- New Last ---------------------
                                                            let rowcntss = 0;

                                                            function addMoreFields(id) {
                                                                const container = document.getElementById('input_more_add' + id);
                                                                container.classList.add('space-y-2');
                                                                const inputfeilddiv = document.createElement('div');
                                                                inputfeilddiv.classList.add('coverform_input', 'input-fields', 'grid', 'grid-cols-4', 'grid-flow-col', 'gap-32',
                                                                    'items-center');

                                                                const input = `

                                                                    <div class="">
                                                                        <input style="width:250px" type="text" onchange="generateJSON(${id})" name="shareUPC[]" onkeyup="checkInput()" placeholder="Enter value" class=" input-field${id} shareUPC border px-1.5 py-1 select_btn" autocomplete="off" oninput="RevenupdateNameField(this, ${rowcntss})">

                                                                        <span class="dropdown-menu shareUPCDropdown w-max " id="shareUPCDropdown${rowcntss}" style="display: none;"></span>
                                                                    </div>
                                                                    <input style="width:250px" type="text" placeholder="Enter value" name="sharename[]" required autocomplete="off" class="form-control select-field input-field${id} border px-1.5 py-1 select_btn" readonly>
                                                                    <input  style="width:250px" type="text" placeholder="%" onchange="generateJSON(${id})" name="percentage[]" class="input-field${id} border px-1.5 py-1 select_btn form-control percentageinput">

                                                                `;
                                                                inputfeilddiv.insertAdjacentHTML('beforeend', input);
                                                                const image = document.createElement("img");
                                                                image.src = "{{ asset('images/remove_circle_outline.svg') }}";
                                                                image.alt = "remove";
                                                                image.classList.add('h-6', 'w-6', 'cursor-pointer')
                                                                image.onclick = function() {
                                                                    removeInputFields(this);
                                                                };
                                                                inputfeilddiv.appendChild(image);
                                                                container.appendChild(inputfeilddiv);
                                                                rowcntss++;
                                                            };

                                                            function removeInputFields(button) {
                                                                const wrapper = button.parentElement;
                                                                wrapper.remove();
                                                            }


                                                            function updateIsrcOptions(selectedUpc, id) {
                                                               console.log('selectedUpc', selectedUpc)

                                                             const userId = $('input[name="userid"]').val();



                                                             $.ajax({
                                                            type: "POST",
                                                                url: "{{ route('getupcDetails1') }}",
                                                                headers: {
                                                                    'X-CSRF-TOKEN': '{{ csrf_token() }}'
                                                                },
                                                                data: {
                                                                    query: 'one',
                                                                    upc:selectedUpc,
                                                                    user_id: userId
                                                                },
success: function (response) {



    $(`.user_detailss${id}`).empty(); 
if(response.split.length > 0){
    

response.split.forEach(function (user) {
const html = `
   <div class="user_detailss">
        <span>UserID: <strong>${user.selected_uid}</strong></span>
        <span>UserName: <strong>${user.user_name}</strong></span>
        <span>Percentage: <strong>${user.percent}%</strong></span>
   </div>
`;
$(`.user_detailss${id}`).append(html);

});

$(`#exit${id}`).css('display','block'); 
}


  const upcToIsrcMap = response.upcToIsrcMap || {};
  const isrcList = upcToIsrcMap[selectedUpc] || [];

  const isrcSelect = document.getElementById("isrc-" + id);
  const selectWrapper = document.getElementById("selectWrapper-" + id);
  const optionsContainer = selectWrapper.querySelector(".custom-options-" + id);

  // Clear options
  optionsContainer.innerHTML = "";

  // Reset selected text
  isrcSelect.textContent = "Select an option";

  // Populate options
  if (isrcList.length > 1) {
    const applyToAll = document.createElement("div");
 applyToAll.className = "custom-option";
    isrcSelect.textContent = "Apply to all tracks";
   applyToAll.textContent = "Apply to all tracks";
    applyToAll.dataset.value = "all";
    optionsContainer.appendChild(applyToAll);
  }

  if (isrcList.length > 0) {
    isrcList.forEach(function (isrc) {
      const option = document.createElement("div");
      option.className = "custom-option";
     // isrcSelect.textContent = "Apply to all tracks";
      option.textContent = isrc;
      option.dataset.value = isrc;
      optionsContainer.appendChild(option);
    });
  } else {
    const empty = document.createElement("div");
    empty.className = "custom-option";
   // empty.textContent = "No ISRC found";
    empty.dataset.value = "";
    optionsContainer.appendChild(empty);
  }

  // Show dropdown on click
  isrcSelect.onclick = function () {





    isrcSelect.style.background = '#F5F5F5';
    isrcSelect.style.border = 'none';
    isrcSelect.style.color = 'black';

    $('#isrcreason' + id).css('display', 'none');
    $('[id^="isrcreason"]').css('display', 'none');

    const isOpen = selectWrapper.classList.toggle("open");
    optionsContainer.style.display = isOpen ? "block" : "none";
  };

  // Close dropdown on blur
  selectWrapper.addEventListener("blur", function () {
    selectWrapper.classList.remove("open");
    optionsContainer.style.display = "none";
  });

  // Handle option selection
  optionsContainer.querySelectorAll(".custom-option").forEach(function (option) {
    option.addEventListener("click", function () {

       // if(this.textContent != 'Apply to all tracks'){

        
$.ajax({
                                                    type: "POST",
                                                        url: "{{ route('getupcDetails1') }}",
                                                        headers: {
                                                            'X-CSRF-TOKEN': '{{ csrf_token() }}'
                                                        },
                                                        data: {
                                                            query: 'three',
                                                            upc:selectedUpc,
                                                            uid: userId,
                                                            isrc:this.textContent
                                                        },
success: function (response) {
$(`.user_detailss${id}`).empty(); 
if(response.split.length > 0){
    

response.split.forEach(function (user) {
const html = `
   <div class="user_detailss">
        <span>UserID: <strong>${user.selected_uid}</strong></span>
        <span>UserName: <strong>${user.user_name}</strong></span>
        <span>Percentage: <strong>${user.percent}%</strong></span>
   </div>
`;
$(`.user_detailss${id}`).append(html);

});

$(`#exit${id}`).css('display','block'); 
}
}
});
// }
// else{
// $(`#exit${id}`).css('display','none'); 
// $(`.user_detailss${id}`).empty(); 
// }


      isrcSelect.textContent = this.textContent;
      selectWrapper.classList.remove("open");
      optionsContainer.style.display = "none";
    });
  });

                                                                }
                                                            })

                                                            }

                                                            function handleInputSelection(selectedText, events) {


                                                                    updateIsrcOptions(selectedText, events);


                                                            }






                                                            function filterOptions(events) {

                                                                const input = document.getElementById('upcInput-' + events).value.toLowerCase();

                                                                const container = document.getElementById('optionsContainer' + events);
                                                                const upcInput1 = document.getElementById('upcInput-' + events);

                                                                $(`#exit${events}`).css('display','none'); 
                                                                $(`.user_detailss${events}`).empty(); 

                                                                upcInput1.style.background = "#F5F5F5";
                                                                upcInput1.style.border = "none";
                                                                upcInput1.style.color = "black";
                                                                $('#reason'+events).css('display','none');

                                                                const query = input;
                                                                const userId = $('input[name="userid"]').val();
                                                                $.ajax({
                                                                    type: "POST",
                                                                    url: "{{ route('getupcDetails1') }}",
                                                                    headers: {
                                                                        'X-CSRF-TOKEN': '{{ csrf_token() }}'
                                                                    },
                                                                    data: {
                                                                        query: query,
                                                                        user_id: userId
                                                                    },
                                                                    success: function (response) {
                                                                        const options1 = response.upcs || [];





                                                                        const options = options1.map(item => ({
                                                                            value: item.upc,
                                                                            text: item.upc

                                                                        }));



            //                                                             const selectedUPCs = Array.from(document.querySelectorAll('[id^="upcInput-"]'))
            //     .map(input => input.value.trim().toLowerCase())
            //     .filter(val => val !== '');

            // const filteredOptions = options.filter(option => {
            //     const optionText = String(option.text).toLowerCase();
            //     return optionText.includes(input) && !selectedUPCs.includes(optionText);
            // });



                                                                const filteredOptions = options.filter(option => {
                // Convert option.text to string before calling toLowerCase
                const optionText = String(option.text);
                return optionText.toLowerCase().includes(input);
            });
                                                              //  const filteredOptions = options.filter(option => option.text.toLowerCase().includes(input));



                                                                container.innerHTML = '';
                                                                if (filteredOptions.length > 0 && input) {
                                                                    filteredOptions.forEach(option => {
                                                                        const listelement = document.createElement('div');
                                                                        listelement.textContent = option.text;
                                                                        listelement.onclick = function() {
                                                                            document.getElementById('upcInput-' + events).value = this.textContent;
                                                                            document.getElementById('upcInput-' + events).setAttribute('data-id', this.textContent)
                                                                            container.style.display = 'none';
                                                                            handleInputSelection(this.textContent, events);
                                                                        };
                                                                        container.appendChild(listelement);
                                                                    });
                                                                    container.style.display = 'block';
                                                                } else {
                                                                    container.style.display = 'none';
                                                                }

                                                            }
                                                        });
                                                            }





    //console.log(formattedOptions);
    let debounceTimer;
                                                            const MAX_RESULTS = 10;


 function RevenupdateNameField(inputElement, id, mid) {
   // clearTimeout(debounceTimer);
    //debounceTimer = setTimeout(function () {
      //  const inputValue = inputElement.value.trim().toLowerCase();
        // const dropdownMenu = document.querySelector(`.coverform_input${mid} #shareUPCDropdown${id}`);
        // dropdownMenu.innerHTML = '';


        $(`#newreason${id}${mid}`).hide();
        $(`#usernewreason${id}${mid}`).hide();
        $(`#pernewreason${id}${mid}`).hide();


}


function callfunctiontoupdate(mid){

                    
const nameInput22 = document.getElementById(`upcInput-${mid}`);
const genderSelect22 = document.getElementById(`isrc-${mid}`);
const additionalInputsContainer22 = document.getElementById(`additional-inputs-${mid}`);
const jsonInput22 = document.getElementById(`json-input-${mid}`);

const RnnRevenname = ["Userid", "Username", "Percentage"];
const RnnRevenname1 = ["Username", "%"];

    
    const jsonData22 = {
        UPCid: nameInput22.value,
        ISRC: genderSelect22.textContent,
        RevenueShareTo: [] // Initialize as empty
    };


    const currentInputs22 = Array.from(additionalInputsContainer22.querySelectorAll('input'));
    for (let i = 0; i < currentInputs22.length; i += 3) {
        const group = {};
        for (let j = 0; j < 3; j++) {
            if (currentInputs22[i + j]) {
                group[RnnRevenname[j] + `${i + j + 1}`] = currentInputs22[i + j].value;
            
            };
        };
        jsonData22.RevenueShareTo.push(group);
        
    };
        console.log('jsonData', jsonData22)
        jsonInput22.value = JSON.stringify(jsonData22);
    document.getElementById('hid-vls').value = document.querySelectorAll('#main-container .container').length;

}

                                                            // function RevenupdateNameField(inputElement, id, mid) {

                                                            //     console.log('Input changed - 1'); // Debug statement
                                                            //     const inputValue = inputElement.value.trim().toLowerCase();
                                                            //     const dropdownMenu = document.querySelector(`.coverform_input${mid} #shareUPCDropdown${id}`);
                                                            //     dropdownMenu.innerHTML = '';
                                                            //     $data.forEach(function(user) {
                                                            //         if (user.uid.toString().toLowerCase().includes(inputValue)) {
                                                            //             var option = document.createElement('div');
                                                            //             option.classList.add('dropdown-item');
                                                            //             option.textContent = user.uid;
                                                            //             option.onclick = function() {
                                                            //                 inputElement.value = user.uid;

                                                            //                 // Set the corresponding name in the sharename input field
                                                            //                 var sharenameInput = inputElement.closest(`.coverform_input${mid}`).querySelector('[name="sharename[]"]');
                                                            //                 // console.log('inputValue', sharenameInput, user)
                                                            //                 sharenameInput.value = user.name;
                                                            //                 dropdownMenu.style.display = 'none';

                                                            //             };
                                                            //             dropdownMenu.appendChild(option);
                                                            //         }
                                                            //     });
                                                            //     if (inputElement.value == '') {
                                                            //         var sharenameInput = inputElement.closest(`.coverform_input${mid}`).querySelector('[name="sharename[]"]');
                                                            //         sharenameInput.value = '';
                                                            //     }

                                                            //     // Display the dropdown menu
                                                            //     if (inputValue.length > 0) {
                                                            //         dropdownMenu.style.display = 'block';
                                                            //     } else {
                                                            //         dropdownMenu.style.display = 'none';
                                                            //     }
                                                            // }

                                                            function generateJSON(id) {
                                                                // Select all input fields related to the given ID
                                                                const inputs = document.querySelectorAll(".input-field" + id);
                                                                const data = [{}];
                                                                // const data = {};

                                                                // Iterate through inputs in pairs
                                                                for (let i = 0; i < inputs.length; i += 3) {
                                                                    if (i + 2 < inputs.length) { // Ensure there are enough elements in the pair
                                                                        const uniqueId = Math.floor(i / 3);
                                                                        // data.push({
                                                                        // value1: inputs[i].value,
                                                                        // value2: inputs[i + 1].value,
                                                                        // Revenue: [
                                                                        //     {
                                                                        //         uid: inputs[i + 2].value,
                                                                        //         user: inputs[i + 3].value,
                                                                        //         percentage: inputs[i + 4].value,
                                                                        //     }
                                                                        // ]
                                                                        // });
                                                                        data[`text${uniqueId}`] = {
                                                                            value1: inputs[i].value,
                                                                            value2: inputs[i + 1].value,
                                                                            Revenue: [{
                                                                                uid: inputs[i + 2].value,
                                                                                user: inputs[i + 3].value,
                                                                                percentage: inputs[i + 4].value,
                                                                            }]
                                                                        };
                                                                    }
                                                                }

                                                                // Convert to JSON format and log it
                                                                const json = JSON.stringify(data, null, 2);
                                                                // console.log('json', data);
                                                            }
                                                        </script>
                                                    </div>
                                                </div>
                                            </div>
                                            <div>




                                                <div
                                                    style="padding: 20px;display: flex;justify-content: space-between;">

<button class="btn" id="submit3">Submit</button>

                                                    <style>
                                                        .enabled {
                                                            cursor: pointer !important;
                                                        }
                                                    </style>

                                                    <script>
                                                        function checkInput() {
                                                            var inputValue = document.getElementById('form_value').value.trim();
                                                            var submitButton = document.getElementById('submit3');
                                                            if (inputValue !== '') {
                                                                submitButton.removeAttribute('disabled');
                                                                submitButton.classList.add('enabled');
                                                            } else {
                                                                submitButton.setAttribute('disabled', 'disabled');
                                                                submitButton.classList.remove('enabled');
                                                            }
                                                        }
                                                    </script>
<a class="clear-btn" onclick="location.reload();">Clear Form</a>
                                                </div>
                                            </div>

                                        </div>
                                </div>
                            </div>
                        </div>
                        </form>
                    </div>
                @endif
                <style>
  .clear-btn {
    cursor: pointer;
    text-decoration: none;
    margin: auto 0;
    float: right;
    background-color: #ffffff;
    color: #1345AC;
    border: 2px solid #1345AC;
    width: 130px;
    height: 50px;
    font-family: Arial;
    font-weight: bold;
    font-size: 16px;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;
  }

  .clear-btn:hover {
    background-color: #1345AC;
    color: #ffffff;
  }
</style>

                <style>
                    .form_input input {
                        width: 95%;
                        border: 1px solid #ccc;
                        padding: 5px;
                        border-radius: 6px;
                        margin-top: 5px;
                    }

                    .verify_btn {
                        background: #f0eaf8;
                        padding: 3px 10px;
                        border-radius: 5px;
                        border: none;
                        color: #5a39b6;
                        box-shadow: 1px 1px 4px #000;
                    }

                    .select_btn {
                        padding: 14px 40px 14px 20px;
                        background: #F5F5F5;
                        color: #000;
                        width: 163px;
                        cursor: pointer;
                        box-sizing: border-box;
                        transition: border-color 0.3s ease;
                    }

                    .select_btn:focus {
                        outline: none;
                        border-color: #ccc;
                    }



                    .user_detailss {
                        display: flex;
                        justify-content: space-evenly;
                        background: #f5f5f5;
                        padding: 10px;
                        height:50px;
                    }

                    .user_detailss span {
                        margin: auto 0;
                    }

                    @keyframes blink {
                        0% {
                            outline: 2px solid red;
                        }

                        50% {
                            outline: 2px solid rgba(228, 228, 228, 0);
                        }

                        100% {
                            outline: 2px solid red;
                        }
                    }

                    .blinking {
                        animation: blink 1.5s infinite;
                    }
                </style>

</html>

<script>
    let array = [];

    function getarray(val, event, name) {

        // console.log('event', val, event);
        if (array.length == event + 1) {

        }
        if (array.length > 0) {
            if (name == 'isrc') {
                array[0]['isrc'] = val.value;
                console.log('event', val.value, event, array)
            }
        } else {
            if (name == 'upc') {
                array.push({
                    "upc": val.value
                });
                console.log('event', val.value, event, array)
            }
        }

    }


    //populateOptions();
</script>
<style>
    .options-container {
        display: none;
        max-height: 150px;
        overflow-y: auto;
        position: absolute;
        background: white;
        z-index: 1000;
    }

    .options-container div {
      padding: 14px 20px 14px 20px;
        cursor: pointer;
    }

    .options-container div:hover {
        background: #fafafa;
    }
</style>
<script>
    let totalPercentageLefta = 100; // Initial total percentage
    let rowcnt = 0;

    function addTextField1() {
        const container = document.getElementById('input_fields_containerr0');
        // const rowcnt = container.children.length + 1;
        // for (let i = 0; i < 1; i++) {
        const newDiv = document.createElement('div');
        // newDiv.className = 'form_input';
        newDiv.classList.add('form_wrappers')
        // <input type="text" class="form-control percentageinput" name="percentage[]" placeholder="%" oninput="updatePercentage(this, ${totalPercentageLefta})">
        newDiv.innerHTML = `
				<br>
                    <div style="width: 100%; gap:20px; display:flex; font-size: 12px" class="form_input">
                        <div style="">UserID:<br>
                            <input type="text" class="form_input form-control shareUPC input-field" onkeyup="checkInput()" name="shareUPC[]" required autocomplete="off" oninput="updateNameField(this, ${rowcnt})">
                            <span class="dropdown-menu shareUPCDropdown" id="shareUPCDropdown${rowcnt}" style="display: none;"></span>
                        </div>
                        <div>
                            UserName:<br>
                            <input style="width:250px" type="text" class="form-control select-field" name="sharename[]" required autocomplete="off" readonly>
                        </div>
                        <div>
                            Enter Percentage:<br>
                            <input style="width:250px" type="text" class="form-control percentageinput" name="percentage[]" placeholder="%" >
                        </div>
                        <div style="margin: auto; width: 5%">
                            <br>
                            <img src="{{ asset('images/remove_circle_outline.svg') }}" alt="remove" onclick="removeTextField(this)" class="remove_img">
                        </div>
                    </div>
                `;

        container.appendChild(newDiv);

        // newDiv.addEventListener("input", generateJSON);
        const inputFields = newDiv.querySelectorAll('.input-field');
        const percentageFields = newDiv.querySelectorAll('.percentageinput');

        inputFields.forEach(input => input.addEventListener('input', generateJSON));
        percentageFields.forEach(input => input.addEventListener('input', generateJSON));
        rowcnt++;

        // }
    }

    function generateJSON_() {
        const inputFields = document.querySelectorAll(".input-field");
        const selectFields = document.querySelectorAll(".select-field");
        const percentageFields = document.querySelectorAll(".percentageinput");
        const inputPairs = [];

        inputFields.forEach((input, index) => {
            const select = index < selectFields.length ? selectFields[index] : null;
            const percentage = index < percentageFields.length ? percentageFields[index].value : '';

            if (input instanceof HTMLInputElement && select instanceof HTMLInputElement) {
                inputPairs.push({
                    userID: input.value,
                    userName: select ? select.value : '',
                    percentage: percentage
                });
            }
        });

        const json = JSON.stringify(inputPairs, null, 2);
        console.log('inputPairs', json)
    }

    function removeTextField(element) {
        const fieldContainer = element.closest('.form_input');
        if (fieldContainer) {
            const percentageInput = fieldContainer.querySelector('input[name="percentage[]"]');
            if (percentageInput) {
                totalPercentageLeft += parseFloat(percentageInput.value) || 0; // Restore the removed percentage
            }
            fieldContainer.remove();
        }
    }

    function checkInput() {
        // Add your implementation here
    }



    function updateNameField(inputElement, id) {

        console.log('Input changed - 1', inputElement, id); // Debug statement
        const inputValue = inputElement.value.trim().toLowerCase();
        const dropdownMenu = document.getElementById('shareUPCDropdown' + id);
        console.log('dropdownMenu', dropdownMenu)
        // Clear the dropdown menu
        dropdownMenu.innerHTML = '';

        // Filter and display similar values from $data
        $data.forEach(function(user) {
            if (user.uid.toString().toLowerCase().includes(inputValue)) {
                var option = document.createElement('div');
                option.classList.add('dropdown-item');
                option.textContent = user.uid;
                option.onclick = function() {
                    inputElement.value = user.uid;
                    // Set the corresponding name in the sharename input field
                    var sharenameInput = inputElement.closest(
                        '.form_input').querySelector(
                        '[name="sharename[]"]');
                    sharenameInput.value = user.name;
                    dropdownMenu.style.display = 'none';
                };
                dropdownMenu.appendChild(option);
            }
        });
        if (inputElement.value == '') {
            var sharenameInput = inputElement.closest(
                '.form_input').querySelector(
                '[name="sharename[]"]');
            sharenameInput.value = '';
        }
        // Display the dropdown menu
        if (inputValue.length > 0) {
            dropdownMenu.style.display = 'block';
        } else {
            dropdownMenu.style.display = 'none';
        }
    }

    function updatePercentage(input, totalPercentageLeft) {
        console.log('totalPercentageLeft', input)
        const percentage = parseFloat(input.value || 0);
        if (percentage > maxPercentage) {
            input.value = maxPercentage;
        }
        updateRemainingPercentage();
        updateAllShares();
    }
</script>



<script>
    function getSumOfPreviousPercentages() {
        const percentages = document.querySelectorAll('input[name="percentage[]"]');
        return Array.from(percentages).reduce((acc, input) => acc + parseFloat(input.value || 0), 0);
    }

    function updateRemainingPercentage() {

        const remainingPercentage = defaultTotalValue1 - getSumOfPreviousPercentages();
        document.getElementById('remaining-percentage').innerText = remainingPercentage + '%';
    }
    let rowcnt2 = 0;
    // let totalPercentageLeft = 100; // Example total percentage left
    // function addTextField2(number) {
    //     const container = document.getElementById('input_fields_container' + number);

    //     // Ensure totalPercentageLeft is valid and non-negative
    //     if (totalPercentageLefta <= 0) {
    //         alert('No percentage left to allocate.');
    //         return;
    //     }

    //     const newDiv = document.createElement('div');
    //     newDiv.className = 'form_input';
    //     // <div style=""> Enter Percentage:<br><input type="text" class="form-control" name="percentage[]" placeholder="%" oninput="updatePercentage(this, ${totalPercentageLeft})"> </div>
    //     newDiv.innerHTML = `
    //             <div style="width: 100%; gap:20px; display:flex; font-size: 12px">
    //                 <div>
    //                     UserID:<br>
    //                    <input type="text" class="form-control shareUPC input-field" onkeyup="checkInput()" name="shareUPC[]" required autocomplete="off" oninput="updateNameField(this, ${rowcnt2})">
    //             <span class="dropdown-menu" id="shareUPCDropdown" style="display: none;"></span>
    //                 </div>
    //                 <div>
    //                     UserName:<br>
    //                     <input type="text" class="form-control select-field" name="sharename[]" required autocomplete="off" readonly>
    //                 </div>
    //                  <div style=""> Enter Percentage:<br><input type="text" class="form-control percentageinput" name="percentage[]" placeholder="%" oninput="updatePercentage(this, ${totalPercentageLeft})"> </div>
    //                 <div style="margin: auto; width: 5%">
    //                     <br>
    //                     <img src="{{ asset('images/remove_circle_outline.svg') }}" alt="remove" onclick="removeTextField(this)" class="remove_img">
    //                 </div>
    //             </div>
    //         `;

    //     container.appendChild(newDiv);
    //     rowcnt2++;
    //     const inputFields = newDiv.querySelectorAll('.input-field');
    //         const percentageFields = newDiv.querySelectorAll('.percentageinput');

    //         inputFields.forEach(input => input.addEventListener('input', generateJSON));
    //         percentageFields.forEach(input => input.addEventListener('input', generateJSON));
    // }


    function addTextField2(rowCount) {
        const inputFieldsDiv = document.getElementById('input_fields_containerr' + rowCount);
        console.log('inputFieldsDiv', inputFieldsDiv, rowCount)

        // Create a wrapper for the input fields and remove button using HTML string
        const htmlString = `
            <div class="input-wrapper">
                <input type="text" placeholder="Enter value" class="input-field">
                <input type="text" placeholder="Enter value" class="input-field">
                <button class="remove-button" onclick="removeInputFields(this)">Remove</button>
            </div>
        `;

        // Insert the HTML string into the input fields container
        inputFieldsDiv.insertAdjacentHTML('beforeend', htmlString);
    }

    function removeTextField(element) {
        const fieldContainer = element.closest('.form_input');
        if (fieldContainer) {
            const percentageInput = fieldContainer.querySelector('input[name="percentage[]"]');
            if (percentageInput) {
                totalPercentageLeft += parseFloat(percentageInput.value) || 0; // Restore the removed percentage
            }
            fieldContainer.remove();
        }
    }

    function removeTextField1(element) {
        document.getElementById('input_fields_container').removeChild(element.closest('.input-group'));
        rowCount--;
        updateRemainingPercentage();
        updateAllShares();
    }



    function updatePercentage(input, maxPercentage) {
        const percentage = parseFloat(input.value || 0);
        if (percentage > maxPercentage) {
            input.value = maxPercentage;
        }
        updateRemainingPercentage();
        updateAllShares();
    }


</script>


<style>
    .form_input {
        margin-bottom: 10px;
    }

    .remove_img {
        cursor: pointer;
        width: 25px;
        height: 25px;
    }
    .add_img2 {
        cursor: pointer;
        width: 25px;
        height: 25px;

    }
    .add_img {
        cursor: pointer;
        width: 25px;
        height: 25px;
        margin-left: -8px;
    margin-top: 2px;
    }
    .add_img1 {
        cursor: pointer;
        width: 20px;
        height: 20px;
        margin-top: -12px;
    margin-left: 2px;
    }
            .dropdown-option {
    padding: 14px 20px 12px 20px;
    cursor: pointer;
    transition: background 0.2s;
  }

  .dropdown-option:hover {
    background-color: #FAFAFA;
  }


</style>
<script>




  function toggleSelectOpen(id, isOpen) {
    const wrapper = document.getElementById(`selectWrapper-${id}`);
    if (wrapper) {
      wrapper.classList.toggle('open', isOpen);
    }
  }
</script>



