@extends('layouts.dashboard.superadminapp')
@section('title', 'Quality Control Board')

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

@push('styles')
<style>
    :root {
        --primary-gradient: linear-gradient(135deg, #4e73df 0%, #224abe 100%);
        --card-shadow: 0 10px 15px -3px rgba(0,0,0,0.1), 0 4px 6px -2px rgba(0,0,0,0.05);
        --text-dark: #2d3748;
        --text-muted: #718096;
        --bg-light: #f8f9fa;
        /* Stage Colors */
        --stage-before: #8b5cf6;
        --stage-during: #f59e0b; 
        --stage-after: #10b981;
    }

    body {
        background-color: var(--bg-light);
        font-family: 'Inter', sans-serif;
    }

    /* Gradient Header */
    .page-header-gradient {
        background: var(--primary-gradient);
        color: white;
        padding: 2rem 2.5rem;
        border-radius: 20px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        position: relative;
        z-index: 10;
        margin-bottom: 2rem;
    }

    .breadcrumb-item + .breadcrumb-item::before {
        color: rgba(255, 255, 255, 0.6);
    }
    .breadcrumb-item.active {
        color: rgba(255, 255, 255, 0.9);
    }

    /* Kanban Board Styling */
    .kanban-section {
        overflow-x: auto;
        padding-bottom: 2rem;
    }

    .kanban-board {
        display: flex;
        gap: 1.5rem;
        min-width: 100%;
    }

    .kanban-column {
        flex: 1;
        min-width: 320px;
        background: #f1f5f9;
        border-radius: 16px;
        padding: 1rem;
        display: flex;
        flex-direction: column;
        border: 1px solid #e2e8f0;
    }

    .column-header {
        font-weight: 700;
        font-size: 1rem;
        color: var(--text-dark);
        margin-bottom: 1rem;
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 0.5rem;
    }

    .column-badge {
        background: white;
        border-radius: 12px;
        padding: 0.2rem 0.6rem;
        font-size: 0.8rem;
        font-weight: 600;
        box-shadow: 0 1px 2px rgba(0,0,0,0.05);
    }

    .kanban-cards {
        flex: 1;
        min-height: 100px;
    }

    .kanban-card {
        background: white;
        border-radius: 12px;
        padding: 1rem;
        margin-bottom: 1rem;
        box-shadow: 0 2px 5px rgba(0,0,0,0.05);
        border: 1px solid transparent;
        cursor: pointer; /* Click to open details */
        transition: all 0.2s ease;
        position: relative;
        border-left: 4px solid transparent; /* Stage indicator */
    }

    .kanban-card:hover {
        transform: translateY(-3px);
        box-shadow: 0 8px 15px rgba(0,0,0,0.1);
    }

    .kanban-card.dragging {
        opacity: 0.5;
        border: 2px dashed #4e73df;
    }

    .card-title {
        font-weight: 700;
        font-size: 0.95rem;
        color: var(--text-dark);
        margin-bottom: 0.25rem;
    }

    .card-subtitle {
        font-size: 0.85rem;
        color: var(--text-muted);
        margin-bottom: 0.5rem;
    }

    .stage-badge {
        font-size: 0.7rem;
        font-weight: 700;
        text-transform: uppercase;
        padding: 0.2rem 0.5rem;
        border-radius: 4px;
        color: white;
        display: inline-block;
        margin-right: 0.5rem;
    }
    .stage-before { background-color: var(--stage-before); }
    .stage-during { background-color: var(--stage-during); }
    .stage-after { background-color: var(--stage-after); }

    .action-row {
        margin-top: 1rem;
        display: flex;
        justify-content: flex-end;
        gap: 0.5rem;
    }
</style>
@endpush

<!-- Gradient Header -->
<div class="page-header-gradient">
    <div class="container-fluid">
        <div class="d-flex justify-content-between align-items-center">
            <div>
                <h1 class="h3 font-weight-bold mb-1">Quality Control Board</h1>
                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb bg-transparent p-0 m-0">
                        <li class="breadcrumb-item"><a href="{{ url('superadmin/dashboard') }}" class="text-white-50">Dashboard</a></li>
                        <li class="breadcrumb-item"><a href="{{ url('superadmin/quality/qc-management') }}" class="text-white-50">QC Management</a></li>
                        <li class="breadcrumb-item active" aria-current="page">{{ $routeCard->route_no }}</li>
                    </ol>
                </nav>
            </div>
            <div>
                 <a href="{{ url('superadmin/quality/qc-management') }}" class="btn btn-sm-glass shadow-sm" style="background: rgba(255,255,255,0.2); border: 1px solid rgba(255,255,255,0.3); color: white;">
                    <i class="fas fa-arrow-left mr-1"></i> Back to List
                </a>
            </div>
        </div>
    </div>
</div>

<div class="container-fluid" style="position: relative; z-index: 20; padding-top: 0;">
    
    <!-- Kanban Board -->
    <div class="kanban-section">
        <div class="kanban-board">
            @foreach (['Pending', 'In Progress', 'Completed', 'Approved', 'Rejected'] as $status)
                @php
                    $statusKey = strtolower(str_replace(' ', '_', $status));
                    // Color coding columns
                    $borderColor = '#e2e8f0';
                    if($status == 'Pending') $borderColor = '#fbbf24'; 
                    if($status == 'In Progress') $borderColor = '#60a5fa';
                    if($status == 'Completed') $borderColor = '#34d399';
                    if($status == 'Approved') $borderColor = '#10b981';
                    if($status == 'Rejected') $borderColor = '#ef4444';
                @endphp
                <div class="kanban-column" style="border-top: 4px solid {{ $borderColor }};" data-status="{{ $status }}">
                    <div class="column-header">
                        <span>{{ $status }}</span>
                        <span class="column-badge" id="badge-{{ $statusKey }}">0</span>
                    </div>
                    <div class="kanban-cards" id="cards-{{ $statusKey }}">
                        <!-- Cards injected via JS -->
                    </div>
                </div>
            @endforeach
        </div>
    </div>
    
    <!-- Table View -->
    <div class="card shadow-sm border-0 mt-4 rounded-lg">
        <div class="card-header bg-white py-3">
             <h6 class="m-0 font-weight-bold text-primary">Detailed Records</h6>
        </div>
        <div class="card-body">
             <div class="table-responsive">
                <table class="table table-hover" id="qc-data-table">
                    <thead>
                        <tr>
                             <th>Part / Process</th>
                             <th>Stage</th>
                             <th>Project</th>
                             <th>Status</th>
                             <th>Approved By</th>
                        </tr>
                    </thead>
                    <tbody id="qc-table-body"></tbody>
                </table>
             </div>
        </div>
    </div>

</div>

<!-- QC Action Modal -->
<div class="modal fade" id="qcActionModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="qcActionModalLabel">QC Action</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="modal-qc-id">
                <p><strong>Process:</strong> <span id="modal-process-name"></span></p>
                <p><strong>Stage:</strong> <span id="modal-stage-badge"></span></p>
                <div class="form-group">
                    <label>Remarks</label>
                    <textarea class="form-control" id="modal-remarks" rows="3"></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="saveRemarksOnly()">Save Remarks</button>
                <div id="decision-buttons" style="display:contents;">
                    <button type="button" class="btn btn-danger" onclick="submitQCVerdict('rejected')">Reject (Rework)</button>
                    <button type="button" class="btn btn-success" onclick="submitQCVerdict('approved')">Approve</button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Toast Notification -->
<div id="qc-toast" class="toast hide" role="alert" aria-live="assertive" aria-atomic="true" style="position:fixed; top:1rem; right:1rem; min-width:250px; 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" data-dismiss="toast">&times;</button>
    </div>
    <div class="toast-body" id="qc-toast-body"></div>
</div>

@endsection

@push('scripts')
    <!-- Libraries -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Sortable/1.15.0/Sortable.min.js"></script>
    <script>
        let qcRecords = [];
        const statusList = [
            { code: 'pending', display: 'Pending' },
            { code: 'in_progress', display: 'In Progress' },
            { code: 'completed', display: 'Completed' },
            { code: 'approved', display: 'Approved' },
            { code: 'rejected', display: 'Rejected' },
        ];

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

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

        function renderKanban() {
            // Clear all columns
            statusList.forEach(s => {
                $('#cards-' + s.code).html('');
                $('#badge-' + s.code).text('0');
            });

            qcRecords.forEach(record => {
                 // Determine where to put it
                 // If status_code is 'pending' -> Pending Column
                 // But wait, the controller returns dynamic list of QCs.
                 // We need to map DB status to Column Code.
                 let targetCode = record.status_code; 
                 // Handle mismatches if any
                 
                 let colElem = $('#cards-' + targetCode);
                 if (colElem.length) {
                     // Update count
                     let badge = $('#badge-' + targetCode);
                     badge.text(parseInt(badge.text()) + 1);

                     let stageClass = 'stage-' + (record.stage || 'before'); // Default to before if null
                     let stageLabel = (record.stage || 'Check').toUpperCase();
                     let borderColors = { 'before': '#8b5cf6', 'during': '#f59e0b', 'after': '#10b981' };
                     
                     let card = `
                        <div class="kanban-card" onclick="openQCAction(${record.id})">
                             <div style="border-left: 4px solid ${borderColors[record.stage] || '#ccc'}; padding-left: 10px; margin-left: -10px;">
                                <div class="card-title">${record.part_no || 'Process'}</div>
                                <div class="mb-1">
                                    <span class="stage-badge ${stageClass}">${stageLabel}</span>
                                </div>
                                <div class="card-subtitle">
                                    <i class="far fa-file-alt mr-1"></i> ${record.document_value || '-'}
                                </div>
                             </div>
                        </div>
                     `;
                     colElem.append(card);
                 }
            });
        }

        let currentQC = null;
        function openQCAction(id) {
            let record = qcRecords.find(r => r.id == id);
            if(!record) return;
            
            currentQC = record;
            $('#modal-qc-id').val(id);
            $('#modal-process-name').text(record.part_no);
            $('#modal-stage-badge').text((record.stage || 'Check').toUpperCase());
            $('#modal-remarks').val(record.remarks || ''); 
            
            // Toggle Decision Buttons only
            if(record.status_code === 'pending' || record.status_code === 'in_progress') {
                $('#decision-buttons').show();
            } else {
                $('#decision-buttons').hide();
            }

            $('#qcActionModal').modal('show');
        }

        function saveRemarksOnly() {
            if(!currentQC) return;
            // Keep current status
            let status = currentQC.status_code; 
            let remarks = $('#modal-remarks').val();
            
            fetch(`{{ url('superadmin/quality/qualitycontrol-status') }}/${currentQC.id}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                body: JSON.stringify({ status: status, remarks: remarks })
            }).then(r => r.json()).then(resp => {
                 if(resp.success) {
                     $('#qcActionModal').modal('hide');
                     showToast('Remarks Saved');
                     fetchRecords();
                 } else {
                     showToast(resp.message || 'Error', 'Error');
                 }
            });
        }

        function submitQCVerdict(verdict) {
            let id = $('#modal-qc-id').val();
            let remarks = $('#modal-remarks').val();
            let url = verdict === 'approved' 
                ? `{{ url('superadmin/quality/qualitycontrol-approve') }}/${id}`
                : `{{ url('superadmin/quality/qualitycontrol-reject') }}/${id}`;

            // Wait... routes are: approveQC and rejectQC?
            // Checking web.php or controller...
            // Controller has approveQC, rejectQC methods.
            // Routes: 
            // Route::post('/qualitycontrol-status/{id}', ...updateQCStatus);
            // I need to add routes for approve/reject specifically if I want to use those controller methods,
            // OR reuse status update. Controller updateQCStatus handles generic? No, strict transition.
            // Actually, I should use the specialized methods.
            // I'll assume routes exist or I will add them.
            // Let's use the updateQCStatus for now if it supports mapping?
            // The method 'updateQCStatus' in QualityController only does status update. ProductionController has approveQC/rejectQC.
            // QualityController is used here.
            // WAIT. qc_management uses SuperAdminQualityController.
            // I edited SuperAdminProductionController. 
            // I need to check where 'approveQC' is located. It was in ProductionController?
            // Yes. But THIS page is served by QualityController.
            // Does QualityController route here? Yes.
            // So I need to add approveQC/rejectQC to QualityController OR enable route to ProductionController.
            // Let's assume I need to ADD routes mapping to SuperAdminProductionController actions for consistency?
            // Or just update updateQCStatus in SuperAdminQualityController to handle 3-stages?
            // Let's update SuperAdminQualityController. It's safer.
            
            // Temporary fix: use existing status update route but I need to handle logic there.
            // Actually, I should update QualityController to have the same logic.
            
             fetch(`{{ url('superadmin/quality/qualitycontrol-status') }}/${id}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                body: JSON.stringify({ status: verdict, remarks: remarks })
            }).then(r => r.json()).then(resp => {
                 if(resp.success) {
                     $('#qcActionModal').modal('hide');
                     showToast('QC ' + verdict);
                     fetchRecords();
                 } else {
                     showToast(resp.message || 'Error', 'Error');
                 }
            });
        }

        function renderTable(records) {
            let tbody = $('#qc-table-body');
            tbody.html('');
            records.forEach(r => {
                let badgeClass = 'badge-light';
                if(r.status_code == 'approved') badgeClass = 'badge-success';
                if(r.status_code == 'rejected') badgeClass = 'badge-danger';
                
                tbody.append(`
                    <tr>
                        <td class="font-weight-bold">${r.part_no || '-'}</td>
                        <td><span class="badge badge-info">${(r.stage||'').toUpperCase()}</span></td>
                        <td>${r.project_no}</td>
                        <td><span class="badge ${badgeClass}">${r.status}</span></td>
                        <td>${r.approved_by || '-'}</td>
                    </tr>
                `);
            });
        }

        $(document).ready(function() {
            fetchRecords();
        });
    </script>
@endpush
