<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>QualityFlow - Endline Selection</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">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css">
    
    <style>
        body {
            font-family: 'Roboto', sans-serif;
            background-color: #f5f6f8; /* Light gray background */
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }

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

        /* Top info pills container */
        .info-pills-container {
            display: flex;
            justify-content: center;
            flex-wrap: wrap;
            gap: 1rem;
            margin: 1rem 0;
        }

        .info-pill {
            background-color: white;
            border: 1px solid #e1e4e8;
            border-radius: 20px;
            padding: 0.4rem 1.2rem;
            font-size: 0.75rem;
            font-weight: 700;
            color: #6a737d;
            letter-spacing: 0.8px;
            text-transform: uppercase;
            display: flex;
            align-items: center;
            gap: 0.5rem;
            box-shadow: 0 1px 3px rgba(0,0,0,0.02);
        }

        .info-pill i {
            color: #2b4cc4;
            font-size: 0.9rem;
        }

        .defect-list-wrapper {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 100%;
            gap: 0.5rem;
            padding: 0.5rem 1.2rem;
        }

        .defect-label-wrapper {
            display: flex;
            align-items: flex-start;
            gap: 0.5rem;
            flex-shrink: 0;
            white-space: nowrap;
        }

        .defect-label-wrapper i {
            color: #dc2626;
        }

        .defect-content {
            line-height: 1.5;
            text-align: left;
            word-break: break-word;
            margin-left: 0.5rem;
            color: #dc2626;
        }

        /* Large selection cards container */
        .selection-cards-container {
            display: flex;
            justify-content: center;
            gap: 2rem;
            max-width: 1800px;
            flex-grow: 1;
            padding: 0 1rem 3rem 1rem;
            flex-wrap: wrap; /* allow wrapping on smaller screens */
        }

        /* Shared Card Styling */
        .selection-card {
            flex: 1;
            min-width: 300px;
            max-width: 800px;
            border-radius: 24px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 4rem 2rem;
            cursor: pointer;
            transition: transform 0.2s, box-shadow 0.2s;
            text-decoration: none;
        }
        
        /* Pass Card Specifics */
        .card-pass {
            background-color: #f0fdf4; /* Light green tint */
            border: 4px solid #bbf7d0; /* Muted green border */
        }

        .card-pass:hover {
            transform: translateY(-5px);
            box-shadow: 0 15px 35px rgba(22, 163, 74, 0.15);
            border-color: #86efac;
        }

        .icon-pass-wrapper {
            background-color: #16a34a; /* Solid green */
            width: 120px;
            height: 120px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 2rem;
            box-shadow: 0 10px 25px rgba(22, 163, 74, 0.3);
        }

        .title-pass {
            color: #16a34a;
            font-size: 3.5rem;
            font-weight: 900;
            margin: 0;
            letter-spacing: -1px;
        }

        .subtitle-pass {
            color: #22c55e;
            font-size: 0.9rem;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 1px;
            margin-top: 0.5rem;
        }

        /* Defective Card Specifics */
        .card-defective {
            background-color: #fef2f2; /* Light red tint */
            border: 4px solid #fecaca; /* Muted red border */
        }

        .card-defective:hover {
            transform: translateY(-5px);
            box-shadow: 0 15px 35px rgba(220, 38, 38, 0.15);
            border-color: #fca5a5;
        }

        .icon-defective-wrapper {
            background-color: #dc2626; /* Solid red */
            width: 120px;
            height: 120px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 2rem;
            box-shadow: 0 10px 25px rgba(220, 38, 38, 0.3);
        }

        .title-defective {
            color: #dc2626;
            font-size: 3.5rem;
            font-weight: 900;
            margin: 0;
            letter-spacing: -1px;
        }

        .subtitle-defective {
            color: #ef4444;
            font-size: 0.9rem;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 1px;
            margin-top: 0.5rem;
        }

        /* Icons inside the circles */
        .circle-icon {
            color: white;
            font-size: 4.5rem;
        }

        /* Custom style for RFID scan success */
        .toast-rfid-success {
            background-color: #FFC107 !important; /* Yellow */
            color: #000000 !important;            /* Black text for readability */
        }

        /* Optional: Makes the little icon black too */
        .toast-rfid-success .toast-message {
            color: #000000 !important;
        }

    </style>
