@extends('layouts.dashboard.superadminapp')

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

<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />

@section('content')

<style>
/* ==================== MODERN PAGE HEADER ==================== */
.page-header-compact {
    background: linear-gradient(135deg, #fff 0%, #f8fafc 100%);
    border-radius: 1rem;
    padding: 1.25rem 1.5rem;
    box-shadow: 0 1px 3px 0 rgb(0 0 0 / 0.1);
    margin-bottom: 1.5rem;
}

.page-header-compact h1 {
    font-size: 1.25rem;
    font-weight: 600;
    color: #1e293b;
    margin: 0;
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.page-header-compact h1 i {
    color: #06b6d4;
    font-size: 1.125rem;
}

.datetime-display {
    display: flex;
    align-items: center;
    gap: 1rem;
    flex-wrap: wrap;
}

.datetime-display .time {
    font-size: 0.875rem;
    color: #64748b;
    font-weight: 500;
    font-family: 'SF Mono', 'Monaco', monospace;
    background: #f1f5f9;
    padding: 0.375rem 0.75rem;
    border-radius: 0.5rem;
    display: flex;
    align-items: center;
    gap: 0.375rem;
}

.datetime-display .time i {
    color: #06b6d4;
}

/* ==================== SECTION CARDS ==================== */
.section-card {
    background: #fff;
    border-radius: 1rem;
    overflow: hidden;
    box-shadow: 0 1px 3px 0 rgb(0 0 0 / 0.1);
    margin-bottom: 1.5rem;
    transition: all 0.2s ease;
}

.section-card:hover {
    box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1);
}

.section-header {
    padding: 1rem 1.5rem;
    font-weight: 600;
    font-size: 1rem;
    color: #fff;
    display: flex;
    align-items: center;
    gap: 0.625rem;
}

.section-header i {
    font-size: 1.125rem;
}

.section-card .card-body {
    padding: 1.5rem;
}

/* Section Color Variants */
.section-card.teal .section-header {
    background: linear-gradient(135deg, #06b6d4 0%, #0891b2 100%);
}

.section-card.blue .section-header {
    background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
}

.section-card.cyan .section-header {
    background: linear-gradient(135deg, #22d3ee 0%, #06b6d4 100%);
}

.section-card.amber .section-header {
    background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
}

.section-card.green .section-header {
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
}

.section-card.slate .section-header {
    background: linear-gradient(135deg, #64748b 0%, #475569 100%);
}

/* ==================== FORM CONTROLS ==================== */
.form-control,
.form-select {
    border: 2px solid #e2e8f0;
    border-radius: 0.5rem;
    padding: 0.625rem 0.875rem;
    font-size: 0.9375rem;
    transition: all 0.2s ease;
    background: #f8fafc;
}

.form-control:hover,
.form-select:hover {
    border-color: #cbd5e1;
}

.form-control:focus,
.form-select:focus {
    border-color: #06b6d4;
    box-shadow: 0 0 0 4px rgba(6, 182, 212, 0.1);
    background: #fff;
    outline: none;
}

label {
    font-weight: 500;
    color: #475569;
    margin-bottom: 0.5rem;
    font-size: 0.875rem;
    display: block;
}

label .text-danger {
    color: #ef4444;
}

textarea.form-control {
    min-height: 100px;
    resize: vertical;
}

/* ==================== FILE ATTACHMENTS ==================== */
.existing-files {
    margin-bottom: 1rem;
}

.file-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0.75rem 1rem;
    background: #f8fafc;
    border: 1px solid #e2e8f0;
    border-radius: 0.5rem;
    margin-bottom: 0.5rem;
    transition: all 0.2s ease;
}

.file-item:hover {
    background: #f1f5f9;
    border-color: #cbd5e1;
}

.file-item a {
    color: #06b6d4;
    text-decoration: none;
    font-size: 0.9375rem;
    font-weight: 500;
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.file-item a:hover {
    color: #0891b2;
}

.file-item .btn-delete {
    background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
    color: #fff;
    border: none;
    padding: 0.375rem 0.75rem;
    border-radius: 0.375rem;
    font-size: 0.875rem;
    cursor: pointer;
    transition: all 0.2s ease;
}

.file-item .btn-delete:hover {
    box-shadow: 0 4px 12px rgba(239, 68, 68, 0.4);
    transform: translateY(-1px);
}

/* ==================== ITEMS TABLE ==================== */
.items-table {
    width: 100%;
    border-collapse: separate;
    border-spacing: 0;
    font-size: 0.9375rem;
}

.items-table thead th {
    background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
    border-bottom: 2px solid #e2e8f0;
    color: #475569;
    font-weight: 600;
    text-transform: uppercase;
    font-size: 0.75rem;
    letter-spacing: 0.5px;
    padding: 0.875rem 0.75rem;
    white-space: nowrap;
    text-align: left;
}

.items-table tbody tr {
    transition: all 0.15s ease;
}

.items-table tbody tr:hover {
    background: #f8fafc;
}

.items-table tbody td {
    padding: 0.75rem;
    vertical-align: middle;
    border-bottom: 1px solid #f1f5f9;
}

.items-table tbody tr:last-child td {
    border-bottom: none;
}

.items-table .form-control,
.items-table .form-select {
    font-size: 0.875rem;
    padding: 0.5rem 0.75rem;
    background: #fff;
}

.items-table .btn-delete-row {
    background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
    color: #fff;
    border: none;
    padding: 0.5rem 0.75rem;
    border-radius: 0.375rem;
    cursor: pointer;
    transition: all 0.2s ease;
}

.items-table .btn-delete-row:hover {
    box-shadow: 0 4px 12px rgba(239, 68, 68, 0.4);
    transform: translateY(-1px);
}

/* ==================== BUTTONS ==================== */
.btn-add-row {
    background: linear-gradient(135deg, #06b6d4 0%, #0891b2 100%);
    color: #fff;
    border: none;
    padding: 0.625rem 1.25rem;
    border-radius: 0.5rem;
    font-weight: 500;
    font-size: 0.9375rem;
    cursor: pointer;
    transition: all 0.2s ease;
    box-shadow: 0 1px 2px 0 rgb(0 0 0 / 0.05);
}

.btn-add-row:hover {
    box-shadow: 0 4px 12px rgba(6, 182, 212, 0.4);
    transform: translateY(-1px);
}

.btn-add-row i {
    margin-right: 0.5rem;
}

.form-actions {
    display: flex;
    justify-content: flex-end;
    gap: 0.75rem;
    padding-top: 1.5rem;
    border-top: 1px solid #e2e8f0;
}

.btn {
    border-radius: 0.5rem;
    padding: 0.625rem 1.25rem;
    font-weight: 500;
    transition: all 0.2s ease;
    border: none;
    box-shadow: 0 1px 2px 0 rgb(0 0 0 / 0.05);
    font-size: 0.9375rem;
}

.btn:hover {
    transform: translateY(-1px);
    box-shadow: 0 1px 3px 0 rgb(0 0 0 / 0.1);
}

.btn-secondary {
    background: linear-gradient(135deg, #64748b 0%, #475569 100%);
    color: #fff;
}

.btn-secondary:hover {
    box-shadow: 0 4px 12px rgba(100, 116, 139, 0.4);
}

.btn-success {
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    color: #fff;
}

.btn-success:hover {
    box-shadow: 0 4px 12px rgba(16, 185, 129, 0.4);
}

.btn i {
    margin-right: 0.5rem;
}

/* ==================== SELECT2 OVERRIDES ==================== */
.select2-container {
    z-index: 999999 !important;
}

.select2-container--default .select2-selection--single {
    border: 2px solid #e2e8f0 !important;
    border-radius: 0.5rem !important;
    height: auto !important;
    padding: 0.5rem 0.75rem !important;
    background: #fff !important;
}

.select2-container--default.select2-container--focus .select2-selection--single {
    border-color: #06b6d4 !important;
    box-shadow: 0 0 0 4px rgba(6, 182, 212, 0.1) !important;
}

/* ==================== TOAST NOTIFICATIONS ==================== */
.toast-notification {
    position: fixed;
    top: 2rem;
    right: 2rem;
    background: #fff;
    padding: 1rem 1.25rem;
    border-radius: 0.75rem;
    box-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1);
    display: flex;
    align-items: center;
    gap: 0.75rem;
    min-width: 300px;
    z-index: 9999;
    animation: slideInRight 0.3s ease-out;
}

@keyframes slideInRight {
    from {
        transform: translateX(400px);
        opacity: 0;
    }
    to {
        transform: translateX(0);
        opacity: 1;
    }
}

.toast-notification.success {
    border-left: 4px solid #10b981;
}

.toast-notification.success i {
    color: #10b981;
    font-size: 1.25rem;
}

.toast-notification.error {
    border-left: 4px solid #ef4444;
}

.toast-notification.error i {
    color: #ef4444;
    font-size: 1.25rem;
}

.toast-notification span {
    flex: 1;
    color: #1e293b;
    font-weight: 500;
    font-size: 0.9375rem;
}

.toast-notification .close {
    background: none;
    border: none;
    font-size: 1.25rem;
    color: #94a3b8;
    cursor: pointer;
    padding: 0;
    line-height: 1;
}

.toast-notification .close:hover {
    color: #64748b;
}

/* ==================== RESPONSIVE ==================== */
@media (max-width: 768px) {
    .page-header-compact {
        padding: 1rem;
    }

    .page-header-compact h1 {
        font-size: 1.125rem;
    }

    .section-card .card-body {
        padding: 1rem;
    }

    .form-actions {
        flex-direction: column;
    }

    .btn {
        width: 100%;
    }

    .toast-notification {
        right: 1rem;
        left: 1rem;
        min-width: auto;
    }
}
</style>

<!-- Modern Compact Page Header -->
<div class="page-header-compact d-flex justify-content-between align-items-center flex-wrap">
    <h1>
        <i class="fas fa-edit"></i>
        Edit Purchase RFQ
    </h1>
    <div class="datetime-display">
        <span class="time">
            <i class="far fa-clock"></i>
            <span id="currentTime"></span>
        </span>
    </div>
</div>

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

    <!-- Section 1: RFQ Information (Teal) -->
    <div class="section-card teal">
        <div class="section-header">
            <i class="fas fa-file-alt"></i>
            RFQ Information
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label>RFQ ID <span class="text-danger">*</span></label>
                    <input type="text" id="rfqNo" name="rfqNo" class="form-control" required readonly value="{{ old('rfqNo', $rfq->rfq_no) }}">
                </div>
                <div class="col-md-6 mb-3">
                    <label>RFQ Date <span class="text-danger">*</span></label>
                    <input type="date" id="rfqDate" name="rfqDate" class="form-control" required value="{{ $rfq->rfq_date ? \Illuminate\Support\Carbon::parse($rfq->rfq_date)->format('Y-m-d') : '' }}">
                </div>
            </div>
        </div>
    </div>

    <!-- Section 2: Vendor Information (Blue) -->
    <div class="section-card blue">
        <div class="section-header">
            <i class="fas fa-building"></i>
            Vendor Information
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label>Vendor <span class="text-danger">*</span></label>
                    <select id="vendor" name="vendor" class="form-control" required>
                        <option value="">Select Vendor</option>
                        @foreach ($vendors as $vendor)
                            <option value="{{ $vendor->id }}" {{ old('vendor', $rfq->vendor_id) == $vendor->id ? 'selected' : '' }}>
                                {{ $vendor->company }}
                            </option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-6 mb-3">
                    <label>Vendor Reference No</label>
                    <input type="text" id="venRefNo" name="venRefNo" class="form-control" value="{{ old('venRefNo', $rfq->vendor_reference_no) }}">
                </div>
            </div>
        </div>
    </div>

    <!-- Section 3: Additional Details (Cyan) -->
    <div class="section-card cyan">
        <div class="section-header">
            <i class="fas fa-info-circle"></i>
            Additional Details
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label>RFQ Type <span class="text-danger">*</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 }}" {{ old('rfqType', $rfq->rfq_type) == $type->rfqtype ? 'selected' : '' }}>
                                {{ $type->rfqtype }}
                            </option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-6 mb-3">
                    <label>Delivery Terms</label>
                    <input type="text" id="deliveryTerms" name="deliveryTerms" class="form-control" value="{{ old('deliveryTerms', $rfq->delivery_terms) }}">
                </div>
            </div>
        </div>
    </div>

    <!-- Section 4: RFQ Items (Amber) -->
    <div class="section-card amber">
        <div class="section-header">
            <i class="fas fa-list"></i>
            RFQ Items
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table id="rfqTable" class="items-table">
                    <thead>
                        <tr>
                            <th width="60">Sl.No</th>
                            <th>Item</th>
                            <th>Description</th>
                            <th width="100">Quantity</th>
                            <th width="100">UOM</th>
                            <th width="140">Required By</th>
                            <th width="50"></th>
                        </tr>
                    </thead>
                    <tbody>
                        @if ($rfq->items && $rfq->items->count())
                            @foreach ($rfq->items as $index => $item)
                                <tr>
                                    <td>{{ $index + 1 }}</td>
                                    <td>
                                        <select class="form-control item-select w-100" name="item[]" required>
                                            <option value="">Select Item</option>
                                            @foreach ($stock_items as $stockItem)
                                                <option value="{{ $stockItem->id }}"
                                                    {{ (string) old('item.' . $index, $item->item_id) === (string) $stockItem->id ? 'selected' : '' }}>
                                                    {{ $stockItem->item_name }}
                                                </option>
                                            @endforeach
                                        </select>
                                    </td>
                                    <td><input type="text" name="description[]" class="form-control" value="{{ old('description.' . $index, $item->description) }}"></td>
                                    <td><input type="number" name="quantity[]" class="form-control" min="1" value="{{ old('quantity.' . $index, $item->quantity) }}"></td>
                                    <td><input type="text" name="uom[]" class="form-control" value="{{ old('uom.' . $index, $item->uom) }}"></td>
                                    <td><input type="date" name="requiredBy[]" class="form-control" value="{{ old('requiredBy.' . $index, $item->required_by ? \Carbon\Carbon::parse($item->required_by)->format('Y-m-d') : '') }}"></td>
                                    <td>
                                        <button type="button" class="btn-delete-row" onclick="deleteRow(this)">
                                            <i class="fa fa-trash"></i>
                                        </button>
                                    </td>
                                </tr>
                            @endforeach
                        @else
                            <tr><td colspan="7" class="text-center text-muted">No RFQ items found.</td></tr>
                        @endif
                    </tbody>
                </table>
            </div>
            <button type="button" class="btn-add-row mt-3" onclick="addRow()">
                <i class="fa fa-plus"></i> Add Row
            </button>
        </div>
    </div>

    <!-- Section 5: Notes & Terms (Green) -->
    <div class="section-card green">
        <div class="section-header">
            <i class="fas fa-sticky-note"></i>
            Notes & Terms
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label>Note I</label>
                    <input type="text" id="description" name="description_main" class="form-control" value="{{ old('description_main', $rfq->description) }}">
                </div>
                <div class="col-md-6 mb-3">
                    <label>Note II</label>
                    <textarea id="note" name="note" class="form-control" rows="3">{{ old('note', $rfq->note) }}</textarea>
                </div>
            </div>
        </div>
    </div>

    <!-- Section 6: File Attachments (Slate) -->
    <div class="section-card slate">
        <div class="section-header">
            <i class="fas fa-paperclip"></i>
            File Attachments
        </div>
        <div class="card-body">
            @php
                $annexureFiles = $rfq->rfqFiles->where('file_type', 'annexure');
            @endphp
            @if ($annexureFiles && $annexureFiles->count())
                <div class="existing-files">
                    <label>Existing Files</label>
                    @foreach ($annexureFiles as $file)
                        <div class="file-item" id="fileRow_{{ $file->id }}">
                            <a href="{{ asset('storage/' . $file->file_path) }}" target="_blank">
                                <i class="fas fa-file"></i>{{ $file->file_name }}
                            </a>
                            <button type="button" onclick="deleteRfqFile({{ $file->id }})" class="btn-delete">
                                <i class="fas fa-times"></i> Delete
                            </button>
                        </div>
                    @endforeach
                </div>
            @endif
            <div class="row">
                <div class="col-md-12">
                    <label>Annexure Files</label>
                    <input type="file" id="annexureFiles" name="annexureFiles[]" class="form-control" multiple accept=".pdf,image/*">
                    <div id="annexureFiles_preview" class="mt-2"></div>
                </div>
            </div>
        </div>
    </div>

    <!-- Form Actions -->
    <div class="form-actions">
        <a href="{{ route('superadmin.purchasebom.rfq.rfqdetails') }}" class="btn btn-secondary">
            <i class="fas fa-arrow-left"></i> Back
        </a>
        <button class="btn btn-success" type="submit">
            <i class="fas fa-save"></i> Update RFQ
        </button>
    </div>
</form>

@endsection

@section('scripts')

<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>

// ==================== LIVE DATE & TIME ====================
function updateDateTime() {
    const now = new Date();
    const timeOptions = { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: true };
    document.getElementById('currentTime').textContent = now.toLocaleTimeString('en-US', timeOptions);
}
setInterval(updateDateTime, 1000);
updateDateTime();

// ==================== TOAST NOTIFICATIONS ====================
function showToast(type, message) {
    const toast = document.createElement('div');
    toast.className = `toast-notification ${type}`;
    toast.innerHTML = `
        <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-circle'}"></i>
        <span>${message}</span>
        <button class="close" onclick="this.parentElement.remove()">&times;</button>
    `;
    document.body.appendChild(toast);

    setTimeout(() => {
        if (toast.parentElement) {
            toast.remove();
        }
    }, 3500);
}

// Show session messages as toasts
@if (session('success'))
    showToast('success', "{{ session('success') }}");
@endif
@if (session('error'))
    showToast('error', "{{ session('error') }}");
@endif

// ==================== RFQ ITEMS TABLE ====================
const rfqItems = @json($rfq->items);

// Delete a row from RFQ table
function deleteRow(btn) {
    const row = btn.closest('tr');
    row.remove();
    updateSlNo();
}

// Update Serial Numbers after deletion
function updateSlNo() {
    const rows = document.querySelectorAll("#rfqTable tbody tr");
    rows.forEach((row, index) => {
        row.cells[0].textContent = index + 1;
    });
}

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

    let route = "{{ route('superadmin.purchasebom.rfq.deletefile', ['id' => '__file_id__']) }}";
    route = route.replace('__file_id__', fileId);

    fetch(route, {
        method: 'DELETE',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': '{{ csrf_token() }}',
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            document.getElementById('fileRow_' + fileId).remove();
            showToast('success', 'File deleted successfully.');
        } else {
            showToast('error', 'Error deleting file.');
        }
    })
    .catch(error => {
        console.error(error);
        showToast('error', 'Something went wrong while deleting the file.');
    });
}

// ==================== SELECT2 INITIALIZATION ====================
function initializeSelect2() {
    $('.item-select').each(function () {
        const $this = $(this);
        if ($this.hasClass("select2-hidden-accessible")) {
            $this.select2('destroy');
        }
        $this.select2({
            dropdownParent: $('#rfqform'),
            width: 'resolve',
            placeholder: "Select Item",
            allowClear: true
        });
    });
}

// Initialize existing selects on page load
$(document).ready(function () {
    initializeSelect2();

    // Apply selected values explicitly from JSON (ensures correctness)
    rfqItems.forEach((item, index) => {
        const select = $(`select[name='item[]']`).eq(index);

        console.log(select.length, rfqItems, item.item);
        if (select.length) {
            select.val(String(item.item)).trigger('change.select2');
        }
    });
});

// Modify addRow() to call initializeSelect2
function addRow() {
    const tbody = document.querySelector("#rfqTable tbody");
    const rowCount = tbody.rows.length;
    const stockItems = @json($stock_items);

    const tr = document.createElement('tr');

    tr.innerHTML = `
        <td>${rowCount + 1}</td>
        <td>
            <select name="item[]" class="form-select item-select w-100" required>
                <option value="">Select Item</option>
                ${stockItems.map(item => `<option value="${item.id}">${item.item_name}</option>`).join('')}
            </select>
        </td>
        <td><input type="text" name="description[]" class="form-control" /></td>
        <td><input type="number" name="quantity[]" class="form-control" min="1" /></td>
        <td><input type="text" name="uom[]" class="form-control" /></td>
        <td><input type="date" name="requiredBy[]" class="form-control" /></td>
        <td><button type="button" class="btn-delete-row" onclick="deleteRow(this)">
            <i class="fa fa-trash"></i></button>
        </td>
    `;

    tbody.appendChild(tr);
    initializeSelect2(); // Reinitialize for new dropdown
}

</script>

@endsection
