@extends('layouts.dashboard.adminapp')
@section('title', 'admin GRN Order')
@section('content')

@if(session('success'))
    <div class="alert alert-success">{{ session('success') }}</div>
@endif
@if(session('error'))
    <div class="alert alert-danger">{{ session('error') }}</div>
@endif
@if ($errors->any())
    <div class="alert alert-danger">
        <ul class="mb-0">
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

<form method="POST" action="{{ route('admin.grn.store') }}" enctype="multipart/form-data" id="grnForm">
    @csrf
    <div class="grn-form" id="grnContent">
        <h1>Goods Received Note (admin)</h1>
        <br>
        <div class="row">
            <div class="col-md-3">
                <label>GRN ID <span class="required">*</span>
                    <input type="text" id="grnNo" name="grn_no" class="form-control" value="{{ $grnNo }}" readonly>
                </label>
            </div>
            <div class="col-md-3">
                <label>GRN Date <span class="required">*</span>
                    <input type="date" id="grnDate" name="grn_date" class="form-control" required>
                </label>
            </div>
            <div class="col-md-3">
                <label>Order Type <span class="required">*</span>
                    <select id="orderTypeSelect" class="form-control" required>
                        <option value="">Select Type</option>
                        <option value="sales">Sales Order</option>
                        <option value="purchase">Purchase Order</option>
                    </select>
                </label>
            </div>
            <div class="col-md-3">
                <label>Order ID <span class="required">*</span>
                    <select id="orderNoSelect" name="order_no" class="form-control" required>
                        <option value="">Select Order</option>
                        {{-- Populated by JS --}}
                    </select>
                </label>
            </div>
        </div>
        <br>
        <div class="row">
            <div class="col-md-6">
                <label>Order Date <span class="required">*</span>
                    <input type="date" id="orderDate" name="order_date" class="form-control" required readonly>
                </label>
            </div>
            <div class="col-md-6">
                <label>Order Reference No
                    <input type="text" id="orderRefNo" name="order_ref_no" class="form-control">
                </label>
            </div>
        </div>
        <br>
        <div class="row">
            <div class="col-md-6">
                <label>Order Company Name <span class="required">*</span>
                    <select id="companyNameSelect" name="company_name" class="form-control" required onchange="fillCompanyDetails(this)">
                        <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 }}">
                                {{ $company->company }}
                            </option>
                        @endforeach
                    </select>
                </label>
            </div>
            <div class="col-md-6">
                <label>Address
                    <input type="text" id="companyAddress" name="company_address" class="form-control">
                </label>
            </div>
        </div>
        <br>
        <div class="row">
            <div class="col-md-6">
                <label>GST No
                    <input type="text" id="companyGSTN" name="company_gstn" class="form-control">
                </label>
            </div>
            <div class="col-md-6">
                <label>Email
                    <input type="email" id="companyEmail" name="company_email" class="form-control">
                </label>
            </div>
        </div>
        <br>
        <div class="row">
            <div class="col-md-6">
                <label>Contact Number
                    <input type="tel" id="companyPhone" name="company_phone" class="form-control">
                </label>
            </div>
            <div class="col-md-6">
                <label>Quotation ID
                    <input type="text" id="quotationNo" name="quotation_no" class="form-control">
                </label>
            </div>
        </div>
        <br>
        <div class="row">
            <div class="col-md-6">
                <label>Quotation Date
                    <input type="date" id="quotationDate" name="quotation_date" class="form-control">
                </label>
            </div>
            <div class="col-md-6">
                <label for="rfqNo">RFQ No</label>
                <input type="text" id="rfqNo" name="rfq_no" class="form-control">
            </div>
        </div>
        <br>
        <div class="row">
            <div class="col-md-6">
                <label for="rfqDate">RFQ Date</label>
                <input type="date" id="rfqDate" name="rfq_date" class="form-control">
            </div>
            <div class="col-md-6">
                <label for="partNo">Part No</label>
                <input type="text" id="partNo" name="part_no" class="form-control">
            </div>
        </div>
        <br>
        <div class="row">
            <div class="col-md-6">
                <label for="project-materialNo">Project Material No</label>
                <input type="text" id="project-materialNo" name="project_material_no" class="form-control">
            </div>
            <div class="col-md-6">
                <label for="drawingNo">Drawing No</label>
                <input type="text" id="drawingNo" name="drawing_no" class="form-control">
            </div>
        </div>
        <br>
        <div class="row">
            <div class="col-md-6">
                <label for="drawingRev">Drawing Revision</label>
                <input type="text" id="drawingRev" name="drawing_rev" class="form-control">
            </div>
            <div class="col-md-6">
                <label for="description">Description</label>
                <textarea id="description" name="description" rows="2" class="form-control"></textarea>
            </div>
        </div>
        <br>
        <div class="row">
            <div class="col-md-6">
                <label>Upload Challan
                    <input type="file" id="grnChallan" name="challan" accept=".pdf" class="form-control">
                </label>
            </div>
        </div>
        <hr>
        <div class="row">
            <div class="col-lg-12">
                <h3>Product Details</h3>
                <div class="product-selection">
                    <label for="productType">Product Type</label>
                    <input type="text" id="productType" name="product_type" class="form-control">
                </div>
                <table id="productTable" class="product-table grn-table">
                    <thead>
                        <tr>
                            <th>Sl No.</th>
                            <th>Description</th>
                            <th>Quantity</th>
                            <th>UOM</th>
                            <th>Date</th>
                            <th>Supplier</th>
                            <th>Remarks</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td>1</td>
                            <td><input type="text" name="products[0][description]" class="description form-control"></td>
                            <td><input type="number" name="products[0][quantity]" class="quantity form-control"></td>
                            <td><input type="text" name="products[0][unit]" class="unit form-control"></td>
                            <td><input type="date" name="products[0][date]" class="date form-control"></td>
                            <td><input type="text" name="products[0][supplier]" class="supplier form-control"></td>
                            <td><input type="text" name="products[0][remarks]" class="remarks form-control"></td>
                            <td><button class="btn btn-danger" type="button" onclick="deleteRow(this)"><i class="fa fa-trash"></i></button></td>
                        </tr>
                    </tbody>
                </table>
                <button type="button" onclick="addRow()">Add Row</button>
            </div>
        </div>
        <hr>
        <div class="row mt-5 mb-5">
            <div class="col-xl-3">
                <button type="submit" id="save-GRN">Save</button>
            </div>
        </div>
    </div>
