@extends('layouts.app')

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

@section('content')
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h4 class="card-title">Quality Control Inspections</h4>
                    <div class="card-tools">
                        <button type="button" class="btn btn-success me-2" data-bs-toggle="modal" data-bs-target="#createQcModal">
                            <i class="fas fa-plus"></i> Create New QC
                        </button>
                        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#filterModal">
                            <i class="fas fa-filter"></i> Filter
                        </button>
                    </div>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-bordered table-striped" id="qcTable">
                            <thead>
                                <tr>
                                    <th>QC Number</th>
                                    <th>GRN Number</th>
                                    <th>PO Number</th>
                                    <th>Supplier</th>
                                    <th>Status</th>
                                    <th>Inspector</th>
                                    <th>Created</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <!-- Data loaded via AJAX -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Filter Modal -->
<div class="modal fade" id="filterModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Filter QC Inspections</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-6">
                        <label for="filterStatus" class="form-label">Status</label>
                        <select class="form-select" id="filterStatus">
                            <option value="">All Status</option>
                            <option value="pending">Pending</option>
                            <option value="in_progress">In Progress</option>
                            <option value="completed">Completed</option>
                            <option value="cancelled">Cancelled</option>
                        </select>
                    </div>
                    <div class="col-md-6">
                        <label for="filterGrnNumber" class="form-label">GRN Number</label>
                        <input type="text" class="form-control" id="filterGrnNumber" placeholder="Search GRN Number">
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" id="applyFilter">Apply Filter</button>
            </div>
        </div>
    </div>
</div>

<!-- Create QC Modal -->
<div class="modal fade" id="createQcModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Create New QC Inspection</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-12">
                        <label for="grnSelect" class="form-label">Select GRN for QC Inspection</label>
                        <select class="form-select" id="grnSelect">
                            <option value="">Loading GRNs...</option>
                        </select>
                        <small class="form-text text-muted">Only GRNs with status 'awaiting_qc' are shown</small>
                    </div>
                </div>
                <div id="grnDetails" class="mt-3" style="display: none;">
                    <h6>GRN Details</h6>
                    <div class="row">
                        <div class="col-md-6">
                            <strong>GRN Number:</strong> <span id="grnNumber"></span><br>
                            <strong>Vendor:</strong> <span id="vendorName"></span><br>
                            <strong>Receipt Date:</strong> <span id="receiptDate"></span>
                        </div>
                        <div class="col-md-6">
                            <strong>Items Count:</strong> <span id="itemsCount"></span><br>
                            <strong>Total Amount:</strong> <span id="totalAmount"></span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-success" id="createQcBtn" disabled>Create QC</button>
            </div>
        </div>
    </div>
</div>
@endsection

@push('plugin-scripts')
<script>
$(function () {
        let qcTable = $('#qcTable').DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            url: '{{ route("qcs.index") }}',
            data: function(d) {
                d.status = $('#filterStatus').val();
                d.grn_number = $('#filterGrnNumber').val();
            }
        },
        columns: [
            { data: 'qc_number', name: 'qc_number' },
            { data: 'grn.grn_number', name: 'grn.grn_number' },
            { data: 'po_number', name: 'po_number', orderable: false, searchable: false },
            { data: 'vendor_name', name: 'vendor_name', orderable: false, searchable: false },
            { data: 'status_badge', name: 'status', orderable: true, searchable: true },
            { data: 'inspector_name', name: 'inspector_name', orderable: false, searchable: false },
            { data: 'formatted_date', name: 'created_at', orderable: true, searchable: false },
            { data: 'actions', name: 'actions', orderable: false, searchable: false }
        ],
        order: [[6, 'desc']], // Sort by created date descending
        pageLength: 15,
        // language: {
        //     processing: '<i class="fa fa-spinner fa-spin fa-3x fa-fw"></i>' +
        //                 '<span class="sr-only">Loading...</span>'
        // }
    });

    // Apply filter
    $('#applyFilter').on('click', function() {
        qcTable.ajax.reload();
        $('#filterModal').modal('hide');
    });

    // Reset filter when closed
    $('#filterModal').on('hidden.bs.modal', function() {
        $('#filterStatus').val('');
        $('#filterGrnNumber').val('');
    });

    // Create QC Modal functionality
    $('#createQcModal').on('show.bs.modal', function() {
        loadAvailableGRNs();
    });

    function loadAvailableGRNs() {
        $.ajax({
            url: '/grns/available-for-qc',
            method: 'GET',
            success: function(response) {
                if (response.success) {
                    const select = $('#grnSelect');
                    select.empty();
                    select.append('<option value="">Select a GRN</option>');

                    response.data.forEach(grn => {
                        select.append(`<option value="${grn.id}"
                            data-grn-number="${grn.grn_number}"
                            data-vendor-name="${grn.vendor_name}"
                            data-receipt-date="${grn.received_date}"
                            data-items-count="${grn.items_count}"
                            data-total-amount="${grn.total_amount}">
                            ${grn.grn_number} - ${grn.vendor_name}
                        </option>`);
                    });
                } else {
                    toastr.error('Failed to load GRNs');
                }
            },
            error: function() {
                toastr.error('Error loading GRNs');
            }
        });
    }

    $('#grnSelect').on('change', function() {
        const selectedOption = $(this).find('option:selected');
        const grnId = $(this).val();

        if (grnId) {
            $('#grnNumber').text(selectedOption.data('grn-number'));
            $('#vendorName').text(selectedOption.data('vendor-name'));
            $('#receiptDate').text(selectedOption.data('receipt-date'));
            $('#itemsCount').text(selectedOption.data('items-count'));
            $('#totalAmount').text(selectedOption.data('total-amount'));
            $('#grnDetails').show();
            $('#createQcBtn').prop('disabled', false);
        } else {
            $('#grnDetails').hide();
            $('#createQcBtn').prop('disabled', true);
        }
    });

    $('#createQcBtn').on('click', function() {
        const grnId = $('#grnSelect').val();
        if (grnId) {
            window.location.href = `/qcs/create/${grnId}`;
        }
    });

    // Debugging
    $('#qcTable').on('xhr.dt', function(e, settings, json) {
        console.log("DataTables JSON response:", json);
    });

    // Add to Stock function
    window.addToStock = function(qcId) {
        if (confirm('Are you sure you want to add QC items to stock? This will move items from quarantine to available stock.')) {
            $.ajax({
                url: '/qcs/' + qcId + '/add-to-stock',
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                success: function(response) {
                    if (response.success) {
                        toastr.success('Items added to stock successfully!');
                        qcTable.ajax.reload();
                    } else {
                        toastr.error(response.message || 'Failed to add items to stock');
                    }
                },
                error: function(xhr) {
                    toastr.error('Error: ' + (xhr.responseJSON?.message || 'Unknown error occurred'));
                }
            });
        }
    };

    // Cancel QC function
    window.cancelQc = function(qcId) {
        if (confirm('Are you sure you want to cancel this QC inspection?')) {
            $.ajax({
                url: '/qcs/' + qcId + '/cancel',
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                success: function(response) {
                    if (response.success) {
                        toastr.success('QC inspection cancelled successfully!');
                        qcTable.ajax.reload();
                    } else {
                        toastr.error(response.message || 'Failed to cancel QC inspection');
                    }
                },
                error: function(xhr) {
                    toastr.error('Error: ' + (xhr.responseJSON?.message || 'Unknown error occurred'));
                }
            });
        }
    };
});
</script>
@endpush

