@extends('layouts.app')

@section('title', 'QC Inspection - ' . $grn->grn_number)

@section('content')
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h4 class="card-title">QC Inspection - {{ $grn->grn_number }}</h4>
                    <div class="card-tools">
                        <a href="{{ route('grns.show', $grn) }}" class="btn btn-secondary">
                            <i class="fas fa-arrow-left"></i> Back to GRN
                        </a>
                    </div>
                </div>
                <div class="card-body">
                    <!-- GRN Information -->
                    <div class="row mb-4">
                        <div class="col-md-6">
                            <h5>GRN Information</h5>
                            <table class="table table-sm">
                                <tr>
                                    <td><strong>GRN Number:</strong></td>
                                    <td>{{ $grn->grn_number }}</td>
                                </tr>
                                <tr>
                                    <td><strong>PO Number:</strong></td>
                                    <td>{{ $grn->purchaseOrder->po_number }}</td>
                                </tr>
                                <tr>
                                    <td><strong>Supplier:</strong></td>
                                    <td>{{ $grn->purchaseOrder->vendor->name }}</td>
                                </tr>
                                <tr>
                                    <td><strong>Received Date:</strong></td>
                                    <td>{{ $grn->received_date->format('d/m/Y') }}</td>
                                </tr>
                            </table>
                        </div>
                        <div class="col-md-6">
                            <h5>QC Information</h5>
                            <table class="table table-sm">
                                <tr>
                                    <td><strong>QC Number:</strong></td>
                                    <td>{{ $qc->qc_number }}</td>
                                </tr>
                                <tr>
                                    <td><strong>Status:</strong></td>
                                    <td>
                                        <span class="badge bg-{{ $qc->status === 'pending' ? 'warning' : ($qc->status === 'completed' ? 'success' : 'secondary') }}">
                                            {{ ucfirst($qc->status) }}
                                        </span>
                                    </td>
                                </tr>
                                <tr>
                                    <td><strong>Created:</strong></td>
                                    <td>{{ $qc->created_at->format('d/m/Y H:i') }}</td>
                                </tr>
                            </table>
                        </div>
                    </div>

                    <!-- QC Form -->
                    <form id="qcForm" method="POST" action="{{ route('qcs.store', $qc) }}">
                        @csrf
                        <div class="row mb-3">
                            <div class="col-md-4">
                                <label for="warehouse_id" class="form-label">Warehouse *</label>
                                <select class="form-select" id="warehouse_id" name="warehouse_id" required>
                                    <option value="">Select Warehouse</option>
                                    @foreach($warehouses as $id => $name)
                                        <option value="{{ $id }}" {{ $grn->warehouse_id == $id ? 'selected' : '' }}>
                                            {{ $name }}
                                        </option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="col-md-4">
                                <label for="inspected_by" class="form-label">Inspector *</label>
                                <select class="form-select" id="inspected_by" name="inspected_by" required>
                                    <option value="">Select Inspector</option>
                                    @foreach($inspectors as $id => $name)
                                        <option value="{{ $id }}">{{ $name }}</option>
                                    @endforeach
                                </select>
                            </div>
                        </div>

                        <!-- QC Items Table -->
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle"></i>
                            <strong>Note:</strong> Items with received quantity less than 1 are automatically excluded from QC inspection.
                        </div>

                        <div class="table-responsive">
                            <table class="table table-bordered table-striped" id="qcItemsTable">
                                <thead>
                                    <tr>
                                        <th>Item</th>
                                        <th>Received Qty</th>
                                        <th>Passed Qty *</th>
                                        <th>Failed Qty *</th>
                                        <th>Available Bin</th>
                                        <th>Rejected Bin</th>
                                        <th>Lot No</th>
                                        <th>Remarks</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach($qc->qcItems as $index => $qcItem)
                                    <tr>
                                        <td>
                                            <input type="hidden" name="qc_items[{{ $index }}][qc_item_id]" value="{{ $qcItem->id }}">
                                            <strong>{{ $qcItem->item->name }}</strong><br>
                                            <small class="text-muted">{{ $qcItem->item->sku }}</small>
                                        </td>
                                        <td>{{ $qcItem->grnItem->received_quantity }}</td>
                                        <td>
                                            <input type="number"
                                                   class="form-control qty-passed"
                                                   name="qc_items[{{ $index }}][qty_passed]"
                                                   step="0.01"
                                                   min="0"
                                                   max="{{ $qcItem->grnItem->received_quantity }}"
                                                   value="{{ $qcItem->qty_passed }}"
                                                   data-max-qty="{{ $qcItem->grnItem->received_quantity }}"
                                                   required>
                                        </td>
                                        <td>
                                            <input type="number"
                                                   class="form-control qty-failed"
                                                   name="qc_items[{{ $index }}][qty_failed]"
                                                   step="0.01"
                                                   min="0"
                                                   max="{{ $qcItem->grnItem->received_quantity }}"
                                                   value="{{ $qcItem->qty_failed }}"
                                                   data-max-qty="{{ $qcItem->grnItem->received_quantity }}"
                                                   required>
                                        </td>
                                        <td>
                                            <select class="form-select available-bin-select"
                                                    name="qc_items[{{ $index }}][available_bin_id]">
                                                <option value="">Select Bin</option>
                                            </select>
                                        </td>
                                        <td>
                                            <select class="form-select rejected-bin-select"
                                                    name="qc_items[{{ $index }}][rejected_bin_id]">
                                                <option value="">Select Bin</option>
                                            </select>
                                        </td>
                                        <td>
                                            <input type="text"
                                                   class="form-control"
                                                   name="qc_items[{{ $index }}][lot_no]"
                                                   value="{{ $qcItem->lot_no }}"
                                                   placeholder="Lot No">
                                        </td>
                                        <td>
                                            <textarea class="form-control"
                                                      name="qc_items[{{ $index }}][remarks]"
                                                      rows="2"
                                                      placeholder="Remarks">{{ $qcItem->remarks }}</textarea>
                                        </td>
                                    </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        </div>

                        <div class="row mt-3">
                            <div class="col-12">
                                <button type="submit" class="btn btn-primary" id="submitBtn">
                                    <i class="fas fa-save"></i> Submit QC Results
                                </button>
                                <button type="button" class="btn btn-secondary" onclick="window.history.back()">
                                    <i class="fas fa-times"></i> Cancel
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
$(document).ready(function() {
    let warehouseId = $('#warehouse_id').val();

    // Load bins when warehouse changes
    $('#warehouse_id').on('change', function() {
        warehouseId = $(this).val();
        if (warehouseId) {
            loadWarehouseBins();
        }
    });

    // Load bins on page load if warehouse is selected
    if (warehouseId) {
        loadWarehouseBins();
    }

    // Quantity validation
    $('.qty-passed, .qty-failed').on('input', function() {
        validateQuantities($(this));
    });

    // Bin selection validation
    $('.qty-passed').on('input', function() {
        const qtyPassed = parseFloat($(this).val()) || 0;
        const availableBinSelect = $(this).closest('tr').find('.available-bin-select');

        if (qtyPassed > 0) {
            availableBinSelect.prop('required', true);
        } else {
            availableBinSelect.prop('required', false);
        }
    });

    $('.qty-failed').on('input', function() {
        const qtyFailed = parseFloat($(this).val()) || 0;
        const rejectedBinSelect = $(this).closest('tr').find('.rejected-bin-select');

        if (qtyFailed > 0) {
            rejectedBinSelect.prop('required', true);
        } else {
            rejectedBinSelect.prop('required', false);
        }
    });

    // Form submission
    $('#qcForm').on('submit', function(e) {
        e.preventDefault();

        if (!validateForm()) {
            return false;
        }

        const formData = $(this).serialize();

        $.ajax({
            url: $(this).attr('action'),
            method: 'POST',
            data: formData,
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                if (response.success) {
                    Swal.fire({
                        title: 'Success!',
                        text: response.message,
                        icon: 'success',
                        confirmButtonText: 'OK'
                    }).then((result) => {
                        window.location.href = '{{ route("grns.show", $grn) }}';
                    });
                } else {
                    Swal.fire({
                        title: 'Error!',
                        text: response.message,
                        icon: 'error',
                        confirmButtonText: 'OK'
                    });
                }
            },
            error: function(xhr) {
                let errorMessage = 'An error occurred while submitting QC results.';
                if (xhr.responseJSON && xhr.responseJSON.message) {
                    errorMessage = xhr.responseJSON.message;
                }

                Swal.fire({
                    title: 'Error!',
                    text: errorMessage,
                    icon: 'error',
                    confirmButtonText: 'OK'
                });
            }
        });
    });

    function loadWarehouseBins() {
        $.ajax({
            url: '{{ route("qcs.warehouse-bins") }}',
            method: 'GET',
            data: {
                warehouse_id: warehouseId,
                bin_type: 'all'
            },
            success: function(response) {
                if (response.success) {
                    const bins = response.data;

                    // Populate available bins
                    $('.available-bin-select').each(function() {
                        $(this).empty().append('<option value="">Select Bin</option>');
                        bins.forEach(function(bin) {
                            if (bin.type === 'available' || bin.type === 'general') {
                                $(this).append(`<option value="${bin.id}">${bin.code} (${bin.type})</option>`);
                            }
                        }.bind(this));
                    });

                    // Populate rejected bins
                    $('.rejected-bin-select').each(function() {
                        $(this).empty().append('<option value="">Select Bin</option>');
                        bins.forEach(function(bin) {
                            if (bin.type === 'rejected' || bin.type === 'general') {
                                $(this).append(`<option value="${bin.id}">${bin.code} (${bin.type})</option>`);
                            }
                        }.bind(this));
                    });
                }
            },
            error: function() {
                console.error('Failed to load warehouse bins');
            }
        });
    }

    function validateQuantities(input) {
        const row = input.closest('tr');
        const qtyPassed = parseFloat(row.find('.qty-passed').val()) || 0;
        const qtyFailed = parseFloat(row.find('.qty-failed').val()) || 0;
        const maxQty = parseFloat(input.data('max-qty')) || 0;
        const total = qtyPassed + qtyFailed;

        // Clear previous validation
        input.removeClass('is-invalid');
        row.find('.invalid-feedback').remove();

        // Validate total quantity
        if (total > maxQty) {
            input.addClass('is-invalid');
            input.after(`<div class="invalid-feedback">Total quantity (${total}) cannot exceed received quantity (${maxQty})</div>`);
            return false;
        }

        return true;
    }

    function validateForm() {
        let isValid = true;

        // Validate warehouse and inspector
        if (!$('#warehouse_id').val()) {
            Swal.fire('Validation Error', 'Please select a warehouse', 'error');
            return false;
        }

        if (!$('#inspected_by').val()) {
            Swal.fire('Validation Error', 'Please select an inspector', 'error');
            return false;
        }

        // Validate quantities and bins
        $('.qty-passed, .qty-failed').each(function() {
            if (!validateQuantities($(this))) {
                isValid = false;
            }
        });

        // Validate bin requirements
        $('.qty-passed').each(function() {
            const qtyPassed = parseFloat($(this).val()) || 0;
            const availableBin = $(this).closest('tr').find('.available-bin-select').val();

            if (qtyPassed > 0 && !availableBin) {
                Swal.fire('Validation Error', 'Available bin is required for passed quantity', 'error');
                isValid = false;
                return false;
            }
        });

        $('.qty-failed').each(function() {
            const qtyFailed = parseFloat($(this).val()) || 0;
            const rejectedBin = $(this).closest('tr').find('.rejected-bin-select').val();

            if (qtyFailed > 0 && !rejectedBin) {
                Swal.fire('Validation Error', 'Rejected bin is required for failed quantity', 'error');
                isValid = false;
                return false;
            }
        });

        return isValid;
    }
});
</script>
@endpush
