<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>QualityFlow - Endline</title>
    <link rel="icon" type="image/png" href="{{ asset('gplogofinal.png') }}">
    <!-- Bootstrap 5 CSS -->
    <link href="{{ asset('css/bootstrap.min.css') }}" rel="stylesheet">
    <!-- Bootstrap Icons -->
    <link rel="stylesheet" href="{{ asset('css/bootstrap-icons.css') }}">
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700;900&display=swap" rel="stylesheet">
    
    <style>
        body {
            font-family: 'Roboto', sans-serif;
            background-color: #f5f6f8; /* Light gray background */
        }
        
        /* Main card styling */
        .main-card {
            max-width: 750px;
            margin: 4rem auto;
            border: none;
            box-shadow: 0 10px 40px rgba(0,0,0,0.06); /* Soft shadow like the design */
            border-radius: 12px;
        }
        
        /* Select dropdown styling */
        .select-production {
            background-color: #fafbfc;
            border: 1px solid #e1e4e8;
            color: #6a737d;
            border-radius: 6px;
        }
        .select-production:focus {
            border-color: #2b4cc4;
            box-shadow: 0 0 0 0.25rem rgba(43, 76, 196, 0.1);
        }
        
        /* Inner profile container styling */
        .profile-container {
            background-color: #f4f6fb;
            border: 1px solid #e2e6f0;
            border-radius: 12px;
            padding: 2.5rem 2rem;
            margin-top: 1.5rem;
        }
        
        /* Circular profile image with blue ring */
        .profile-image-wrapper {
            width: 140px;
            height: 140px;
            border-radius: 50%;
            border: 4px solid #2b4cc4;
            padding: 4px; /* Space between border and image (creates the white gap) */
            background-color: white;
            box-shadow: 0 4px 12px rgba(0,0,0,0.08); /* slight shadow under avatar */
        }
        
        .profile-image {
            width: 100%;
            height: 100%;
            border-radius: 50%;
            object-fit: cover;
        }
        
        /* Badges styling */
        .badge-verified {
            background-color: #ecfdf3;
            color: #12b76a;
            border: 1px solid #d1fadf;
            font-weight: 700;
            font-size: 0.65rem;
            letter-spacing: 0.5px;
            text-transform: uppercase;
        }
        
        .badge-grade {
            background-color: #eff4ff;
            color: #2b4cc4;
            border: 1px solid #d1e0ff;
            font-weight: 700;
            font-size: 0.65rem;
            letter-spacing: 0.5px;
            text-transform: uppercase;
        }
        
        .badge-dept {
            background-color: #f8f9fa;
            color: #6c757d;
            border: 1px solid #e9ecef;
            font-weight: 700;
            font-size: 0.65rem;
            letter-spacing: 0.5px;
            text-transform: uppercase;
        }
        
        /* Start Inspection Button */
        .btn-start-inspection {
            background-color: #2b4cc4;
            color: white;
            font-weight: 600;
            padding: 0.8rem 2rem;
            border-radius: 8px;
            border: none;
            box-shadow: 0 4px 10px rgba(43, 76, 196, 0.2);
            transition: all 0.2s;
            font-size: 1rem;
        }
        
        .btn-start-inspection:hover {
            background-color: #223c9e;
            color: white;
            transform: translateY(-1px);
            box-shadow: 0 6px 15px rgba(43, 76, 196, 0.3);
        }
        
        /* Rescan ID text */
        .wrong-profile-text {
            font-size: 0.65rem;
            color: #8c98a4;
            font-weight: 700;
            letter-spacing: 0.5px;
        }

        /* Custom Dropdown Styling */
        .custom-select-btn {
            background-color: #fafbfc !important;
            border: 1px solid #e1e4e8;
            color: #495057;
            border-radius: 6px;
            width: 100%;
            height: 3.5rem;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        
        .custom-dropdown-menu {
            position: absolute;
            top: 100%;
            left: 0;
            width: 100%;
            margin-top: 5px;
            background-color: white;
            border: 1px solid #e2e6f0;
            border-radius: 8px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.08);
            z-index: 1000;
            display: none;
        }
        
        .custom-dropdown-menu.show {
            display: block;
        }

        .grid-container {
            display: grid;
            grid-template-columns: repeat(12, 1fr); /* 12 columns for mobile */
            gap: 5px;
            max-height: 250px;
            overflow-y: auto;
        }
        
        @media (min-width: 768px) {
            .grid-container {
                grid-template-columns: repeat(15, 1fr); /* 15 columns for desktop */
            }
        }

        .line-item {
            aspect-ratio: 1;
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: #f5f6f8;
            border-radius: 4px;
            font-size: 0.85rem;
            font-weight: 600;
            color: #6a737d;
            cursor: pointer;
            user-select: none;
            transition: all 0.2s;
        }

        .line-item:hover {
            background-color: #e2e6f0;
        }

        .line-item.selected {
            background-color: #2b4cc4;
            color: white;
        }

        .dropdown-footer {
            border-top: 1px solid #e2e6f0;
            padding: 1rem;
            background-color: #fcfcfd;
            border-bottom-left-radius: 8px;
            border-bottom-right-radius: 8px;
        }

        .selected-count {
            font-size: 0.70rem;
            font-weight: 700;
            color: #6c757d;
            letter-spacing: 0.8px;
            text-transform: uppercase;
        }

        .clear-all-btn {
            font-size: 0.70rem;
            font-weight: 800;
            color: #24292e;
            padding: 0;
            letter-spacing: 0.8px;
            text-transform: uppercase;
        }
        
        .clear-all-btn:hover {
            color: #2b4cc4;
        }

        .top-badge {
            background-color: #2b4cc4;
            color: white;
            border-radius: 20px;
            padding: 0.4rem 1rem;
            font-size: 0.75rem;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            text-transform: uppercase;
            box-shadow: 0 4px 6px rgba(43, 76, 196, 0.2);
        }

        /* Hide specific navbar elements for this view */
        #navScanNext {
            display: none !important;
        }

        .line-card{
            aspect-ratio: 1;
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: #f5f6f8;
            border-radius: 8px;
            font-size: 0.75rem;
            font-weight: 600;
            color: #6a737d;
            cursor: pointer;
            user-select: none;
            transition: all 0.2s;
            border: 1px solid transparent;
        }

        .line-card:hover{
            background-color: #e2e6f0;
            transform: scale(1.05);
        }

        .line-selected{
        border:2px solid #2b4cc4;
        background:#eff4ff;
        color: #2b4cc4;
        }

        #wrongcheckerCardMetaText:hover{
            text-decoration: underline;
            cursor: pointer;
        }

        /* Custom Red Tooltip */
        .scanner-tooltip-container {
            position: relative;
        }
        .custom-tooltip-red {
            position: absolute;
            bottom: 120%;
            left: 50%;
            transform: translateX(-50%);
            background: white;
            color: #d32f2f; /* Premium Red */
            padding: 6px 12px;
            border-radius: 6px;
            border: 1px solid #d32f2f;
            font-size: 0.8rem;
            font-weight: 600;
            white-space: nowrap;
            display: none;
            z-index: 1050;
            box-shadow: 0 4px 12px rgba(211, 47, 47, 0.15);
        }
        .custom-tooltip-red::after {
            content: "";
            position: absolute;
            top: 100%;
            left: 50%;
            margin-left: -5px;
            border-width: 5px;
            border-style: solid;
            border-color: #d32f2f transparent transparent transparent;
        }
        #openCheckerScannerBtnDiv:hover .custom-tooltip-red {
            display: block;
        }
    </style>
