@extends('layouts.client')
@section('title', 'SNCheck')

@section('content')
<section id="checkSN" class="grow py-4 min-h-[calc(100vh-_5rem)] pt-32">
    <div class="space-y-8 mb-8 w-full">
        <div class="grid grid-cols-1 lg:grid-cols-2 items-center gap-y-10">
            <div style="background-image: url('https://img.freepik.com/premium-photo/1-geometric-background-colorful-wallpaper-abstract-4k-background-8k-background-latest-wallpaper_669273-1050.jpg')" class="block
            ml-[15%] lg:ml-[30%] w-[70%] h-[300px] lg:w-[70%] lg:h-full xl:w-[70%] xl:h-full bg-center bg-cover rounded-md">
            </div>
            <!-- <div class="block
                mx-auto lg:mx-0 w-[200px] h-[200px] md:w-[300px] md:h-[300px] lg:w-[350px] lg:h-[350px] xl:w-[450px]
                xl:h-[450px] bg-center bg-cover rounded-md">
                <img class="w-4/5 rounded-lg mr-[50px]" src="https://img.freepik.com/premium-photo/1-geometric-background-colorful-wallpaper-abstract-4k-background-8k-background-latest-wallpaper_669273-1050.jpg" alt="image">
            </div> -->
            <div class="space-y-6 h-[500px] flex flex-col justify-center items-center md:mt-8 lg:mr-[10%]">


                <div class="w-4/5 lg:w-full xl:w-4/5 bg-white rounded-lg flex flex-col p-8 p-4 rounded-md">
                    <h1 class="uppercase text-4xl font-bold text-center text-[#5278ad] mb-8">SN CHECKER</h1>
                    <div id="notification_connect" class="text-center font-bold" hidden>
                        <span class="text-red-500">Search server connection failed. Please wait and try again</span>
                        <i class="ri-loop-right-line text-[#12b512] hover:bg-[#dddddd] px-[3px] py-[3px] cursor-pointer rounded-lg" onclick="window.location.reload()"></i>
                    </div>
                    <span class="text-xs italic font-bold text-[#003a65b3]">*Some serial numbers take a long time to find. Results will be
                        updated in the search history</span>
                    <span class="text-xs italic font-bold text-[#003a65b3]">*Maximum 20 serial numbers, separated by spaces or line breaks</span>
                    <span class="text-xs italic font-bold text-[#003a65b3]">*Serial numbers ranging from 6-25 characters in length</span>
                    <textarea id="serial_numbers_input" class="border font-bold p-2 my-2 bg-white rounded-lg" autofocus style="height: 400px; color:#003a65b3;"></textarea>
                    <div class="flex justify-between text-sm">

                        <div id="summary_div" class="w-[75%]">
                        </div>

                        <div class="w-[25%] flex items-center">
                            <button id="btn_submit" disabled class="w-[100%] bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-2 rounded float-right">Check now</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="w-[90%] bg-white rounded-lg flex flex-col p-8 mx-auto my-8 shadow-xl shadow-opacity-75">
            <h1 id="title_table" class="uppercase text-3xl font-bold text-center text-[#5278ad] mb-4">CHECK REPORT SUMMARY</h1>
            <div class="text-right">

                <i id="tooltip" class="print_btn ri-printer-fill text-green-600 cursor-pointer rounded-lg" onclick="printDiv()">
                    <span id="tooltiptext">Print</span>
                </i>
                <i id="tooltip" class="send_mail_btn ri-mail-send-line text-green-600 cursor-pointer rounded-lg" onclick="sendReportSummary()">
                    <span id="tooltiptext">Send to mail</span>
                </i>
            </div>
            <div class="overflow-x-auto">
                <table id='table_summary' class="border-collapse border border-gray-300 w-full">
                    <thead class="bg-blue-100">
                        <tr>
                            <th class="h-12">#</th>
                            <th>Serial Number/Instance ID</th>
                            <th>Part Number</th>
                            <th>Country of Origin</th>
                            <th>Flag</th>
                            <th>Cover</th>
                            <th>Warranty end</th>
                            <th>End Customer</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody id="body_table"></tbody>
                </table>
            </div>
        </div>
    </div>
