@extends('layouts.dashboard.superadminapp')
@section('title', 'Edit GRN Order')

@section('styles')
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<style>
    /* Modern Page Header */
    .modern-page-header {
        background: linear-gradient(135deg, #ffffff 0%, #f0fdfa 100%);
        border-radius: 1rem;
        padding: 1.25rem 1.5rem;
        box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        margin-bottom: 1.5rem;
        display: flex;
        justify-content: space-between;
        align-items: center;
        flex-wrap: wrap;
        gap: 1rem;
    }

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

    .header-right {
        display: flex;
        align-items: center;
        gap: 1.5rem;
    }

    .display-date {
        font-size: 0.875rem;
        color: #64748b;
        font-weight: 500;
    }

    .display-time {
        font-family: 'SF Mono', 'Monaco', monospace;
        background: #ecfeff;
        color: #0e7490;
        padding: 0.375rem 0.75rem;
        border-radius: 0.5rem;
        font-size: 0.875rem;
        font-weight: 600;
    }

    /* Section Cards */
    .section-card {
        background: #ffffff;
        border-radius: 1rem;
        box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        margin-bottom: 1.5rem;
        overflow: hidden;
        border: 1px solid #e2e8f0;
    }

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

    .section-card.teal .section-header {
        background: linear-gradient(135deg, #06b6d4 0%, #0891b2 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 .card-body {
        padding: 1.5rem;
    }

    /* Modern Form Controls */
    .form-control {
        border: 2px solid #e2e8f0;
        border-radius: 0.5rem;
        padding: 0.625rem 1rem;
        font-size: 0.875rem;
        transition: all 0.2s;
        background: #f8fafc;
    }

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

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

    .form-control[readonly] {
        background: #f1f5f9;
        color: #64748b;
        cursor: not-allowed;
    }

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

    label .text-danger {
        color: #ef4444;
        margin-left: 0.25rem;
    }

    /* Enhanced Table */
    .table-responsive {
        border-radius: 0.75rem;
        overflow: hidden;
        box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        margin-bottom: 1rem;
    }

    #productTable {
        margin-bottom: 0;
    }

    #productTable thead th {
        background: linear-gradient(135deg, #f0fdfa 0%, #ccfbf1 100%);
        border-bottom: 2px solid #06b6d4;
        color: #0e7490;
        font-weight: 600;
        text-transform: uppercase;
        font-size: 0.75rem;
        letter-spacing: 0.5px;
        padding: 1rem;
        white-space: nowrap;
    }

    #productTable tbody tr {
        transition: all 0.15s;
    }

    #productTable tbody tr:hover {
        background: #f0fdfa;
    }

    #productTable tbody td {
        padding: 0.75rem;
        vertical-align: middle;
        border-bottom: 1px solid #e2e8f0;
    }

    #productTable input.form-control {
        padding: 0.375rem 0.625rem;
        font-size: 0.875rem;
        min-height: 38px;
    }

    #productTable .select2-container {
        width: 100% !important;
    }

    #productTable .select2-selection--single {
        height: 38px !important;
        padding: 2px 5px;
        font-size: 0.875rem;
    }

    /* Modern Buttons */
    .btn {
        border-radius: 0.5rem;
        padding: 0.625rem 1.25rem;
        font-weight: 500;
        transition: all 0.2s;
        border: none;
        font-size: 0.875rem;
        display: inline-flex;
        align-items: center;
        gap: 0.5rem;
    }

    .btn:hover {
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
    }

    .btn-primary {
        background: linear-gradient(135deg, #06b6d4 0%, #0891b2 100%);
        color: #ffffff;
    }

    .btn-primary:hover {
        background: linear-gradient(135deg, #0891b2 0%, #0e7490 100%);
        box-shadow: 0 4px 12px rgba(6, 182, 212, 0.4);
    }

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

    .btn-success:hover {
        background: linear-gradient(135deg, #059669 0%, #047857 100%);
        box-shadow: 0 4px 12px rgba(16, 185, 129, 0.4);
    }

    .btn-danger {
        background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
        color: #ffffff;
    }

    .btn-danger:hover {
        background: linear-gradient(135deg, #dc2626 0%, #b91c1c 100%);
        box-shadow: 0 4px 12px rgba(239, 68, 68, 0.4);
    }

    .btn-outline-secondary {
        background: transparent;
        border: 2px solid #cbd5e1;
        color: #64748b;
    }

    .btn-outline-secondary:hover {
        background: #f8fafc;
        border-color: #94a3b8;
        color: #475569;
    }

    .btn-sm {
        padding: 0.375rem 0.875rem;
        font-size: 0.8125rem;
    }

    /* Select2 Enhancement */
    .select2-container .select2-selection--single {
        height: 38px;
        border: 2px solid #e2e8f0;
        border-radius: 0.5rem;
        background: #f8fafc;
    }

    .select2-container--default .select2-selection--single .select2-selection__rendered {
        line-height: 34px;
        color: #1e293b;
    }

    .select2-container--default .select2-selection--single .select2-selection__arrow {
        height: 34px;
    }

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

    /* Toast Notifications */
    .toast-container {
        position: fixed;
        top: 20px;
        right: 20px;
        z-index: 9999;
    }

    .toast {
        background: #ffffff;
        border-radius: 0.75rem;
        box-shadow: 0 10px 25px rgba(0,0,0,0.2);
        padding: 1rem 1.25rem;
        margin-bottom: 1rem;
        display: flex;
        align-items: center;
        gap: 0.75rem;
        min-width: 300px;
        animation: slideIn 0.3s ease;
        border-left: 4px solid;
    }

    .toast.success {
        border-left-color: #10b981;
    }

    .toast.error {
        border-left-color: #ef4444;
    }

    .toast-icon {
        font-size: 1.25rem;
    }

    .toast.success .toast-icon {
        color: #10b981;
    }

    .toast.error .toast-icon {
        color: #ef4444;
    }

    .toast-message {
        flex: 1;
        color: #1e293b;
        font-size: 0.875rem;
    }

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

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

    /* File Link Styling */
    .current-file-link {
        display: inline-flex;
        align-items: center;
        gap: 0.5rem;
        padding: 0.5rem 0.75rem;
        background: linear-gradient(135deg, #f0fdfa 0%, #ccfbf1 100%);
        border: 2px solid #06b6d4;
        border-radius: 0.5rem;
        color: #0e7490;
        font-size: 0.875rem;
        text-decoration: none;
        margin-top: 0.5rem;
        transition: all 0.2s;
    }

    .current-file-link:hover {
        background: linear-gradient(135deg, #ccfbf1 0%, #99f6e4 100%);
        color: #155e75;
        transform: translateY(-1px);
    }

    /* Responsive */
    @media (max-width: 768px) {
        .modern-page-header {
            flex-direction: column;
            align-items: flex-start;
        }

        .header-right {
            width: 100%;
            justify-content: space-between;
        }
    }
</style>
@endsection

@section('content')

<!-- Toast Container -->
<div class="toast-container" id="toastContainer"></div>

<!-- Modern Page Header -->
<div class="modern-page-header">
    <h1>
        <i class="fas fa-edit" style="color: #06b6d4;"></i>
        Edit Goods Received Note
    </h1>
    <div class="header-right">
        <div class="display-date">
            <span id="day">{{ now()->format('l') }}</span>,
            <span id="daynum">{{ now()->format('d') }}</span>
            <span id="month">{{ now()->format('F') }}</span>
            <span id="year">{{ now()->format('Y') }}</span>
        </div>
        <div class="display-time" id="current-time">{{ now()->format('h:i:s A') }}</div>
    </div>
</div>

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

    <!-- Section 1: GRN Information -->
    <div class="section-card teal">
        <div class="section-header">
            <i class="fas fa-file-alt"></i>
            GRN Information
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-3 mb-3">
                    <label>GRN ID <span class="text-danger">*</span></label>
                    <input type="text" id="grnNo" name="grn_no" class="form-control" value="{{ $grn->grn_no }}" readonly>
                </div>
                <div class="col-md-3 mb-3">
                    <label>GRN Date <span class="text-danger">*</span></label>
                    <input type="date" id="grnDate" name="grn_date" class="form-control" value="{{ $grn->grn_date }}" required>
                </div>
                <div class="col-md-3 mb-3">
                    <label>Order ID <span class="text-danger">*</span></label>
                    <input type="text" id="orderNo" name="order_no" class="form-control" value="{{ $grn->order_no }}" required>
                </div>
                <div class="col-md-3 mb-3">
                    <label>Order Date <span class="text-danger">*</span></label>
                    <input type="date" id="orderDate" name="order_date" class="form-control" value="{{ $grn->order_date }}" required>
                </div>
            </div>

            <div class="row">
                <div class="col-md-6 mb-3">
                    <label>Order Reference No</label>
                    <input type="text" id="orderRefNo" name="order_ref_no" class="form-control" value="{{ $grn->order_ref_no }}">
                </div>
                <div class="col-md-6 mb-3">
                    <label>Upload Challan (PDF)</label>
                    <input type="file" id="grnChallan" name="challan" accept=".pdf" class="form-control">
                    @if($grn->challan_file)
                        <a href="{{ asset('storage/' . $grn->challan_file) }}" target="_blank" class="current-file-link">
                            <i class="fas fa-file-pdf"></i>
                            View Current Challan
                        </a>
                    @endif
                </div>
            </div>
        </div>
    </div>

    <!-- Section 2: Company/Vendor Details -->
    <div class="section-card cyan">
        <div class="section-header">
            <i class="fas fa-building"></i>
            Company/Vendor Details
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label>Order Company Name <span class="text-danger">*</span></label>
                    <select id="companyNameSelect" name="company_name" class="form-control" onchange="fillCompanyDetails(this)" required>
                        <option value="">Select Company</option>
                        @foreach ($companies as $company)
                            <option value="{{ $company->company }}"
                                data-address="{{ $company->billing_address }}"
                                data-gst="{{ $company->gstno }}"
                                data-email="{{ $company->email }}"
                                data-phone="{{ $company->mobile }}"
                                {{ $grn->company_name == $company->company ? 'selected' : '' }}>
                                {{ $company->company }}
                            </option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-6 mb-3">
                    <label>Address</label>
                    <input type="text" id="companyAddress" name="company_address" class="form-control" value="{{ $grn->company_address }}">
                </div>
            </div>

            <div class="row">
                <div class="col-md-4 mb-3">
                    <label>GST No</label>
                    <input type="text" id="companyGSTN" name="company_gst" class="form-control" value="{{ $grn->company_gst }}">
                </div>
                <div class="col-md-4 mb-3">
                    <label>Email</label>
                    <input type="email" id="companyEmail" name="company_email" class="form-control" value="{{ $grn->company_email }}">
                </div>
                <div class="col-md-4 mb-3">
                    <label>Contact Number</label>
                    <input type="tel" id="companyPhone" name="company_phone" class="form-control" value="{{ $grn->company_phone }}">
                </div>
            </div>
        </div>
    </div>

    <!-- Section 3: Additional References -->
    <div class="section-card amber">
        <div class="section-header">
            <i class="fas fa-tags"></i>
            Additional References
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-3 mb-3">
                    <label>Quotation ID</label>
                    <input type="text" id="quotationNo" name="quotation_no" class="form-control" value="{{ $grn->quotation_no }}">
                </div>
                <div class="col-md-3 mb-3">
                    <label>Quotation Date</label>
                    <input type="date" id="quotationDate" name="quotation_date" class="form-control" value="{{ $grn->quotation_date }}">
                </div>
                <div class="col-md-3 mb-3">
                    <label>RFQ No</label>
                    <input type="text" id="rfqNo" name="rfq_no" class="form-control" value="{{ $grn->rfq_no }}">
                </div>
                <div class="col-md-3 mb-3">
                    <label>RFQ Date</label>
                    <input type="date" id="rfqDate" name="rfq_date" class="form-control" value="{{ $grn->rfq_date }}">
                </div>
            </div>

            <div class="row">
                <div class="col-md-3 mb-3">
                    <label>Part No</label>
                    <input type="text" id="partNo" name="part_no" class="form-control" value="{{ $grn->part_no }}">
                </div>
                <div class="col-md-3 mb-3">
                    <label>Project Material No</label>
                    <input type="text" id="project-materialNo" name="project_material_no" class="form-control" value="{{ $grn->project_material_no }}">
                </div>
                <div class="col-md-3 mb-3">
                    <label>Drawing No</label>
                    <input type="text" id="drawingNo" name="drawing_no" class="form-control" value="{{ $grn->drawing_no }}">
                </div>
                <div class="col-md-3 mb-3">
                    <label>Drawing Revision</label>
                    <input type="text" id="drawingRev" name="drawing_rev" class="form-control" value="{{ $grn->drawing_rev }}">
                </div>
            </div>

            <div class="row">
                <div class="col-md-12 mb-3">
                    <label>Description</label>
                    <textarea id="description" name="description" rows="2" class="form-control">{{ $grn->description }}</textarea>
                </div>
            </div>
        </div>
    </div>

    <!-- Section 4: Product Details -->
    <div class="section-card green">
        <div class="section-header">
            <i class="fas fa-boxes"></i>
            Product Details
        </div>
        <div class="card-body">
            <div class="row mb-3">
                <div class="col-md-4">
                    <label>Product Type</label>
                    <input type="text" id="productType" name="product_type" class="form-control" value="{{ $grn->product_type }}">
                </div>
            </div>

            <div class="table-responsive">
                <table id="productTable" class="table table-bordered table-sm">
                    <thead>
                        <tr>
                            <th width="50">Sl No.</th>
                            <th>Description</th>
                            <th width="100">Quantity</th>
                            <th width="80">UOM</th>
                            <th width="130">Date</th>
                            <th>Supplier</th>
                            <th>Remarks</th>
                            <th width="50"></th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach($grn->products as $index => $product)
                        <tr>
                            <td>{{ $index + 1 }}</td>
                            <td>
                                <select name="products[{{ $index }}][description]" class="description form-control stock-item-select" style="width: 100%;" required>
                                    <option value="{{ $product->description }}" selected>{{ $product->description }}</option>
                                </select>
                                <input type="hidden" name="products[{{ $index }}][stock_item_id]" class="stock-item-id" value="{{ $product->stock_item_id }}">
                            </td>
                            <td><input type="number" name="products[{{ $index }}][quantity]" class="quantity form-control" value="{{ $product->quantity }}" required></td>
                            <td><input type="text" name="products[{{ $index }}][unit]" class="unit form-control" value="{{ $product->unit }}" required></td>
                            <td><input type="date" name="products[{{ $index }}][date]" class="date form-control" value="{{ $product->date }}" required></td>
                            <td><input type="text" name="products[{{ $index }}][supplier]" class="supplier form-control" value="{{ $product->supplier }}"></td>
                            <td><input type="text" name="products[{{ $index }}][remarks]" class="remarks form-control" value="{{ $product->remarks }}"></td>
                            <td><button class="btn btn-danger btn-sm" type="button" onclick="deleteRow(this)"><i class="fa fa-trash"></i></button></td>
                        </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>

            <div class="mb-3">
                <button type="button" class="btn btn-primary btn-sm" onclick="addRow()">
                    <i class="fa fa-plus"></i> Add Row
                </button>
            </div>
        </div>
    </div>

    <!-- Action Buttons -->
    <div class="d-flex justify-content-end gap-2 mb-4">
        <button type="submit" class="btn btn-success" id="save-GRN">
            <i class="fa fa-save"></i> Update GRN
        </button>
        <a href="{{ route('superadmin.grn.grndetails') }}" class="btn btn-outline-secondary">
            <i class="fa fa-arrow-left"></i> Back to List
        </a>
    </div>
</form>

<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
// Toast Notification Function
function showToast(message, type = 'success') {
    const container = document.getElementById('toastContainer');
    const toast = document.createElement('div');
    toast.className = `toast ${type}`;
    toast.innerHTML = `
        <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-circle'} toast-icon"></i>
        <div class="toast-message">${message}</div>
        <button class="toast-close" onclick="this.parentElement.remove()">&times;</button>
    `;
    container.appendChild(toast);
    setTimeout(() => toast.remove(), 5000);
}

// Live Clock Update
function updateTime() {
    const now = new Date();
    const timeString = now.toLocaleTimeString('en-US', {
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: true
    });
    document.getElementById('current-time').textContent = timeString;
}
setInterval(updateTime, 1000);

// Show session messages as toasts
@if(session('success'))
    showToast("{{ session('success') }}", 'success');
@endif
@if(session('error'))
    showToast("{{ session('error') }}", 'error');
@endif
@if($errors->any())
    @foreach($errors->all() as $error)
        showToast("{{ $error }}", 'error');
    @endforeach
@endif

$(document).ready(function() {
    // Initialize Select2 for existing rows
    $('.stock-item-select').each(function() {
        initStockItemSelect(this);
    });
});

function initStockItemSelect(element) {
    $(element).select2({
        placeholder: 'Search or type...',
        allowClear: true,
        tags: true,
        ajax: {
            url: '{{ route("superadmin.grn.searchStockItems") }}',
            dataType: 'json',
            delay: 250,
            data: function (params) {
                return { q: params.term };
            },
            processResults: function (data) {
                return { results: data.results };
            },
            cache: true
        },
        minimumInputLength: 0,
        width: '100%'
    }).on('select2:select', function (e) {
        // Auto-fill UOM and stock_item_id when stock item is selected
        var data = e.params.data;
        var row = $(this).closest('tr');
        if (data.uom) {
            row.find('.unit').val(data.uom);
        }
        // Set stock_item_id if it's an existing stock item (not a custom tag)
        if (data.stock_item_id) {
            row.find('.stock-item-id').val(data.stock_item_id);
        } else {
            row.find('.stock-item-id').val('');
        }
    }).on('select2:clear', function (e) {
        var row = $(this).closest('tr');
        row.find('.stock-item-id').val('');
    });
}

function addRow() {
    const table = document.querySelector("#productTable tbody");
    const index = table.rows.length;
    const row = document.createElement("tr");
    row.innerHTML = `
        <td>${index + 1}</td>
        <td>
            <select name="products[${index}][description]" class="description form-control stock-item-select" style="width: 100%;" required>
                <option value="">Search or type...</option>
            </select>
            <input type="hidden" name="products[${index}][stock_item_id]" class="stock-item-id">
        </td>
        <td><input type="number" name="products[${index}][quantity]" class="quantity form-control" required></td>
        <td><input type="text" name="products[${index}][unit]" class="unit form-control" required></td>
        <td><input type="date" name="products[${index}][date]" class="date form-control" required></td>
        <td><input type="text" name="products[${index}][supplier]" class="supplier form-control"></td>
        <td><input type="text" name="products[${index}][remarks]" class="remarks form-control"></td>
        <td><button class="btn btn-danger btn-sm" type="button" onclick="deleteRow(this)"><i class="fa fa-trash"></i></button></td>
    `;
    table.appendChild(row);
    // Initialize Select2 for the new row
    initStockItemSelect(row.querySelector('.stock-item-select'));
}

function deleteRow(button) {
    const row = button.closest("tr");
    // Destroy Select2 before removing row
    $(row).find('.stock-item-select').select2('destroy');
    row.remove();
    // Re-index remaining rows
    const rows = document.querySelectorAll("#productTable tbody tr");
    rows.forEach((tr, i) => {
        tr.querySelectorAll("input, select").forEach(field => {
            if (field.name) {
                const name = field.name.replace(/products\[\d+\]/, `products[${i}]`);
                field.name = name;
            }
        });
        tr.querySelector("td").textContent = i + 1;
    });
}

function fillCompanyDetails(select) {
    const selected = select.options[select.selectedIndex];
    document.getElementById('companyAddress').value = selected.getAttribute('data-address') || '';
    document.getElementById('companyGSTN').value = selected.getAttribute('data-gst') || '';
    document.getElementById('companyEmail').value = selected.getAttribute('data-email') || '';
    document.getElementById('companyPhone').value = selected.getAttribute('data-phone') || '';
}
</script>
@endsection