</form>

<script>
document.addEventListener('DOMContentLoaded', function () {
    // Set GRN date to today
    document.getElementById('grnDate').value = new Date().toISOString().split('T')[0];

    let ordersData = [];

    // When order type changes, load orders
    document.getElementById('orderTypeSelect').addEventListener('change', function () {
        const type = this.value;
        loadOrderDropdown(type);
    });

    // When order is selected, autofill details
    document.getElementById('orderNoSelect').addEventListener('change', function () {
        const orderNo = this.value;
        const type = document.getElementById('orderTypeSelect').value;
        if (!orderNo || !type) return;
        fetch("{{ url('admin/grn/order-details') }}?type=" + type + "&order_no=" + orderNo)
            .then(r => r.json())
            .then(order => {
                if (order.error) return;
                document.getElementById('orderDate').value = (type === 'sales' ? order.sales_order_date : order.purchase_order_date) || '';
                // Auto-fill company/vendor/customer details
                if (type === 'sales' && order.customer) {
                    document.getElementById('companyNameSelect').value = order.customer.company || '';
                    document.getElementById('companyAddress').value = order.company_address || '';
                    document.getElementById('companyGSTN').value = order.customer.gstno || '';
                    document.getElementById('companyEmail').value = order.customer.email || '';
                    document.getElementById('companyPhone').value = order.customer.mobile || '';
                } else if (type === 'purchase' && order.vendor) {
                    document.getElementById('companyNameSelect').value = order.vendor.company || '';
                    document.getElementById('companyAddress').value = order.company_address || '';
                    document.getElementById('companyGSTN').value = order.company_gstn || '';
                    document.getElementById('companyEmail').value = order.company_email || '';
                    document.getElementById('companyPhone').value = order.company_phone || '';
                }
                document.getElementById('orderRefNo').value = order.customer_ref_no || '';
                document.getElementById('quotationNo').value = order.quotation_no || '';
                document.getElementById('quotationDate').value = order.quotation_date || '';
                document.getElementById('rfqNo').value = order.rfq_no || '';
                document.getElementById('rfqDate').value = order.rfq_date || '';
                document.getElementById('partNo').value = order.part_no || '';
                document.getElementById('project-materialNo').value = order.project_material_no || '';
                document.getElementById('drawingNo').value = order.drawing_no || '';
                document.getElementById('drawingRev').value = order.drawing_rev || '';
                document.getElementById('description').value = order.description || '';
                document.getElementById('productType').value = order.product_type || '';
            });
    });

    function loadOrderDropdown(type) {
        if (!type) {
            document.getElementById('orderNoSelect').innerHTML = '<option value="">Select Order</option>';
            return;
        }
        fetch("{{ url('admin/grn/available-orders') }}")
            .then(r => r.json())
            .then(data => {
                ordersData = data;
                const options = data
                    .filter(o => o.order_type === type)
                    .map(o => `<option value="${o.order_no}">${o.order_no}</option>`);
                document.getElementById('orderNoSelect').innerHTML =
                    '<option value="">Select Order</option>' + options.join('');
            });
    }
});

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><input type="text" name="products[${index}][description]" class="description form-control"></td>
        <td><input type="number" name="products[${index}][quantity]" class="quantity form-control"></td>
        <td><input type="text" name="products[${index}][unit]" class="unit form-control"></td>
        <td><input type="date" name="products[${index}][date]" class="date form-control"></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" type="button" onclick="deleteRow(this)"><i class="fa fa-trash"></i></button></td>
    `;
    table.appendChild(row);
}

function deleteRow(button) {
    const row = button.closest("tr");
    row.remove();
    // Re-index remaining rows
    const rows = document.querySelectorAll("#productTable tbody tr");
    rows.forEach((tr, i) => {
        tr.querySelectorAll("input").forEach(input => {
            const name = input.name.replace(/products\[\d+\]/, `products[${i}]`);
            input.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