</section>
@include('client.sections.feature')
@include('client.pages.sn_check.modal_detail')
@endsection
@section('style')
<style>
    textarea:focus {
        outline: none !important;
        border: 1px solid #0093ff;
        box-shadow: 0 0 10px #719ECE;
    }

    #body_table tr:hover {
        background-color: rgb(214, 214, 214)
    }

    td,
    th {
        text-align: center;
        font-weight: 700;
        border: solid 1px rgb(209, 209, 209);
    }

    td {
        color: #5b5b5b;
    }

    /* Add some basic styling to the tooltip */
    #tooltip {
        position: relative;
        display: inline-block;
        cursor: pointer;
    }

    #tooltip #tooltiptext {
        visibility: hidden;
        width: 100px;
        background-color: #333;
        color: #fff;
        text-align: center;
        border-radius: 5px;
        font-size: 0.7rem;
        padding: 5px;
        position: absolute;
        z-index: 1;
        bottom: 125%;
        /* Position the tooltip above the text */
        left: 50%;
        margin-left: -60px;
        /* Center the tooltip above the text */
        opacity: 0;
        transition: opacity 0.3s;
    }

    /* Show the tooltip on hover */
    #tooltip:hover #tooltiptext {
        visibility: visible;
        opacity: 1;
    }
</style>
@endsection