</head>
<body>

    <!-- Injecting the navigation bar blade components -->
    @include('Quality.Endline_nav')

    <!-- Main Content Application Region -->
    <div class="container">
        <div class="card main-card">
            <div class="card-body p-2 p-md-1">

                <div class="container-fluid mt-4">

                    <div class="text-center mb-4">
                        <h3 class="fw-bold">Endline Inspection - Checker Login</h3>
                    </div>


                        <div class="grid-container mb-4" id="lineCards">

                            @forelse($lines as $line)

                           

                            <div class="line-card shadow-sm"
                                data-group="{{ $line->Zone }}"
                                data-cc="-"
                                data-line="{{ $line->Line_No }}"
                                data-line_no="{{ $line->Line_No }}"
                                data-unit="10">
                                {{ $line->Line_No }}
                            </div>

                            @empty
                            <div class="col-12 text-center py-4 text-muted w-100" style="grid-column: 1 / -1;">
                                <i class="bi bi-info-circle me-2"></i> No lines found
                            </div>
                            @endforelse

                        </div>

                    <hr>

                    <div class="row justify-content-center my-4">

                        <div class="col-12 col-md-8 text-center">

                        <h5>Selected Line</h5>

                        <div class="alert alert-success" id="selectedLine">
                        Please Select Line
                        </div>

                        <input type="hidden" id="checker_scan">

                        <div id="openCheckerScannerBtnDiv" class="d-grid gap-2 scanner-tooltip-container">
                            <div id="scannerTooltip" class="custom-tooltip-red">Select Line group to Scan</div>
                            <button type="button" class="btn btn-primary" id="openCheckerScannerBtn" disabled>Scan</button>
                        </div>

                        <div class="my-3 w-100 d-none" id="checkerInfoCard">
                            <div class="profile-container w-100 d-flex flex-column flex-md-row align-items-center justify-content-center gap-4 gap-md-5">
                                <div class="profile-image-wrapper flex-shrink-0">
                                    <img src="https://images.unsplash.com/photo-1542601906990-b4d3fb778b09?ixlib=rb-4.0.3&auto=format&fit=crop&w=300&q=80" alt="Checker Profile" class="profile-image">
                                </div>

                                <div class="d-flex flex-column align-items-center align-items-md-start w-100">
                                    <h2 class="fw-bold mb-3 text-dark fs-3 letter-spacing-tight" id="checkerCardName">-</h2>

                                    <div class="d-flex flex-wrap gap-2 justify-content-center justify-content-md-start mb-4">
                                        <span class="badge badge-verified rounded-pill px-3 py-2">
                                            VERIFIED CHECKER
                                        </span>
                                        <span class="badge badge-grade rounded-pill px-3 py-2">
                                            GRADE A+
                                        </span>
                                        <span class="badge badge-dept rounded-pill px-3 py-2" id="checkerDeptBadge">
                                            DEPT: -
                                        </span>
                                    </div>

                                    <button id="startInspectionBtn" type="button" class="btn btn-start-inspection w-100 mb-3 d-flex align-items-center justify-content-center gap-2" disabled>
                                        <i class="bi bi-box-arrow-in-right fs-5"></i>
                                        START INSPECTION
                                    </button>

                                    <div class="text-center w-100 mt-2" id="checkerCardMeta">
                                        <span class="wrong-profile-text"></span>
                                    </div>

                                    <div class="text-center w-100 mt-2 d-none" id="wrongcheckerCardMeta">
                                        <span id="wrongcheckerCardMetaText" class="wrong-profile-text text-primary">WRONG PROFILE? RESCAN ID CARD</span>
                                    </div>  
                                </div>
                            </div>
                        </div>

                        <div class="d-none">
                            <div id="checkerScannedCode">-</div>
                            <div id="checkerDetails">Please scan checker card</div>
                        </div>

                        </div>

                    </div>

                </div>           

            </div>
        </div>
    </div>

    <div class="modal fade" id="checkerScannerModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Scan Barcode</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div id="checkerScannerError" class="alert alert-danger d-none mb-3"></div>
                    <div id="checkerScannerRegion" style="width: 100%;"></div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="garmentbarcodescanner" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Scan Barcode</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div id="garmentbarcodescannerError" class="alert alert-danger d-none mb-3"></div>
                    <div id="garmentbarcodescannerRegion" style="width: 100%;">
                        <input type="text" id="garmentbarcodescannerInput" maxlength="24" minlength="15" class="form-control" autocomplete="off" placeholder="Scan Barcode">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary d-none" id="garmentbarcodescannerBtn">Okay</button>
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>

    </div>

    <!-- External Script Dependencies (jQuery & Bootstrap) -->
    <!-- jQuery Core -->
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <!-- Bootstrap 5 JS with Popper.js -->
    <script src="{{ asset('js/bootstrap.bundle.min.js') }}"></script>
    <script src="https://unpkg.com/html5-qrcode@2.3.8/html5-qrcode.min.js"></script>
    
    <script>
        $(document).ready(function() {
       //$("#unitSelect").removeClass('d-none');
       $('#unitSelectDiv').removeClass("d-none");
    const lines = @js($lines);
    console.log("Lines Data:", lines);

     // ── Fetch & populate Units ──
        function fetchUnitDetails() {
            $.ajax({
                url: '/gut_unitdetails',
                method: 'GET',
                success: function(response) {
                    if (response.success && response.data) {
                        let $unitSelect = $('#unitSelect');
                        // Remove existing options except the first one (All)
                        $unitSelect.find('option:not(:first)').remove();
                        
                        response.data.forEach(unit => {
                            $unitSelect.append(`<option value="${unit.Unitcode}">${unit.Unit_Lookup}</option>`);
                        });

                        // Set T-W-I as default
                        $unitSelect.find('option').filter(function() {
                            return $(this).text() === "T-W-I";
                        }).prop('selected', true);
                        
                        $unitSelect.trigger('change');
                    }
                },
                error: function(err) {
                    console.error("Error fetching units:", err);
                }
            });
        }

        // Initialize units
        fetchUnitDetails();


        $('#unitSelect').on('change', function() {
        let unit = $(this).val();
        
        $.ajax({
            url: '/gut_linedetails',
            method: 'GET',
            data: { unit: unit },
            success: function(response) {
                if (response.success && response.data) {
                    let $lineCards = $('#lineCards');
                    $lineCards.empty();
                    
                    if (response.data.length === 0) {
                        $lineCards.append(`
                            <div class="col-12 text-center py-4 text-muted w-100" style="grid-column: 1 / -1;">
                                <i class="bi bi-info-circle me-2"></i> No lines found
                            </div>
                        `);
                    } else {
                        response.data.forEach(line => {
                            $lineCards.append(`
                                <div class="line-card shadow-sm"
                                    data-group="${line.Zone}"
                                    data-cc="-"
                                    data-line="${line.Line_No}"
                                    data-line_no="${line.Line_No}"
                                    data-unit="${unit}">
                                    ${line.Line_No}
                                </div>
                            `);
                        });
                    }

                    // Reset current selection state
                    selectedLine = '';
                    $('.line-card').removeClass('line-selected');
                    $('#selectedLine').html('Please Select Line');
                    $('#openCheckerScannerBtn').prop('disabled', true);
                    
                    // Re-add tooltip if missing
                    if ($('#scannerTooltip').length === 0) {
                        $('#openCheckerScannerBtnDiv').prepend('<div id="scannerTooltip" class="custom-tooltip-red">Select Line group to Scan</div>');
                    }
                    
                    $('#navLineNo').text('-');
                    $('#navGroupbatch').text('-');
                    
                    try {
                        sessionStorage.removeItem('endline_line_no');
                        sessionStorage.removeItem('endline_group');
                        sessionStorage.setItem('endline_unit', String(unit));
                        sessionStorage.removeItem('endline_outline');
                    } catch (e) {}
                }
            },
            error: function(err) {
                console.error("Error fetching lines:", err);
            }
        });
    });
    
    // If you want to log each line individually:
    lines.forEach(line => {
        console.log("Single Line:", line);
    });

        var selectedLine = '';
        const preselectedGroupFromSession = @js(session('endline_groupbatch.name'));

        let checkerHtml5Qrcode = null;
        const checkerScannerModalEl = document.getElementById('checkerScannerModal');
        const checkerScannerModal = checkerScannerModalEl ? new bootstrap.Modal(checkerScannerModalEl) : null;

        $('#garmentIdDiv').addClass('d-none');
        $('#logoutbtn').addClass('d-none');

		if (preselectedGroupFromSession) {
            const $card = $('.line-card').filter(function() {
                return String($(this).data('group')) === String(preselectedGroupFromSession);
            }).first();

            if ($card.length) {
                var group = $card.data('group');
                var unit = $card.data('unit');
                var cc = $card.data('cc');
                var line = $card.data('line');
                var outline = $card.data('line_no');

                $('.line-card').removeClass('line-selected');
                $card.addClass('line-selected');

                selectedLine = line;

                try {
                    sessionStorage.setItem('endline_line_no', String(line));
                    sessionStorage.setItem('endline_group', String(group));
                    sessionStorage.setItem('endline_unit', String(unit));
                    sessionStorage.setItem('endline_outline', String(outline));
                } catch (e) {}

                $('#navLineNo').text(line);
                $('#navGroupbatch').text(group);
                $('#linedisplaydiv').show();

                $('#selectedLine').html(
                    // "Group : "+group+" | CC : "+cc+" | Line : "+line
                    "Line : "+line
                );
                $('#openCheckerScannerBtn').prop('disabled', false);
                $('#scannerTooltip').remove();
            }
        }

        $('#openCheckerScannerBtn').on('click', function() {
          $('#garmentbarcodescanner').modal('show');
        });

        // Auto-trigger when length is 15 or 24
        $('#garmentbarcodescannerInput').on('input', function() {
            var value = $(this).val();
            if (value.length === 15 || value.length === 24) {
                handleCheckerScannedCode(value);
                $('#garmentbarcodescanner').modal('hide');
            }
        });

        // Modal focus and input reset logic
        $('#garmentbarcodescanner').on('shown.bs.modal', function() {
            $('#garmentbarcodescannerInput').val('').focus();
        });





        let barcodeBuffer = '';
        let barcodeTimeout;

        // $('#openCheckerScannerBtn').on('click', function() {
        //     $('#garmentbarcodescanner').modal('show');
        // });

        // $('#garmentbarcodescanner').on('shown.bs.modal', function () {
        //     barcodeBuffer = '';
        //     $(document).on('keypress.garmentBarcode', function(e) {
        //         if (e.which == 13) { // Enter key
        //             e.preventDefault();
        //             if (barcodeBuffer.length > 0) {
        //                 $('#garmentbarcodescanner').modal('hide');
        //                 handleCheckerScannedCode(barcodeBuffer);
        //                 barcodeBuffer = '';
        //             }
        //         } else {
        //             barcodeBuffer += String.fromCharCode(e.which);
        //             clearTimeout(barcodeTimeout);
        //             barcodeTimeout = setTimeout(function() {
        //                 barcodeBuffer = '';
        //             }, 500); // Clear buffer if pause is longer than 500ms
        //         }
        //         $('#garmentbarcodescannerRegion').text(barcodeBuffer);
        //     });
        // });

        // $('#garmentbarcodescanner').on('hidden.bs.modal', function () {
        //     $(document).off('keypress.garmentBarcode');
        //     barcodeBuffer = '';
        //     clearTimeout(barcodeTimeout);
        // });

        

        

        function setCheckerScannerError(message) {
            const $err = $('#checkerScannerError');
            if (!message) {
                $err.addClass('d-none').text('');
                return;
            }
            $err.removeClass('d-none').text(message);
        }

        async function stopCheckerScanner() {
            try {
                if (checkerHtml5Qrcode) {
                    try {
                        await checkerHtml5Qrcode.stop();
                    } catch (e) {
                    }
                    try {
                        await checkerHtml5Qrcode.clear();
                    } catch (e) {
                    }
                }
            } catch (e) {
            } finally {
                checkerHtml5Qrcode = null;
                $('#checkerScannerRegion').empty();
            }
        }

        async function startCheckerScanner() {
            setCheckerScannerError('');

            if (!checkerHtml5Qrcode) {
                checkerHtml5Qrcode = new Html5Qrcode('checkerScannerRegion');
            }

            try {
                const config = {
                    fps: 10,
                    qrbox: { width: 300, height: 180 },
                    disableFlip: false
                };

                await checkerHtml5Qrcode.start(
                    { facingMode: 'environment' },
                    config,
                    function(decodedText) {
                        handleCheckerScannedCode(decodedText);
                        if (checkerScannerModal) {
                            checkerScannerModal.hide();
                        }
                    },
                    function() {}
                );
            } catch (e) {
                setCheckerScannerError('Unable to start camera scanner. Please allow camera permission and use HTTPS (or localhost).');
                await stopCheckerScanner();
            }
        }

        function extractEmployeeIdFromCheckerCode(raw) {
            if (!raw) return '';
            let value = String(raw).trim();
            if (!value) return '';

            if (value.startsWith('0')) {
                value = value.slice(1);
            }

            if (/[a-zA-Z]$/.test(value)) {
                value = value.slice(0, -1);
            }

            value = value.replace(/\D/g, '');

            if (value.length >= 5) {
                value = value.slice(-5);
            }

            return value;
        }

        function renderCheckerDetailsLoading(employeeId) {
            const $el = $('#checkerDetails');
            if ($el.length === 0) return;
            $el.text('Fetching checker details for Employee ID: ' + employeeId + ' ...');

            $('#checkerCardName').text('-');
            $('#checkerDeptBadge').text('DEPT: -');
            $('#checkerCardMeta').text('Fetching details for Employee ID: ' + employeeId + ' ...');
            $('#checkerInfoCard').removeClass('d-none');
            $('#startInspectionBtn').prop('disabled', true);
        }

        function renderCheckerDetailsError(message) {
            const $el = $('#checkerDetails');
            if ($el.length === 0) return;
            $el.text(message);

            $('#checkerCardName').text('-');
            $('#checkerDeptBadge').text('DEPT: -');
            $('#checkerCardMeta').text(message);
            $('#checkerInfoCard').removeClass('d-none');
            $('#startInspectionBtn').prop('disabled', true);
        }

       function handleCheckerScannedCode(rawCode, lineNo = '', outline = '', groupbatch = '') {
            const $scannedEl = $('#checkerScannedCode');
            
          
 
            if ($scannedEl.length > 0) {
                $scannedEl.text(rawCode);
            }
            $('#checker_scan').val(rawCode);
            let employeeId = '';
            if(rawCode.length == 15){
                employeeId = extractEmployeeIdFromCheckerCode(rawCode);
            }
            else{
                employeeId = rawCode;
            }
            
            if (!employeeId) {
                renderCheckerDetailsError('Invalid code scanned.');
                return;
            }

            renderCheckerDetailsLoading(employeeId);

            $.ajax({
                url: "/endline/checker_details",
                method: 'GET',
                dataType: 'json',
                data: { 
                    employee_id: employeeId,
                    line_no: sessionStorage.getItem('emp_login_lineno'),
                    outline: $('#unitSelect').val(),
                    groupbatch: groupbatch
                },
                success: function(resp) {
                    if (!resp || resp.success !== true) {
                        renderCheckerDetailsError((resp && resp.message) ? resp.message : 'Checker not found');
                        return;
                    }

                    const emp_id = resp.data && resp.data.employee_id ? resp.data.employee_id : null;
                    const name = resp.data && resp.data.name ? resp.data.name : '-';
                    const dept = resp.data && resp.data.department ? resp.data.department : '-';
                    const $el = $('#checkerDetails');
                    if ($el.length > 0) {
                        $el.text('Emp ID: ' + employeeId + ' | Name: ' + name + ' | Dept: ' + dept);
                    }

                    

                    $('#checkerCardName').text(name);
                    $('#checkerDeptBadge').text('DEPT: ' + dept);
                    $('#checkerCardMeta').text('');
                    $('#checkerInfoCard').removeClass('d-none');
                    $('#startInspectionBtn').prop('disabled', false);
                    $('#navCheckerName').text(name);

                    if (groupbatch) {
                        $('#navGroupbatch').text(groupbatch);
                    }
                    if (lineNo) {
                        $('#navLineNo').text(lineNo);
                        $('#linedisplaydiv').show();
                    }
                    
                    // Save to sessionStorage
                    sessionStorage.setItem('emp_id', String(emp_id));
                    console.log('emp_id', emp_id);
                    sessionStorage.setItem('endline_checker_name', name);
                    
                    // Prefer existing unit, or take from response
                    const currentUnit = sessionStorage.getItem('endline_unit');
                    if (!currentUnit || currentUnit === 'undefined') {
                        sessionStorage.setItem('endline_unit', resp.data && resp.data.unit_code ? resp.data.unit_code : '');
                    }
                    $('#openCheckerScannerBtnDiv').addClass('d-none');
                    $('#wrongcheckerCardMeta').removeClass('d-none');

                     // Auto-scroll to checkerInfoCard
                    setTimeout(function() {
                        document.getElementById('checkerInfoCard').scrollIntoView({ behavior: 'smooth', block: 'start' });
                    }, 100);
                    $('#startInspectionBtn').trigger('click');
                },
                error: function() {
                    renderCheckerDetailsError('Failed to fetch checker details.');
                }
            });

            // Retrieve unit from the selected line card
            const unit = $('.line-selected').data('unit');
            if (unit) {
                sessionStorage.setItem('endline_unit', unit);
            }
            console.log('sessionunit', sessionStorage.getItem('endline_unit'));
        }

        $('#wrongcheckerCardMetaText').on('click', function() {
            $('#openCheckerScannerBtnDiv').removeClass('d-none');
            $('#checkerInfoCard').addClass('d-none');
        });

        // $('#openCheckerScannerBtn').on('click', function() {
        //     if (checkerScannerModal) {
        //         checkerScannerModal.show();
        //     }
        // });

        if (checkerScannerModalEl) {
            checkerScannerModalEl.addEventListener('shown.bs.modal', function() {
                startCheckerScanner();
            });

            checkerScannerModalEl.addEventListener('hidden.bs.modal', function() {
                stopCheckerScanner();
            });
        }

        $('#startInspectionBtn').on('click', function() {
            window.location.href = "{{ route('endline.linetable') }}";
        });

        $('#lineCards').on('click', '.line-card', function(){
            var group = $(this).data('group');
            var unit = $(this).data('unit');
            var cc = $(this).data('cc');
            var line = $(this).data('line');
            var outline = $(this).data('line_no');
            sessionStorage.setItem('emp_login_lineno', String(line));

            $('.line-card').removeClass('line-selected');
            $(this).addClass('line-selected');

            console.log('outline', outline);
            console.log('line', line);

            selectedLine = line;
            try {
                sessionStorage.setItem('endline_line_no', String(line));
                sessionStorage.setItem('endline_group', String(group));
                sessionStorage.setItem('endline_unit', String(unit));
                sessionStorage.setItem('endline_outline', String(outline));
              //  sessionStorage.setItem('endline_groupbatch', String(groupbatch));
            } catch (e) {}

            $('#navLineNo').text(line);
            $('#navGroupbatch').text(group);
            $('#linedisplaydiv').show();

            $('#selectedLine').html(
            // "Group : "+group+" | CC : "+cc+" | Line : "+line
            "Line : "+line
            );

            $('#openCheckerScannerBtn').prop('disabled', false);
            $('#scannerTooltip').remove();

            if($('#navCheckerName').text() == '-'){
                $('#garmentbarcodescanner').modal('show');
                $('#garmentbarcodescannerBtn').off('click').on('click', function() {
                    handleCheckerScannedCode($('#garmentbarcodescannerInput').val(), line, outline, group);
                  
                    $('#garmentbarcodescanner').modal('hide');
                });
                return;
            }
        });
            console.log("Endline interface initialized.");

            // Finalized Start Inspection action
            $('#startInspectionBtn').on('click', function() {
                window.location.href = "{{ route('endline.selection') }}";
            });
        });
    </script>
</body>
</html>
