@extends('layouts.dashboard.adminapp')

@section('title', 'Quality Control Board')

@section('content')
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css" />
    <style>
        .kanban-section {
            background: #fff;
            border-radius: 18px;
            box-shadow: 0 2px 20px 0 rgba(80, 102, 144, 0.07);
            padding: 2rem 2rem 1.5rem 2rem;
        }

        .kanban-board {
            display: flex;
            gap: 2rem;
            overflow-x: auto;
            margin-bottom: 2rem;
        }

        .kanban-column {
            flex: 1;
            background: #f7f9fb;
            border-radius: 14px;
            padding: 1rem;
            min-width: 270px;
            max-width: 320px;
            border: 1px solid #f1f3f9;
            box-shadow: 0 1px 10px 0 rgba(80, 102, 144, 0.04);
            display: flex;
            flex-direction: column;
            min-height: 450px;
        }

        .kanban-column h5 {
            font-size: 1.13rem;
            font-weight: 700;
            margin-bottom: 1rem;
            color: #3e4651;
            display: flex;
            align-items: center;
            gap: 0.45em;
        }

        .kanban-cards {
            flex: 1;
            min-height: 20px;
            transition: background 0.2s;
        }

        .kanban-card {
            background: #fff;
            border-radius: 10px;
            padding: 1.1rem 1rem 0.9rem 1rem;
            margin-bottom: 1rem;
            box-shadow: 0 2px 12px 0 rgba(60, 60, 100, 0.06);
            border: 1px solid #f1eeda;
            cursor: grab;
            transition: box-shadow 0.15s;
            position: relative;
            user-select: none;
        }

        .kanban-card.dragging {
            box-shadow: 0 8px 30px 0 rgba(80, 100, 180, .12);
            opacity: 0.82;
        }

        .kanban-card .card-title {
            font-size: 1.09em;
            font-weight: bold;
            margin-bottom: .1em;
            color: #2e5a7b;
            padding-right: 60px;
            /* <-- ADD THIS LINE */
            word-break: break-word;
        }

        .kanban-card .part-label {
            font-size: .98em;
            color: #222;
            font-weight: 500;
        }

        .kanban-card .badge-status {
            font-size: 0.87em;
            font-weight: 500;
            background: #d6ecfa;
            color: #2476b8;
            padding: 0.14em 0.85em;
            border-radius: 13px;
        }

        .kanban-card .edit-btn {
            position: absolute;
            top: 9px;
            right: -70px !important;
            background: none;
            border: none;
            color: #2662b0;
            font-size: 1.13em;
            cursor: pointer;
            outline: none;
            padding: 2px 4px;
        }

        .kanban-card .delete-btn {
            position: absolute;
            top: 9px;
            right: -100px !important;
            background: none;
            border: none;
            color: #2662b0;
            font-size: 1.13em;
            cursor: pointer;
            outline: none;
            padding: 2px 4px;
        }

        .kanban-card .delete-btn {
            right: 8px;
            color: #e34a3e;
        }

        .kanban-card .edit-btn:hover {
            color: #2980ef;
        }

        .kanban-card .delete-btn:hover {
            color: #b30000;
        }

        .kanban-card .drag-handle {
            position: absolute;
            left: 8px;
            top: 9px;
            color: #ccc;
            cursor: move;
            font-size: 1.12em;
        }

        @media (max-width:900px) {
            .kanban-board {
                gap: 1rem;
            }

            .kanban-column {
                min-width: 250px;
                padding: 0.6rem;
            }
        }

        @media (max-width:600px) {
            .kanban-section {
                padding: 0.4rem;
            }

            .kanban-board {
                gap: 0.7rem;
            }
        }
    </style>

    <div class="container-fluid px-2 kanban-section">
        <div class="d-flex align-items-center justify-content-between mb-3">
            <h2 class="h5 mb-0 text-gray-800">UEPL / Quality Control Board</h2>
            <a href="{{ url('admin/manufacturing/production/in-progress') }}"
                class="btn btn-outline-secondary btn-sm">&larr; Back</a>
        </div>

        <h4 class="mb-3" style="letter-spacing:.02em;">Quality Control Kanban Board</h4>
        <div class="kanban-board" id="qc-kanban-board">
            @foreach (['Pending', 'In Progress', 'Completed', 'Approved'] as $status)
                <div class="kanban-column" data-status="{{ $status }}">
                    <h5>
                        {{ $status }}
                        <span class="badge badge-secondary"
                            id="badge-{{ strtolower(str_replace(' ', '-', $status)) }}">0</span>
                    </h5>
                    <div class="kanban-cards" id="cards-{{ strtolower(str_replace(' ', '-', $status)) }}"></div>
                </div>
            @endforeach
        </div>

        <hr>
        <h4 class="mb-3">Quality Control Records Table</h4>
        <div class="d-flex mb-2">
            <input type="text" id="search-input" class="form-control mr-2" placeholder="Search records..."
                style="max-width:250px;">
            <button class="btn btn-outline-success" onclick="exportToCSV()">Export to CSV</button>
        </div>
        <div class="table-responsive">
            <table class="table table-bordered table-hover" id="qc-data-table">
                <thead class="thead-light">
                    <tr>
                        <th>Customer</th>
                        <th>Project No.</th>
                        <th>Material No.</th>
                        <th>Part No.</th>
                        <th>Drawing No.</th>
                        <th>Status</th>
                        
                    </tr>
                </thead>
                <tbody id="qc-table-body"></tbody>
            </table>
        </div>
    </div>

    <!-- Toast Notification -->
    <div id="qc-toast" class="toast" role="alert" aria-live="assertive" aria-atomic="true"
        style="position:fixed; top:1rem; right:1rem; min-width:200px; z-index:9999;">
        <div class="toast-header">
            <strong class="mr-auto" id="qc-toast-title">Notice</strong>
            <button type="button" class="ml-2 mb-1 close" onclick="$('#qc-toast').toast('hide');">&times;</button>
        </div>
        <div class="toast-body" id="qc-toast-body"></div>
    </div>

