@extends('layouts.dashboard.superadminapp')

@section('title', 'Edit RFQ')

@section('styles')
<style>
    .section-card {
        border: none;
        border-radius: 0.5rem;
        box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.1);
        margin-bottom: 1.5rem;
    }
    .section-card .card-header {
        background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);
        color: #fff;
        font-weight: 600;
        padding: 0.75rem 1rem;
        border-radius: 0.5rem 0.5rem 0 0 !important;
    }
    .section-card .card-header.bg-info-gradient {
        background: linear-gradient(135deg, #36b9cc 0%, #258391 100%);
    }
    .section-card .card-header.bg-success-gradient {
        background: linear-gradient(135deg, #1cc88a 0%, #13855c 100%);
    }
    .section-card .card-header.bg-warning-gradient {
        background: linear-gradient(135deg, #f6c23e 0%, #dda20a 100%);
    }
    .form-label {
        font-weight: 600;
        color: #5a5c69;
        font-size: 0.85rem;
        margin-bottom: 0.25rem;
    }
    .required-star {
        color: #e74a3b;
    }
    .material-row {
        background: #f8f9fc;
        border: 1px solid #e3e6f0;
        border-radius: 0.5rem;
        padding: 0.5rem 0.75rem;
        margin-bottom: 0.5rem;
    }
    .material-row .input-group {
        align-items: center;
    }
    .material-row .form-control {
        border-radius: 0.35rem 0 0 0.35rem !important;
    }
    .material-row .input-group-append {
        margin-left: -1px;
    }
    .material-row .input-group-append .btn {
        border-radius: 0 0.35rem 0.35rem 0 !important;
        height: 38px;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    .file-preview {
        display: flex;
        flex-wrap: wrap;
        gap: 0.5rem;
        margin-top: 0.5rem;
    }
    .file-preview img {
        max-width: 100px;
        max-height: 80px;
        border-radius: 0.25rem;
        border: 1px solid #e3e6f0;
    }
    .existing-file {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        padding: 0.35rem 0.5rem;
        background: #e3e6f0;
        border-radius: 0.35rem;
        margin-bottom: 0.5rem;
        font-size: 0.85rem;
    }
    .existing-file a {
        color: #4e73df;
    }
    .existing-file .delete-file-btn {
        color: #e74a3b;
        cursor: pointer;
    }
    .existing-file .delete-file-btn:hover {
        color: #c0392b;
    }
</style>
@endsection

@section('content')
    <!-- Page Heading -->
    <div class="bg-white p-2 d-sm-flex align-items-center justify-content-between mb-4">
        <h1 class="h5 mb-0 text-gray-800">UEPL | Edit RFQ</h1>
        <div class="display-date">
            <span id="day">day</span>,
            <span id="daynum">00</span>
            <span id="month">month</span>
            <span id="year">0000</span>
        </div>
        <div class="display-time"></div>
    </div>

    <!-- Alerts -->
    @if (session('success'))
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="fas fa-check-circle mr-2"></i>{{ session('success') }}
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
    @endif
    @if (session('error'))
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <i class="fas fa-exclamation-circle mr-2"></i>{{ session('error') }}
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
    @endif
    @if ($errors->any())
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <i class="fas fa-exclamation-triangle mr-2"></i>
            <strong>Please fix the following errors:</strong>
            <ul class="mb-0 mt-2">
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
    @endif

    <form id="rfqForm" action="{{ route('superadmin.salesbom.rfq.update', $rfq->id) }}" method="POST" enctype="multipart/form-data">
        @csrf
        @method('PUT')

        <!-- RFQ Basic Information -->
        <div class="card section-card">
            <div class="card-header">
                <i class="fas fa-file-alt mr-2"></i> RFQ Information
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-4 mb-3">
                        <label class="form-label">RFQ No <span class="required-star">*</span></label>
                        <input type="text" name="rfqNo" class="form-control" value="{{ $rfq->rfq_no }}" readonly>
                    </div>
                    <div class="col-md-4 mb-3">
                        <label class="form-label">RFQ Date <span class="required-star">*</span></label>
                        <input type="date" name="rfqDate" class="form-control" value="{{ $rfq->rfq_date }}" required>
                    </div>
                    <div class="col-md-4 mb-3">
                        <label class="form-label">Customer Reference No</label>
                        <input type="text" name="cusRefNo" class="form-control" value="{{ $rfq->cus_ref_no }}">
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-4 mb-3">
                        <label class="form-label">Customer <span class="required-star">*</span></label>
                        <select name="customer" class="form-control" required>
                            <option value="">Select Customer</option>
                            @foreach ($customers as $customer)
                                <option value="{{ $customer->id }}" {{ $rfq->customer == $customer->id ? 'selected' : '' }}>
                                    {{ $customer->company }}
                                </option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-md-4 mb-3">
                        <label class="form-label">RFQ Type <span class="required-star">*</span></label>
                        <select id="rfqType" name="rfqType" class="form-control" required>
                            <option value="">Select RFQ Type</option>
                            @foreach($rfqTypes as $type)
                                <option value="{{ $type->rfqtype }}" {{ $rfq->rfq_type == $type->rfqtype ? 'selected' : '' }}>
                                    {{ $type->rfqtype }}
                                </option>
                            @endforeach
                            <option value="other" {{ !$rfqTypes->contains('rfqtype', $rfq->rfq_type) && $rfq->rfq_type ? 'selected' : '' }}>Other</option>
                        </select>
                        <input type="text" name="other_rfq_type" id="other-rfq-type" class="form-control mt-2"
                            placeholder="Enter RFQ Type" value="{{ !$rfqTypes->contains('rfqtype', $rfq->rfq_type) ? $rfq->rfq_type : '' }}" style="display: none;">
                    </div>
                    <div class="col-md-4 mb-3">
                        <label class="form-label">Product Type <span class="required-star">*</span></label>
                        <select id="productType" name="productType" class="form-control" required>
                            <option value="">Select Product Type</option>
                            @foreach($productTypes as $type)
                                <option value="{{ $type->name }}" {{ $rfq->product_type == $type->name ? 'selected' : '' }}>
                                    {{ $type->name }}
                                </option>
                            @endforeach
                            <option value="other" {{ !$productTypes->contains('name', $rfq->product_type) && $rfq->product_type ? 'selected' : '' }}>Other</option>
                        </select>
                        <input type="text" name="other_product_type" id="other-product-type" class="form-control mt-2"
                            placeholder="Enter Product Type" value="{{ !$productTypes->contains('name', $rfq->product_type) ? $rfq->product_type : '' }}" style="display: none;">
                    </div>
                </div>
            </div>
        </div>

        <!-- Product Details -->
        <div class="card section-card">
            <div class="card-header bg-info-gradient">
                <i class="fas fa-cube mr-2"></i> Product Details
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-4 mb-3">
                        <label class="form-label">Part No</label>
                        <input type="text" name="partNo" class="form-control" value="{{ $rfq->part_no }}">
                    </div>
                    <div class="col-md-4 mb-3">
                        <label class="form-label">Project/Material No</label>
                        <input type="text" name="project_materialNo" class="form-control" value="{{ $rfq->project_material_no }}">
                    </div>
                    <div class="col-md-4 mb-3">
                        <label class="form-label">Description</label>
                        <input type="text" name="description" class="form-control" value="{{ $rfq->description }}">
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-3 mb-3">
                        <label class="form-label">Drawing No</label>
                        <input type="text" name="drawingNo" class="form-control" value="{{ $rfq->drawing_no }}">
                    </div>
                    <div class="col-md-3 mb-3">
                        <label class="form-label">Drawing Revision</label>
                        <input type="text" name="drawingRev" class="form-control" value="{{ $rfq->drawing_rev }}">
                    </div>
                    <div class="col-md-3 mb-3">
                        <label class="form-label">Quantity <span class="required-star">*</span></label>
                        <input type="number" name="quantity" class="form-control" value="{{ $rfq->quantity }}" required>
                    </div>
                    <div class="col-md-3 mb-3">
                        <label class="form-label">UOM <span class="required-star">*</span></label>
                        <input type="text" name="uom" class="form-control" value="{{ $rfq->uom }}" required>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-12 mb-3">
                        <label class="form-label">Notes</label>
                        <textarea name="note" class="form-control" rows="2">{{ $rfq->note }}</textarea>
                    </div>
                </div>
            </div>
        </div>

        <!-- Raw Materials -->
        <div class="card section-card">
            <div class="card-header bg-success-gradient">
                <i class="fas fa-layer-group mr-2"></i> Raw Materials <span class="required-star">*</span>
            </div>
            <div class="card-body">
                <div id="materials-wrapper">
                    <!-- Materials will be loaded by JS -->
                </div>
                <button type="button" id="add-material" class="btn btn-outline-success btn-sm mt-2">
                    <i class="fas fa-plus mr-1"></i> Add Material
                </button>
            </div>
        </div>

        <!-- File Attachments -->
        <div class="card section-card">
            <div class="card-header bg-warning-gradient">
                <i class="fas fa-paperclip mr-2"></i> File Attachments
            </div>
            <div class="card-body">
                @php
                    $fileLabels = [
                        'drawing' => ['label' => 'Drawing File', 'input' => 'drawingFiles'],
                        'material_spec' => ['label' => 'Material Specification File', 'input' => 'materialSpecificationFiles'],
                        'rfq_form' => ['label' => 'RFQ Form File', 'input' => 'rfqFormFiles'],
                        'annexure' => ['label' => 'Annexure File', 'input' => 'annexureFiles']
                    ];
                @endphp

                <div class="row">
                    @foreach ($fileLabels as $type => $info)
                        @php
                            $files = $rfq->rfqFiles->where('file_type', $type);
                        @endphp
                        <div class="col-md-6 mb-3">
                            <label class="form-label">{{ $info['label'] }}</label>

                            <!-- Existing Files -->
                            @if ($files->count())
                                <div class="mb-2">
                                    @foreach ($files as $file)
                                        <div class="existing-file" id="fileRow_{{ $file->id }}">
                                            <i class="fas fa-file text-primary"></i>
                                            <a href="{{ '/induspro/public' . Storage::url($file->file_path) }}" target="_blank">
                                                {{ Str::limit($file->file_name, 30) }}
                                            </a>
                                            <i class="fas fa-times delete-file-btn ml-auto" onclick="deleteRfqFile({{ $file->id }})" title="Delete"></i>
                                        </div>
                                    @endforeach
                                </div>
                            @endif

                            <input type="file" name="{{ $info['input'] }}[]" class="form-control" multiple accept=".pdf,image/*">
                            <div id="{{ $info['input'] }}_preview" class="file-preview"></div>
                            <small class="text-muted">Accepts: PDF, JPG, PNG</small>
                        </div>
                    @endforeach
                </div>
            </div>
        </div>

        <!-- Form Actions -->
        <div class="d-flex justify-content-between mb-4">
            <a href="{{ route('superadmin.salesbom.rfq.rfqdetails') }}" class="btn btn-secondary">
                <i class="fas fa-arrow-left mr-1"></i> Back to List
            </a>
            <button type="submit" class="btn btn-success" id="submitBtn">
                <span class="spinner-border spinner-border-sm d-none" role="status"></span>
                <span class="btn-text"><i class="fas fa-save mr-1"></i> Update RFQ</span>
            </button>
        </div>
    </form>

    <!-- Modal for Adding Raw Material -->
    <div class="modal fade" id="addRawMaterialModal" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <form id="addRawMaterialForm">
                <div class="modal-content">
                    <div class="modal-header bg-success text-white py-2">
                        <h6 class="modal-title"><i class="fas fa-plus-circle mr-2"></i>Add New Raw Material</h6>
                        <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                            <span>&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <div class="form-group">
                            <label class="form-label">Raw Material Name <span class="required-star">*</span></label>
                            <input type="text" name="name" class="form-control" required>
                        </div>
                        <div class="form-group">
                            <label class="form-label">ISO Specification <span class="required-star">*</span></label>
                            <input type="text" name="iso_specification" class="form-control" required>
                        </div>
                        <div class="form-group">
                            <label class="form-label">Material Density</label>
                            <input type="text" name="density" class="form-control">
                        </div>
                        <div class="form-group">
                            <label class="form-label">Mechanical Properties</label>
                            <input type="text" name="mechanical_properties" class="form-control">
                        </div>
                    </div>
                    <div class="modal-footer py-2">
                        <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-success btn-sm">
                            <i class="fas fa-plus mr-1"></i> Add Material
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>
@endsection

@section('scripts')
<script>
$(document).ready(function() {
    // Load all raw materials for the selects
    let allMaterials = [];
    let initialMaterials = {!! json_encode(is_array(json_decode($rfq->raw_material, true)) ? json_decode($rfq->raw_material, true) : []) !!};

    function loadRawMaterialsSelects(callback) {
        $.get('{{ route('superadmin.salesbom.rawmaterials.list') }}', function(data) {
            allMaterials = data;
            renderMaterialRows();
            if (callback) callback();
        });
    }

    function renderMaterialRows() {
        let html = '';
        if (!Array.isArray(initialMaterials)) initialMaterials = [];
        initialMaterials = initialMaterials.filter(x => !!x);

        for (let i = 0; i < Math.max(initialMaterials.length, 1); i++) {
            html += buildMaterialRow(initialMaterials[i] || '');
        }
        $('#materials-wrapper').html(html);
        setTimeout(disableDuplicateOptions, 100);
    }

    function buildMaterialRow(selectedVal) {
        let select = `<select name="rawmaterials[]" class="form-control raw-material-select" required>`;
        select += '<option value="">Select Raw Material</option>';
        allMaterials.forEach(mat => {
            let sel = (mat.id == selectedVal) ? 'selected' : '';
            select += `<option value="${mat.id}" ${sel}>${mat.rm_grade} (${mat.iso_specification})</option>`;
        });
        select += '</select>';
        return `
            <div class="material-row">
                <div class="input-group">
                    ${select}
                    <div class="input-group-append">
                        <button type="button" class="btn btn-danger remove-material" title="Remove">
                            <i class="fas fa-trash-alt"></i>
                        </button>
                    </div>
                </div>
            </div>
        `;
    }

    function disableDuplicateOptions() {
        let selectedVals = [];
        $('.raw-material-select').each(function() {
            let val = $(this).val();
            if (val) selectedVals.push(val);
        });
        $('.raw-material-select').each(function() {
            let currentVal = $(this).val();
            $(this).find('option').each(function() {
                let optVal = $(this).val();
                if (optVal && optVal !== currentVal && selectedVals.includes(optVal)) {
                    $(this).prop('disabled', true);
                } else {
                    $(this).prop('disabled', false);
                }
            });
        });
    }

    // Show/hide Other fields
    function toggleOtherFields() {
        $('#other-rfq-type').toggle($('#rfqType').val() === 'other');
        $('#other-product-type').toggle($('#productType').val() === 'other');
    }

    $('#rfqType').on('change', toggleOtherFields);
    $('#productType').on('change', toggleOtherFields);
    toggleOtherFields(); // Initial check

    // Add new material row
    $(document).on('click', '#add-material', function() {
        $('#materials-wrapper').append(buildMaterialRow(''));
        setTimeout(disableDuplicateOptions, 100);
    });

    // Remove material row
    $(document).on('click', '.remove-material', function() {
        if ($('.material-row').length > 1) {
            $(this).closest('.material-row').remove();
            disableDuplicateOptions();
        } else {
            showToast('error', 'At least one raw material is required');
        }
    });

    // Handle select change for duplicate prevention
    $(document).on('change', '.raw-material-select', function() {
        disableDuplicateOptions();
    });

    // Store new raw material via modal
    $('#addRawMaterialForm').submit(function(e) {
        e.preventDefault();
        let form = this;
        $.ajax({
            url: '{{ route('superadmin.salesbom.rawmaterials.store') }}',
            method: 'POST',
            data: $(form).serialize(),
            headers: {
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            },
            success: function(response) {
                if (response.success) {
                    $('#addRawMaterialModal').modal('hide');
                    form.reset();
                    loadRawMaterialsSelects(function() {
                        $('.raw-material-select').last().val(response.material.id);
                        disableDuplicateOptions();
                    });
                    showToast('success', 'Raw material added successfully');
                }
            },
            error: function() {
                showToast('error', 'Error adding new raw material');
            }
        });
    });

    // Form submit with loading
    $('#rfqForm').on('submit', function() {
        var $btn = $('#submitBtn');
        $btn.prop('disabled', true);
        $btn.find('.spinner-border').removeClass('d-none');
        $btn.find('.btn-text').text('Updating...');
    });

    // File preview
    const previewFileInputs = ['drawingFiles', 'materialSpecificationFiles', 'rfqFormFiles', 'annexureFiles'];
    previewFileInputs.forEach(function(inputId) {
        $(document).on('change', `input[name="${inputId}[]"]`, function(event) {
            const previewContainer = $(`#${inputId}_preview`);
            previewContainer.html('');

            const files = event.target.files;
            if (files.length > 0) {
                Array.from(files).forEach(file => {
                    const fileType = file.type;
                    if (fileType.startsWith('image/')) {
                        const reader = new FileReader();
                        reader.onload = function(e) {
                            previewContainer.append(`<img src="${e.target.result}" class="img-thumbnail">`);
                        };
                        reader.readAsDataURL(file);
                    } else {
                        previewContainer.append(`<a href="#" class="d-block text-primary"><i class="fas fa-file mr-1"></i>${file.name}</a>`);
                    }
                });
            }
        });
    });

    // Toast notification helper
    function showToast(type, message) {
        var bgClass = type === 'success' ? 'bg-success' : 'bg-danger';
        var icon = type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle';

        var toastHtml = `
            <div class="toast ${bgClass} text-white" role="alert" aria-live="assertive" aria-atomic="true" data-delay="3000" style="position: fixed; top: 20px; right: 20px; z-index: 9999; min-width: 250px;">
                <div class="toast-body d-flex align-items-center">
                    <i class="fas ${icon} mr-2"></i>
                    <span>${message}</span>
                    <button type="button" class="ml-auto close text-white" data-dismiss="toast" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            </div>
        `;

        var $toast = $(toastHtml);
        $('body').append($toast);
        $toast.toast('show');

        $toast.on('hidden.bs.toast', function() {
            $(this).remove();
        });
    }

    // Load materials on page load
    loadRawMaterialsSelects();
});

// Delete RFQ File
function deleteRfqFile(fileId) {
    if (!confirm("Are you sure you want to delete this file?")) return;

    let route = "{{ route('superadmin.salesbom.rfq.deletefile', ':id') }}".replace(':id', fileId);

    fetch(route, {
        method: "DELETE",
        headers: {
            "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]').content,
            "Content-Type": "application/json"
        }
    })
    .then(res => res.json())
    .then(res => {
        if (res.success) {
            document.getElementById('fileRow_' + fileId)?.remove();
        } else {
            alert(res.message);
        }
    })
    .catch(err => {
        console.error(err);
        alert("An error occurred while deleting.");
    });
}
</script>
@endsection