@section('script')
<script src="/js/socket.io.js"></script>
<script>
    const columns = [
        "serial-number",
        "part-number",
        "country-of-origin",
        "flag",
        "cover",
        "warranty-end",
        "end-customer",
        "action"
    ];

    let debounceTimer;
    let timestamp = 0;
    let keyID = 0;
    let listSNSearch = [];
    window.resultSNCheck = [];
    window.enableSendMail = false
    const loader =
        '<div id="loader" class="w-4 h-4 border-t-2 border-blue-800 border-solid rounded-full animate-spin mx-auto"></div>';
    var socketIO = io("https://sn.danielvu.com", {
        transports: ["websocket"],
        upgrade: false,
        path: "/socket.io/",
        auth: {
            token: "Q2lzY29TeW10ZW0sNDg0OTAzNTY3NDY4OCwzYWI0ZWVmNzVlNmNiZGQwYzU1NmVjOTUwZjA4YWNkNTUzNzMzZGMyNDQ4MjM5NzQ3NGRhNjljMjU2YzA2ZWQz",
        },
    });


    socketIO.on("connect", (socket) => {
        socketIO.on("cisco-result", function(data) {
            if (data.timestamp === timestamp) {
                updateRowData(data);
                isEndCheck(data.isEnd)
            }
        });

        socketIO.on("cisco-result-db", function(data) {
            if (data.timestamp === timestamp) {
                updateRowData(data);
                isEndCheck(data.isEnd)
            }
        });
    });

    // Print report summary
    const printDiv = () => {
        // Create an iframe element
        const iframe = document.createElement('iframe');

        // Set the iframe style and hide it from view
        iframe.style.display = 'none';
        document.body.appendChild(iframe);
        const printWindow = iframe.contentWindow;
        let body = `
        <style>
            th, td, tr {
                border: 1.4px solid #ccc; /* Set explicit border for th and td */
            }
        </style>
        <table style="font-size:12px; border-collapse: collapse; margin: 0 auto;">
                        <thead>
                            <tr>
                                <th style="border: solid 1.4px gray;">No.</th>
                                <th style="border: solid 1.4px gray;">Serial Number/Instance ID</th>
                                <th style="border: solid 1.4px gray;">Part Number</th>
                                <th style="border: solid 1.4px gray;">Country of Origin</th>
                                <th style="border: solid 1.4px gray;">Flag</th>
                                <th style="border: solid 1.4px gray;">Cover</th>
                                <th style="border: solid 1.4px gray;">Warranty end</th>
                                <th style="border: solid 1.4px gray;">End Customer</th>
                            </tr>
                        </thead>`

        window.resultSNCheck.filter((i) => i.updated).forEach((item, index) => {
            body += `
                        <tr>
                            <td style="border: solid 1.4px gray;">${index+1}</td>
                            <td style="border: solid 1.4px gray;">${item._serialNumber}/${item.instanceId}</td>
                            <td style="border: solid 1.4px gray;">${item._partNumber}</td>
                            <td style="border: solid 1.4px gray; text-align:center;">${item.CountryOfOrigin}</td>
                            <td style="border: solid 1.4px gray;">${item.disabledLineFlagMsgs}</td>
                            <td style="border: solid 1.4px gray;">${item.isCovered}</td>
                            <td style="border: solid 1.4px gray; text-align:center;">${item.warrantyExpiry}</td>
                            <td style="border: solid 1.4px gray; text-align:center;">${item.endCustomer}</td>
                        </tr>
                    `
        })
        printWindow.document.write('<html><head><title>CHECK REPORT SUMMARY</title></head><body>');
        printWindow.document.write(body)
        printWindow.document.write(`</table></body></html>`);
        printWindow.document.close();
        printWindow.print();
    }

    // Print report summary
    const sendReportSummary = () => {
        if (window.enableSendMail) {
            window.enableSendMail = false
            if (typeof toastr !== 'undefined') {
                toastr.info('', 'Sending...', {
                    positionClass: "toast-bottom-right"
                });
            }
            $.ajax({
                url: "{{ route('serial-number-check.send-report-summary') }}",
                type: "POST",
                data: {
                    _token: '{{ csrf_token() }}',
                    html_content: JSON.stringify(window.resultSNCheck.filter((i) => i.updated))
                },
                success: function(response) {
                    if (response.status) {
                        if (typeof toastr !== 'undefined') {
                            toastr.success(response.message, '', {
                                positionClass: "toast-bottom-right"
                            });
                        }
                    } else {
                        if (typeof toastr !== "undefined") {
                            toastr.error(response.message);
                        }
                    }
                },
                error: function(error) {
                    if (typeof toastr !== "undefined") {
                        toastr.error(error?.responseJSON?.message);
                    }
                    console.log("Error:", error);
                    window.enableSendMail = true
                },
            });
        } else {
            if (window.resultSNCheck.length > 0 && timestamp === 0) {
                if (typeof toastr !== 'undefined') {
                    toastr.warning('The email has been sent previously', '', {
                        positionClass: "toast-bottom-right"
                    });
                }
            } else {
                if (typeof toastr !== 'undefined') {
                    toastr.warning('No data', '', {
                        positionClass: "toast-bottom-right"
                    });
                }
            }
        }
    }

    // Replace all special characters to number
    const replaceSpecialCharacters = (inputString) => {
        // Use a regular expression to match all non-alphanumeric characters
        var regex = /[^a-zA-Z0-9]/g;

        // Replace all matches with an empty string
        var resultString = inputString.replace(regex, function(match) {
            // Replace special character with its ASCII value
            return parseInt(match.charCodeAt(0)) + keyID;
        })

        return resultString;
    }

    // Get list serial number
    const getListSN = (serialNumbersValue) => {
        // Filter list data
        const listSerialNumbers = serialNumbersValue
            .replace(/\n/g, " ") // remove line break
            .replace(/,/g, " ") // remove ','
            .replace(/\s+/g, " ") // remove duplicate space
            .trim().toUpperCase()
            .split(" ")
            .filter((sn) => sn !== "") // remove serial number empty
            .filter((value, index, self) => {
                // remove duplicate serial number
                return self.indexOf(value) === index;
            });

        return listSerialNumbers;
    };

    // Initialization data
    const initData = () => {
        listSNSearch.map((sn) => {
            window.resultSNCheck.push({
                _serialNumber: sn,
                instanceId: "",
                _partNumber: "",
                CountryOfOrigin: "",
                disabledLineFlagMsgs: "",
                isCovered: "",
                warrantyExpiry: "",
                endCustomer: "",
                updated: false,
            });
        });
    };

    // Render table body when click 'Check' button
    const renderBodyTable = () => {
        let tBody = "";

        if (window.resultSNCheck.length > 0) {
            window.resultSNCheck = window.resultSNCheck.sort((a, b) => {
                const snA = a._serialNumber.toLowerCase();
                const snB = b._serialNumber.toLowerCase();

                if (snA < snB) {
                    return -1;
                } else if (snA > snB) {
                    return 1;
                } else {
                    return 0;
                }
            });

            window.resultSNCheck.map(
                (item, index) => {
                    let serialNumberID = replaceSpecialCharacters(item._serialNumber)
                    tBody += `<tr id=${
                  item.instanceId !== ""
                    ? serialNumberID + "_" + item.instanceId
                    : serialNumberID
                } ${index % 2 === 0 ? "class='bg-gray-100'":"class='bg-white'"}>
                        <td>${index + 1}</td>
                        <td class=${columns[0]}></td>
                        <td class=${columns[1]}>${
                  item._partNumber !== "" ? item._partNumber : loader
                }</td>
                        <td class=${columns[2]}>${
                  item.CountryOfOrigin !== "" ? item.CountryOfOrigin : loader
                }</td>
                        <td class=${columns[3]}>${
                  item.disabledLineFlagMsgs !== ""
                    ? item.disabledLineFlagMsgs
                    : loader
                }</td>
                        <td class=${columns[4]}>${
                  item.isCovered !== "" ? item.isCovered : loader
                }</td>
                        <td class=${columns[5]}>${
                  item.warrantyExpiry !== "" ? item.warrantyExpiry : loader
                }</td>
                        <td class=${columns[6]}>${
                  item.endCustomer !== "" ? item.endCustomer : loader
                }</td>
                <td class=${columns[7]} hidden>
                    <i id="tooltip" class="ri-bill-line text-green-600 hover:bg-[#dddddd] mx-auto cursor-pointer rounded-lg" onclick="showDetailByIndex(${index})">
                    <span id="tooltiptext">Detail</span>
                    </i>
                </td>
                <td class=${columns[7]}_temp>${loader}</td>
                    </tr>`
                }
            );
            $("#body_table").html(tBody);

            window.resultSNCheck.map((item, index) => {
                let trID = ''
                let text = ''
                let serialNumberID = replaceSpecialCharacters(item._serialNumber)
                if ($('#' + serialNumberID + "_" + item.instanceId).length > 0) {
                    trID = serialNumberID + "_" + item.instanceId
                    text = item._serialNumber + "/" + item.instanceId
                } else {
                    trID = serialNumberID
                    text = item._serialNumber
                }

                $("#" + trID + " ." + columns[0]).text(text)
            })
        } else {
            $("#body_table").html("");
        }
    };

    // Update object in array with property is empty
    const updatePropertyObjectInArray = (data) => {
        window.resultSNCheck.forEach((obj, index) => {
            // Check and update property is empty
            if (
                obj._serialNumber === data._serialNumber &&
                obj.instanceId === data.instanceId && obj._partNumber === data._partNumber
            ) {
                for (const key in obj) {
                    window.resultSNCheck[index]['updated'] = true;
                    if (obj.hasOwnProperty(key) && obj[key] === "" && data[key]) {
                        window.resultSNCheck[index][key] = data[key];
                    }
                }
            } else {

                // Update when _serialNumber exist and instanceId empty
                if (
                    obj._serialNumber === data._serialNumber && obj.instanceId === "" && window.resultSNCheck.filter((item) => item._serialNumber === data._serialNumber && item.instanceId !== "").length === 0
                ) {
                    for (const key in obj) {
                        window.resultSNCheck[index]['updated'] = true;
                        if (obj.hasOwnProperty(key) && obj[key] === "" && data[key]) {
                            window.resultSNCheck[index][key] = data[key];
                        }
                    }
                }

                // Add new row when row not exist in resultSNCheck
                if (
                    obj._serialNumber === data._serialNumber &&
                    window.resultSNCheck.filter((item) => item._serialNumber === data._serialNumber && item.instanceId === data.instanceId).length === 0 &&
                    data.instanceId !== ""
                ) {
                    window.resultSNCheck.push(data);
                }

                // Add new row when row not exist in resultSNCheck
                if (
                    obj._serialNumber === data._serialNumber &&
                    window.resultSNCheck.filter(
                        (item) =>
                        item._serialNumber === data._serialNumber &&
                        item._partNumber === data._partNumber
                    ).length === 0 && data._partNumber !== ""
                ) {
                    window.resultSNCheck.push(data);
                }
            }
        });
    };

    // Update row by data socket
    const updateRowData = (data) => {
        Array.isArray(data.data) &&
            data.data.map((row) => {
                const endCustomer = row.endCustomer;
                let customerName = "";
                let customerId = "";
                let customerCountry = "";

                if (endCustomer) {
                    if (endCustomer.name) {
                        customerName = endCustomer.name;
                    }
                    if (endCustomer.id) {
                        customerId = "(" + endCustomer.id + "),";
                    }
                    if (endCustomer.address) {
                        customerCountry = endCustomer.address?.country;
                    }
                }

                let newData = {
                    _serialNumber: row._serialNumber,
                    instanceId: row.instanceId ? row.instanceId : "",
                    _partNumber: row._partNumber ? row._partNumber : "",
                    CountryOfOrigin: row.CountryOfOrigin && !row.CountryOfOrigin.toLowerCase().includes('no data') ? row.CountryOfOrigin : "",
                    disabledLineFlagMsgs: row.disabledLineFlagMsgs?.length > 0 ? "Flagged" : "",
                    isCovered: row.isCovered ? "Yes" : "",
                    warrantyExpiry: row.warrantyExpiry ? row.warrantyExpiry : "",
                    endCustomer: (
                        customerName +
                        " " +
                        customerId +
                        " " +
                        customerCountry
                    ).trim(),
                    updated: true,
                };

                const itemCheck = window.resultSNCheck.filter(
                    (obj) => obj._serialNumber === newData._serialNumber
                );

                // Item not exists
                if (itemCheck.length === 0) {
                    window.resultSNCheck.push(newData);
                } else {
                    updatePropertyObjectInArray(newData);
                }
            });
        renderBodyTable();
    };

    // Check empty cell -> No data
    const checkTDEmpty = (list, mess) => {
        list.map((item) => {
            let serialNumberID = replaceSpecialCharacters(item._serialNumber)
            const id = item.instanceId ? serialNumberID + "_" + item.instanceId : serialNumberID
            columns.map((col) => {
                const element = $(
                    "#" + id + " ." + col
                ).html();
                if (element && element.includes('id="loader"')) {
                    $(
                        "#" + id + " ." + col
                    ).html(`<span class="text-xs text-blue-300 italic">${mess}</span>`);
                }
            });
            if ($("#" + id + " .action_temp").length > 0 && timestamp === 0) {
                $("#" + id + " .action_temp").html(`<span class="text-xs text-blue-300 italic">${mess}</span>`);
            }
        });
    };

    // Render rows not found
    const renderRowNotFound = () => {
        const listSN = listSNSearch;
        $('.action').show()
        $('.action_temp').hide()
        listSN.map((sn) => {
            if (
                window.resultSNCheck.filter(
                    (i) => i._serialNumber === sn && !i.updated
                ).length > 0
            ) {
                $(`#${replaceSpecialCharacters(sn)}`).css({
                    'background-color': 'rgb(255 219 219)'
                })
                columns.slice(1).map((col) => {
                    $(`#${replaceSpecialCharacters(sn)} .${col}`).html(
                        `<span class="text-xs text-red-700 italic">Not found</span>`
                    );
                });
            }
        });
    };

    // Update search button
    const controlButton = (status) => {
        if (status === 'enable') {
            $("#btn_submit").prop("disabled", false);
            $("#btn_submit").html("Check now");
        }
        if (status === 'disable-search') {
            $("#btn_submit").prop("disabled", true);
            $("#btn_submit").html("Check now");
        }
        if (status === 'disable-loader') {
            $("#btn_submit").prop("disabled", true);
            $("#btn_submit").html(loader);
        }
    }

    // Check isEnd when search finish
    const isEndCheck = (isEnd) => {
        if (isEnd) {
            const notFoundLength = window.resultSNCheck.filter((i) => !i.updated).length
            clearTimeout(debounceTimer);
            checkTDEmpty(window.resultSNCheck, "No data");
            renderRowNotFound();
            controlButton('enable');
            timestamp = 0;
            keyID = 0;
            if (window.resultSNCheck.length > 0) {
                window.enableSendMail = true;
            }
            $('#summary_div').html(`
                <p class="text-[#0093ff] font-bold">Number of serial number searched: ${listSNSearch.length}</p>
                <p class="text-[#27eb27] font-bold">Result(s) found: ${window.resultSNCheck.length - notFoundLength}</p>
                <p class="text-[#ff5e5e] font-bold">Not found: ${notFoundLength}</p>
                `)
        }
    }

    const handleSearch = () => {
        keyID = Math.floor(Math.random() * (999999 - 1 + 1)) + 1;
        listSNSearch = getListSN($("#serial_numbers_input").val())
        if (listSNSearch.length > 0 && listSNSearch.length <= 20) {
            timestamp = Date.now();
            window.resultSNCheck = [];
            $.ajax({
                url: "{{ route('serial-number-check.search') }}",
                type: "POST",
                data: {
                    _token: '{{ csrf_token() }}',
                    keyword: listSNSearch
                },
                success: function(response) {
                    if (response.status) {
                        if (typeof toastr !== 'undefined') {
                            toastr.info(response.message, 'Searching...', {
                                positionClass: "toast-bottom-right"
                            });

                            $('#summary_div').html('');
                            $('#serial_numbers_input').val(listSNSearch.join(' '))
                            initData();
                            renderBodyTable();
                            debounceTimer = setTimeout(() => {
                                timestamp = 0;
                                keyID = 0;
                                checkTDEmpty(window.resultSNCheck, "Timeout");
                                $('#summary_div').html(
                                    `<p class="text-orange-400 font-bold">Search time is over. Results will be updated to the search history once completed!</p>`
                                )
                                window.resultSNCheck = [];
                            }, 90000);

                            socketIO.emit("get-sn-information", {
                                checkId: (response.serial_number_check.id)
                                    .toString(),
                                timestamp: timestamp,
                                checkPages: ["ccwr", "cway", "gcta"],
                                serialNumbers: listSNSearch,
                                reCheck: 1,
                            });
                            var targetSection = $('#title_table');
                            $('html, body').animate({
                                scrollTop: targetSection.offset().top - 200
                            }, 1000);
                        }

                        if (response.user !== 'undefined') {
                            for (let column in response.user) {
                                $UPDATE_DATA_ATTR({
                                    table: 'user',
                                    column: column,
                                    text: response.user[column]
                                });
                            }
                        }


                    } else {
                        if (typeof toastr !== "undefined") {
                            toastr.error("Search failed");
                        }
                    }
                },
                error: function(error) {
                    if (typeof toastr !== "undefined") {
                        toastr.error(error?.responseJSON?.message);
                    }
                    timestamp = 0;
                    keyID = 0;
                    console.log("Error:", error);
                },
            });
        } else {
            if (listSNSearch.length > 20) {
                if (typeof toastr !== "undefined") {
                    toastr.error("Maximum 20 serial numbers.");
                }
            }

            if (listSNSearch.length === 0) {
                if (typeof toastr !== "undefined") {
                    toastr.warning('Please enter the serial you want to search!');
                }
            }
        }
    }

    window.addEventListener("load", (event) => {
        setTimeout(() => {
            if (!socketIO.connected) {
                $('#notification_connect').show()
            } else {
                // Default check button -> disable -> enable when connected
                $("#btn_submit").prop("disabled", false);
                const snSearchFromHomePage = localStorage.getItem('sn-search-from-home')
                if (snSearchFromHomePage !== null) {
                    $("#serial_numbers_input").val(snSearchFromHomePage)
                    $('#btn_submit').click();
                    localStorage.removeItem('sn-search-from-home');
                }
            }
        }, 200)
        $("#btn_submit").on("click", () => {
            window.enableSendMail = false
            if (timestamp !== 0) {
                if (confirm(
                        'Are you sure you want to start another search? The results of the current search session will be included in the search history.'
                    )) {
                    window.resultSNCheck = [];
                    timestamp = 0;
                    keyID = 0;
                    clearTimeout(debounceTimer);
                    handleSearch()
                }
            } else {
                handleSearch()
            }
        });
    });
</script>
@endsection