@endsection

@push('scripts')
    <!-- jQuery and Bootstrap Bundle -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
    <!-- SortableJS for Drag & Drop -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Sortable/1.15.0/Sortable.min.js"></script>
    <script>
        let sortableInstances = {};
        let qcRecords = [];

        // Add this:
        const statusList = [{
                code: 'pending',
                display: 'Pending'
            },
            {
                code: 'in_progress',
                display: 'In Progress'
            },
            {
                code: 'completed',
                display: 'Completed'
            },
            {
                code: 'approved',
                display: 'Approved'
            }
        ];

        function showToast(msg, title = 'Notice') {
            $('#qc-toast-title').text(title);
            $('#qc-toast-body').text(msg);
            $('#qc-toast').toast({
                delay: 2500
            });
            $('#qc-toast').toast('show');
        }

        function fetchRecords() {
            fetch("{{ url('admin/quality/qualitycontrol-data/' . $routeCard->id) }}")
                .then(res => res.json())
                .then(data => {
                    qcRecords = data;
                    renderKanban();
                    renderTable(qcRecords);
                });
        }

        function renderKanban() {
            statusList.forEach(col => {
                let colId = '#cards-' + col.code.replace(/_/g, '-');
                let colElem = $(colId);
                colElem.html('');
                let records = qcRecords.filter(r => r.status_code === col.code);
                $(`#badge-${col.code.replace(/_/g, '-')}`).text(records.length);
                records.forEach(record => {
                    let card = $(`
            <div class="kanban-card" data-id="${record.id}">
                <span class="drag-handle"><i class="fas fa-grip-lines"></i></span>
                <div class="card-title">${record.customer}</div>
                <div class="part-label">Part No: ${record.part_no || '-'}</div>
                <div class="mt-1">
                    <span class="badge-status">${record.status}</span>
                </div>
                
            </div>
        `);
                    colElem.append(card);
                });
            });

            statusList.forEach(col => {
                let list = document.getElementById('cards-' + col.code.replace(/_/g, '-'));
                if (!list) return;
                if (sortableInstances[col.code]) {
                    sortableInstances[col.code].destroy();
                    delete sortableInstances[col.code];
                }
                sortableInstances[col.code] = Sortable.create(list, {
                    group: 'kanban',
                    handle: '.drag-handle',
                    animation: 160,
                    ghostClass: 'dragging',
                    onEnd: function(evt) {
                        let id = $(evt.item).data('id');
                        let newStatus = $(evt.to).closest('.kanban-column').data('status');
                        // Convert display back to code:
                        let target = statusList.find(s => s.display === newStatus || s.code ===
                            newStatus.toLowerCase().replace(/ /g, '_'));
                        if (target) {
                            updateQCStatus(id, target.code);
                        }
                    }
                });
            });
        }

        function updateQCStatus(id, status_code) {
            fetch(`{{ url('admin/quality/qualitycontrol-status') }}/${id}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                body: JSON.stringify({
                    status: status_code
                })
            }).then(r => r.json()).then(resp => {
                if (resp.success) {
                    showToast('Status updated!');
                    fetchRecords();
                } else {
                    showToast(resp.message || 'Error', 'Error');
                    fetchRecords();
                }
            });
        }

        function renderTable(records) {
            let tbody = $('#qc-table-body');
            tbody.html('');
            records.forEach(record => {
                let row = `
                <tr>
                    <td>${record.customer}</td>
                    <td>${record.project_no}</td>
                    <td>${record.material_no || '-'}</td>
                    <td>${record.part_no || '-'}</td>
                    <td>${record.document_value || '-'}</td>
                    <td><span class="badge badge-info">${record.status}</span></td>
                    
                </tr>
            `;
                tbody.append(row);
            });
        }

        function editRecord(id) {
            showToast('Edit logic here.');
        }

        function deleteRecord(id) {
            if (!confirm('Are you sure you want to delete this record?')) return;
            fetch("{{ url('admin/quality/qualitycontrol') }}/" + id, {
                method: 'DELETE',
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            }).then(res => {
                if (res.ok) {
                    fetchRecords();
                    showToast('Record deleted!');
                } else {
                    showToast('Delete failed', 'Error');
                }
            });
        }

        function exportToCSV() {
            let csv = 'Customer,Project No.,Material No.,Part No.,Drawing No.,Status\n';
            qcRecords.forEach(record => {
                csv += [
                    record.customer,
                    record.project_no,
                    record.material_no,
                    record.part_no,
                    record.document_value,
                    record.status
                ].join(',') + '\n';
            });
            let blob = new Blob([csv], {
                type: 'text/csv'
            });
            let link = document.createElement('a');
            link.href = window.URL.createObjectURL(blob);
            link.download = 'quality-control-records.csv';
            link.click();
        }

        $(document).ready(function() {
            fetchRecords();
            $('#search-input').on('keyup', function() {
                let val = $(this).val().toLowerCase();
                let filtered = qcRecords.filter(r =>
                    Object.values(r).some(v =>
                        v && v.toString().toLowerCase().includes(val)
                    )
                );
                renderTable(filtered);
            });
        });
    </script>
@endpush