</head>
<body>

    @php
        $emp_checker = session('endline_checker');
        $emp_id_from_session = $emp_checker ? $emp_checker['employee_id'] : '';
        $unit_from_session = $emp_checker ? $emp_checker['unit_code'] : '';
        $lineNo = session('endline_lineNo');
    @endphp

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

    <!-- RFID Input Card -->
    <div class="container mt-4 d-flex justify-content-center">
        <div id="rfidinputcard" class="card shadow-sm border-0 rounded-4 w-100" style="max-width: 400px; background-color: white;">
            <div class="card-body p-4 text-center">
                <label for="garmentId" class="form-label fw-bold" style="color: #6a737d; letter-spacing: 1px;"><i class="bi bi-upc-scan me-2"></i>SCAN RFID</label>
                <div id="garmentIdDiv">
                    <input type="text" id="garmentId" class="form-control form-control-lg text-center mt-2" maxlength="24"  style="border-radius: 12px; border: 2px solid #e1e4e8; font-weight: 500;" placeholder="Enter RFID" autocomplete="off" autofocus>
                </div>
            </div>
        </div>
    </div>

    <!-- Info Pills -->
    <div id="infoPills" class="info-pills-container d-none">
        <div class="info-pill d-none">
            <i class="bi bi-hash"></i>
            ID: <span id="info_id" class="ms-1"></span>
        </div>
        <!-- <div class="info-pill">
            <i class="bi bi-hash"></i>
            ID: GARMENT-9405
        </div> -->
        <div class="info-pill">
            <i class="bi bi-boxes"></i>
            CC: <span id="info_cc" class="ms-1"></span>
        </div>
        <!-- <div class="info-pill">
            <i class="bi bi-boxes"></i>
            CC: 114227
        </div> -->
        <div class="info-pill">
            <i class="bi bi-palette"></i>
            COLOR: <span id="info_color" class="ms-1"></span>
        </div>
        <!-- <div class="info-pill">
            <i class="bi bi-palette"></i>
            COLOR: PURPLE
        </div> -->
        <div class="info-pill">
            <i class="bi bi-tag"></i>
            MODEL: <span id="info_model" class="ms-1"></span>
        </div>
        <!-- <div class="info-pill">
            <i class="bi bi-tag"></i>
            MODEL: 8919663-PURPLE
        </div> -->
        <div class="info-pill">
            <i class="bi bi-tag"></i>
            SIZE: <span id="info_size" class="ms-1"></span>
        </div>
        <div class="info-pill">
            <i class="bi bi-hash"></i>
            BUNDLE_NO: <span id="info_bundle_no" class="ms-1"></span>
        </div>
        <div class="info-pill">
            <i class="bi bi-box"></i>
            BUNDLE: <span id="info_bundle" class="ms-1"></span>
        </div>
        <div class="defect-list-wrapper mx-5 d-none">
            <div class="defect-label-wrapper">
                <i class="bi bi-list"></i>
                <span class="fw-bold">DEFECT LIST(Rework):</span>
            </div>
            <span id="info_defect_list" class="defect-content"></span>
        </div>
    </div>

    <!-- Selection Cards -->
    <div id="selectionCardsContainer" class="selection-cards-container d-none">
        
        <!-- Pass Card -->
        <a href="{{ route('endline.linetable') }}" id="passCard" class="selection-card card-pass">
            <div class="icon-pass-wrapper">
                <i class="bi bi-check-circle circle-icon"></i>
            </div>
            <h1 class="title-pass">PASS</h1>
            <span class="subtitle-pass">NO DEFECTS FOUND</span>
        </a>

        <!-- Defective Card -->
        <a href="{{ route('endline.defectselection') }}" id="defectiveCard" 
        class="selection-card card-defective">
            <div class="icon-defective-wrapper">
                <i class="bi bi-x-lg circle-icon" style="font-size: 4rem;"></i>
            </div>
            <h1 class="title-defective">DEFECTIVE</h1>
            <span class="subtitle-defective">LOG ISSUES FOUND</span>
        </a>

    </div>

    <!-- External Script Dependencies (jQuery & Bootstrap) -->
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
    <script src="{{ asset('js/bootstrap.bundle.min.js') }}"></script>
    
    <script>
        $(document).ready(function() {
            console.log("Endline Selection page initialized.");
            $('#homebtn').removeClass('d-none');

            $("#garmentId").val('').focus();

            //$("#selectionCardsContainer").hide();
            //$("#garmentId").addClass("d-none");
           // $("#infoPills").addClass("d-none");

           

            var Ean_no = '';
            
            $('#garmentId').on('input', function() {
                
                var garmentId = $(this).val();
                var lineNo = sessionStorage.getItem('endline_outline') || "{{ $lineNo }}";
                
                var jsUnit = sessionStorage.getItem('endline_unit');
                var serverUnit = "{{ $unit_from_session }}";
                var unitno = jsUnit ? jsUnit : serverUnit;
                
                if (unitno && !jsUnit) {
                    sessionStorage.setItem('endline_unit', unitno);
                }

                
                console.log(unitno);
                if (garmentId.length != 24) {
                    //toastr.error("Please enter a valid RFID");
                    return;
                }
                // Trigger only when exactly 24 characters are reached
                if (garmentId.length === 24) {
                    
                    $.ajax({
                        url: '/convert-rfid-prod', // Updated Laravel route
                        type: 'GET',
                        data: {
                            tagID: garmentId,
                            unitno: unitno,
                            lineNo: lineNo
                        },
                        success: function(response) {
                            console.log("Data retrieved for: " + garmentId);

                            if(response.data.bundle.length === 0) {
                                toastr.error("Mismatch RFID No Bundle Data");
                                return;
                            }
                            
                            if(response.status === 'ok' && response.data) {
                                $("#infoPills").removeClass("d-none");
                            
                                $('#info_id').text(garmentId);
                                $('#info_cc').text(response.data.IMMAN);
                                $('#info_color').text(response.data.color);
                                $('#info_model').text(response.data.model);
                                $('#info_size').text(response.data.size);
                                if (response.data.bundle && response.data.bundle.length > 0) {
                                    let b = response.data.bundle[0];
                                    let iss = parseInt(b.Iss_Qty) || 0;
                                    let bal = parseInt(b.Bal_Qty) || 0;
                                    $('#info_bundle').html(`<span class="text-success fw-bold">${iss}</span>/${iss + bal}`);
                                } else {
                                    $('#info_bundle').text('N/A');
                                }
                                $('#info_bundle_no').text(response.data.bundle[0].Bundle_No);
                                Ean_no = response.data.Eancode;
                                console.log('Ean_no', Ean_no);

                                
                                
                                $("#selectionCardsContainer").removeClass('d-none');
                                $("#rfidinputcard").addClass('d-none');
                                //toastr.success(response.message);

                            
                                
                            }
                            
                            // OPTIONAL: Clear the input so the next 24-char scan can start fresh
                            $('#garmentId').val(''); 
                            
                        },
                        error: function(xhr) {
                            console.error("Error processing ID: " + garmentId);
                            // Maybe highlight the input red if there is an error
                            toastr.error(xhr.responseJSON.message);
                            $('#garmentId').val('').focus();
                        }
                    });

                    $.ajax({
                        url: "{{ route('endline.get_defect_list') }}",
                        type: "GET",
                        data: {
                            garmentId: garmentId,
                        },
                        success: function(response) {
                            console.log(response);
                            if(response.data.defect_list){
                                $('.defect-list-wrapper').removeClass('d-none');
                                $('#info_defect_list').text(response.data.defect_list);
                            }else{
                                $('.defect-list-wrapper').addClass('d-none');
                                $('#info_defect_list').text('');
                            }
                        },
                        error: function(xhr) {
                            console.error("Error processing ID: " + garmentId);
                            // Maybe highlight the input red if there is an error
                            toastr.error(xhr.responseJSON.message);
                            $('#garmentId').val('').focus();
                        }
                    });
                }
            });

            $('#passCard').on('click', function(e) {
                e.preventDefault(); // Prevent default link behavior if any

                var lineNo = sessionStorage.getItem('endline_outline') || "{{ $lineNo }}";
                var unitNo = sessionStorage.getItem('endline_unit') || "{{ $unit_from_session }}";
                var empNo = sessionStorage.getItem('emp_id') || "{{ $emp_id_from_session }}";
                var garmentId = $('#info_id').text();
                var cc = $('#info_cc').text();
                var color = $('#info_color').text();
                var model = $('#info_model').text();
                var size = $('#info_size').text();
                console.log('Ean_no', Ean_no);
                $.ajax({
                    url: '/rfid-save',
                    type: 'POST', // Route is defined as GET in web.php
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    data: {
                        line: lineNo,
                        unit: unitNo,
                        empno: empNo,
                        garmentId: garmentId,
                        ccno: cc,
                        color: color,
                        model: model,
                        size: size,
                        Ean_no: Ean_no,
                        type: 1 // 1 for PASS
                    },
                    success: function(response) {
                        console.log("Data saved for: " + garmentId);
                        
                        // Proceed to linetable if successful (matches original href)
                        // window.location.href = "{{ route('endline.linetable') }}";
                        $('#info_id').text('');
                        $('#info_cc').text('');
                        $('#info_color').text('');
                        $('#info_model').text('');
                        $('#info_size').text('');
                        $('#info_bundle').text('');
                        $('#info_bundle_no').text('');
                        $("#selectionCardsContainer").hide();
                        $("#rfidinputcard").removeClass('d-none');
                        $("#infoPills").addClass("d-none");

                        window.location.href = "{{ route('endline.selection') }}";
                        
                        

                        toastr.success("Pass record saved successfully.");

                        return true;
                    },
                    error: function(xhr) {
                        console.error("Error saving ID: " + garmentId);
                        // alert("Failed to save Pass record. Please try again.");
                        toastr.error(xhr.responseJSON.message);
                        return false;
                    }
                });
            });

            $('#defectiveCard').on('click', function(e) {
                e.preventDefault();
                var garmentId = $('#info_id').text();
                var cc = $('#info_cc').text();
                var color = $('#info_color').text();
                var model = $('#info_model').text();
                var size = $('#info_size').text();
                var ean_no = Ean_no;

                var url = $(this).attr('href');
                var params = $.param({
                    cc: cc,
                    color: color,
                    model: model,
                    size: size,
                    garmentId: garmentId,
                    ean_no: ean_no
                });

                window.location.href = url + '?' + params;
            });
        });
    </script>
</body>
</html>
