@extends('layouts.dashboard.adminapp')
@section('title', 'Edit Purchase Order')
@section('content')
<x-layout.page-header title="UEPL | Edit Purchase Order" icon="shopping-bag" iconColor="primary" />

<div class="card-header d-flex align-items-center justify-content-between">
    <a href="{{ route('admin.purchase.purchasedetails') }}" class="btn btn-secondary btn-sm" >← Back to List</a>
</div>
<!-- Hidden Order ID for JS -->
<input type="hidden" id="editOrderId" value="{{ $po->id }}">

<form id="soForm" class="bg-white p-4 rounded shadow-sm" method="POST" action="{{ route('admin.purchase.order.update', $po->id) }}">
    @csrf
    @method('POST')
    <!-- Hidden for serialized products -->
    <input type="hidden" id="tableProducts" name="tableProducts">

    <div class="row">
        <div class="col-md-6">
            <label>Purchase Order No.
                <input type="text" id="sOrderNo" name="soNo1" value="{{ $po->purchase_order_no }}" readonly class="form-control">
            </label>
            <label>Date
                <input type="date" id="sOrderDate" name="soDate" value="{{ $po->purchase_order_date }}" required class="form-control">
            </label>
            <label>GRN No.
                <input type="text" id="grnNo" name="grnNo1" value="{{ $po->grn_no }}" class="form-control">
            </label>
            <label>Vendor Reference No.
                <input type="text" id="custRefNo" name="custRefSoNo" value="{{ $po->customer_ref_no }}" class="form-control">
            </label>
            <label>Vendor PO
                <input type="file" id="customerSO" name="customerSO" accept=".pdf" class="form-control">
            </label>
        </div>
        <div class="col-md-6">
            <section class="order-company-info">
                <label>Vendor Company Name
                    <input type="text" id="soCompanyId" name="companyId" value="{{ optional($po->vendor)->company ?? $po->company_name }}" required class="form-control">
                    <input type="hidden" id="soCompanyName" name="companyName" value="{{ optional($po->vendor)->id ?? '' }}" required class="form-control">
                </label>
                <label>Address
                    <input type="text" id="soCompanyAddress" name="soCompanyAddress" value="{{ $po->company_address }}" required class="form-control">
                </label>
                <label>GSTN
                    <input type="text" id="soCompanyGSTN" name="soCompanyGSTN" value="{{ $po->company_gstn }}" required class="form-control">
                </label>
                <label>Phone
                    <input type="tel" id="soCompanyPhone" name="soCompanyPhone" value="{{ $po->company_phone }}" required class="form-control">
                </label>
                <label>Email
                    <input type="email" id="soCompanyEmail" name="soCompanyEmail" value="{{ $po->company_email }}" required class="form-control">
                </label>
            </section>
        </div>
    </div>

    <hr>
    <div class="row mt-3">
        <div class="col-md-6">
            <label for="quotationSelect">Quotation ID</label>
            <!--<select id="quotationSelect" name="quotationId" class="form-select">-->
            <!--    <option value="">Select Quotation</option>-->
            <!--</select>-->
            <input type="text" id="quotationSelect" name="quotationId" value="{{ $po->quotation_no }}" class="form-control" readonly>
        </div>
        <div class="col-md-6">
            <label for="quotationDate">Quotation Date</label>
            <input type="date" id="quotationDate" name="quotationDate" value="{{ $po->quotation_date }}" class="form-control">
        </div>
    </div>

    <div class="row mt-3">
        <div class="col-md-6">
            <label for="rfqNo">RFQ No</label>
            <input type="text" id="rfqNo" name="rfqNo" value="{{ $po->rfq_no }}" class="form-control">
        </div>
        <div class="col-md-6">
            <label for="rfqDate">RFQ Date</label>
            <input type="date" id="rfqDate" name="rfqDate" value="{{ $po->rfq_date }}" class="form-control">
        </div>
    </div>

    <div class="row mt-3">
        <div class="col-md-6">
            <label for="partNo">Part No</label>
            <input type="text" id="partNo" name="partNo" value="{{ $po->part_no }}" class="form-control">
        </div>
        <div class="col-md-6">
            <label for="projectMaterialNo">Project Material No</label>
            <input type="text" id="projectMaterialNo" name="projectMaterialNo" value="{{ $po->project_material_no }}" class="form-control">
        </div>
    </div>

    <div class="row mt-3">
        <div class="col-md-6">
            <label for="drawingId">Drawing No</label>
            <input type="text" id="drawingId" name="drawingId" value="{{ $po->drawing_no }}" class="form-control">
        </div>
        <div class="col-md-6">
            <label for="drawingRevision">Drawing Revision</label>
            <input type="text" id="drawingRevision" name="drawingRevision" value="{{ $po->drawing_rev }}" class="form-control">
        </div>
    </div>

    <div class="row mt-3">
        <div class="col-md-12">
            <label for="projectDescription">Project Description</label>
            <textarea id="projectDescription" name="projectDescription" rows="2" class="form-control">{{ $po->description }}</textarea>
        </div>
    </div>

    <hr>
    <div class="row">
        <div class="col-md-6">
            <label>Bill To
                <textarea name="billAddress" id="billAddress" class="form-control" rows="3">{{ $po->bill_address }}</textarea>
            </label>
        </div>
        <div class="col-md-6">
            <label>Ship To
                <textarea name="shipAddress" id="shipAddress" class="form-control" rows="3">{{ $po->ship_address }}</textarea>
            </label>
        </div>
    </div>

    <hr>
    <div class="product-selection">
        <label for="productType">Product Type</label>
        <input type="text" id="productType" name="productType" value="{{ $po->product_type }}" placeholder="Product Type" required class="form-control">
    </div>
    <div class="po-so">
        <table id="productTable" class="table table-bordered product-table">
            <thead>
                <tr>
                    <th>Sl No.</th>
                    <th>Material Code</th>
                    <th>HSN Code</th>
                    <th>Description</th>
                    <th>Additional Details</th>
                    <th>Req By Date</th>
                    <th>Quantity</th>
                    <th>UOM</th>
                    <th>Unit Rate (INR)</th>
                    <th>Discount (%)</th>
                    <th>Value (INR)</th>
                    <th>SGST (%)</th>
                    <th>CGST (%)</th>
                    <th>IGST (%)</th>
                    <th>Amount (INR)</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                @foreach ($po->items as $item)
                <tr>
                    <td>{{ $loop->iteration }}</td>
                    <td><input type="text" class="material-code form-control" value="{{ $item->material_code }}"></td>
                    <td><input type="text" class="hsn-code form-control" value="{{ $item->hsn_code }}"></td>
                    <td><textarea class="description form-control" rows="1">{{ $item->material_description }}</textarea></td>
                    <td><textarea class="additional-details form-control" rows="1">{{ $item->additional_details }}</textarea></td>
                    <td><input type="date" class="req-by-date form-control" value="{{ $item->required_by_date }}"></td>
                    <td><input type="number" class="quantity form-control" value="{{ $item->quantity }}"></td>
                    <td><input type="text" class="uom form-control" value="{{ $item->uom }}"></td>
                    <td><input type="number" class="rate form-control" value="{{ $item->unit_rate }}"></td>
                    <td><input type="number" class="discount form-control" value="{{ $item->discount }}"></td>
                    <td><input type="number" class="value form-control" value="{{ $item->value }}" readonly></td>
                    <td><input type="number" class="sgst form-control" value="{{ $item->sgst }}"></td>
                    <td><input type="number" class="cgst form-control" value="{{ $item->cgst }}"></td>
                    <td><input type="number" class="igst form-control" value="{{ $item->igst }}"></td>
                    <td><input type="number" class="amount form-control" value="{{ $item->amount }}" readonly></td>
                    <td><button class="btn btn-danger" type="button" onclick="deleteRow(this)">Delete</button></td>
                </tr>
                @endforeach
            </tbody>
        </table>
        <button type="button" class="btn btn-primary" onclick="addRow()">Add Row</button>
    </div>

    <hr>
    <div class="row mt-4">
        <div class="col-md-6">
            <label for="GT-in-letters">Grand Total in Words</label>
            <input type="text" id="GT-in-letters" name="GT_in_letters" value="{{ $po->inr_in_words }}" readonly class="form-control">
        </div>
        <div class="col-md-6 total-fields">
            <div class="totals align-self-lg-end">
                <div class="row mb-2">
                    <div class="col-md-3"><label>SUB TOTAL</label></div>
                    <div class="col-md-9"><input type="text" id="totalAmount" name="totalAmount" value="{{ $po->subtotal }}" readonly class="form-control"></div>
                </div>
                <div class="row mb-2">
                    <div class="col-md-3"><label>SGST Amount</label></div>
                    <div class="col-md-9"><input type="text" id="sgstA" name="sgstA" value="{{ $po->sgst_amount }}" readonly class="form-control"></div>
                </div>
                <div class="row mb-2">
                    <div class="col-md-3"><label>CGST Amount</label></div>
                    <div class="col-md-9"><input type="text" id="cgstA" name="cgstA" value="{{ $po->cgst_amount }}" readonly class="form-control"></div>
                </div>
                <div class="row mb-2">
                    <div class="col-md-3"><label>IGST Amount</label></div>
                    <div class="col-md-9"><input type="text" id="IgstA" name="IgstA" value="{{ $po->igst_amount }}" readonly class="form-control"></div>
                </div>
                <div class="row mb-2">
                    <div class="col-md-3"><label>Round Up</label></div>
                    <div class="col-md-9"><input type="text" id="roundUp" name="roundUp" value="{{ $po->round_up }}" readonly class="form-control"></div>
                </div>
                <div class="row mb-2">
                    <div class="col-md-3"><label>Grand Total</label></div>
                    <div class="col-md-9"><input type="text" id="grandTotal" name="grandTotal" value="{{ $po->grand_total }}" readonly class="form-control"></div>
                </div>
            </div>
        </div>
    </div>

    <div class="row p-2">
        <!-- Submit Button -->
        <div class="btn">
            <button class="btn btn-success" type="submit">Save</button>
        </div>

        <div class="btn">
            <button class="btn btn-danger" type="reset" onclick="resetForm()">Clear</button>
        </div>
    </div>
</form>
@endsection

@section('scripts')
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
// ---- Indian Rupees to Words ----
function convertNumberToWords(num) {
    var a = [
        '', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine',
        'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen'
    ];
    var b = [
        '', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety'
    ];
    var g = [
        '', 'Thousand', 'Lakh', 'Crore'
    ];
    if (typeof num !== 'number') num = parseFloat(num);
    if (isNaN(num) || num === 0) return 'Zero Rupees Only';
    function numToWords(n, suffixIdx) {
        if (n == 0) return '';
        if (n < 20) return a[n] + ' ' + (g[suffixIdx] ? g[suffixIdx] + ' ' : '');
        if (n < 100) return b[Math.floor(n / 10)] + (n % 10 ? ' ' + a[n % 10] : '') + ' ' + (g[suffixIdx] ? g[suffixIdx] + ' ' : '');
        if (n < 1000) return a[Math.floor(n / 100)] + ' Hundred ' + numToWords(n % 100, 0) + (g[suffixIdx] ? g[suffixIdx] + ' ' : '');
        return '';
    }
    let words = '';
    let crore = Math.floor(num / 10000000);
    num = num % 10000000;
    let lakh = Math.floor(num / 100000);
    num = num % 100000;
    let thousand = Math.floor(num / 1000);
    num = num % 1000;
    let hundred = Math.floor(num / 100);
    let rest = num % 100;
    if (crore) words += numToWords(crore, 3);
    if (lakh) words += numToWords(lakh, 2);
    if (thousand) words += numToWords(thousand, 1);
    if (hundred) words += a[hundred] + ' Hundred ';
    if (rest) words += numToWords(rest, 0);
    return words.trim() + ' Rupees Only';
}

function getTableData() {
    const rows = document.querySelectorAll("#productTable tbody tr");
    const data = [];
    rows.forEach((row, idx) => {
        data.push({
            slNo: idx + 1,
            materialCode: row.querySelector(".material-code").value,
            hsnCode: row.querySelector(".hsn-code").value,
            description: row.querySelector(".description").value,
            additionalDetails: row.querySelector(".additional-details").value,
            reqByDate: row.querySelector(".req-by-date").value,
            quantity: row.querySelector(".quantity").value,
            uom: row.querySelector(".uom").value,
            unitRate: row.querySelector(".rate").value,
            discount: row.querySelector(".discount").value,
            value: row.querySelector(".value").value,
            sgst: row.querySelector(".sgst").value,
            cgst: row.querySelector(".cgst").value,
            igst: row.querySelector(".igst").value,
            amount: row.querySelector(".amount").value
        });
    });
    return data;
}

function calculateRowValue(input) {
    const row = input.closest("tr");
    const quantity = parseFloat(row.querySelector(".quantity").value) || 0;
    const rate = parseFloat(row.querySelector(".rate").value) || 0;
    const discount = parseFloat(row.querySelector(".discount").value) || 0;
    const sgst = parseFloat(row.querySelector(".sgst").value) || 0;
    const cgst = parseFloat(row.querySelector(".cgst").value) || 0;
    const igst = parseFloat(row.querySelector(".igst").value) || 0;

    const baseValue = quantity * rate * (1 - discount / 100);
    row.querySelector(".value").value = baseValue.toFixed(2);

    const amount = baseValue * (1 + (sgst + cgst + igst) / 100);
    row.querySelector(".amount").value = amount.toFixed(2);

    calculateAllTotals();
}

function calculateAllTotals() {
    let subtotal = 0, sgstTotal = 0, cgstTotal = 0, igstTotal = 0;
    document.querySelectorAll("#productTable tbody tr").forEach(row => {
        const val = parseFloat(row.querySelector(".value").value) || 0;
        const sgst = parseFloat(row.querySelector(".sgst").value) || 0;
        const cgst = parseFloat(row.querySelector(".cgst").value) || 0;
        const igst = parseFloat(row.querySelector(".igst").value) || 0;

        subtotal += val;
        sgstTotal += val * sgst / 100;
        cgstTotal += val * cgst / 100;
        igstTotal += val * igst / 100;
    });

    const grandTotalRaw = subtotal + sgstTotal + cgstTotal + igstTotal;
    const roundUp = Math.ceil(grandTotalRaw) - grandTotalRaw;
    const grandTotal = grandTotalRaw + roundUp;

    document.getElementById("totalAmount").value = subtotal.toFixed(2);
    document.getElementById("sgstA").value = sgstTotal.toFixed(2);
    document.getElementById("cgstA").value = cgstTotal.toFixed(2);
    document.getElementById("IgstA").value = igstTotal.toFixed(2);
    document.getElementById("roundUp").value = roundUp.toFixed(2);
    document.getElementById("grandTotal").value = grandTotal.toFixed(2);
    document.getElementById("GT-in-letters").value = convertNumberToWords(grandTotal);
}

function addRowEventListeners(row) {
    row.querySelector(".quantity").addEventListener("input", function() { calculateRowValue(this); });
    row.querySelector(".rate").addEventListener("input", function() { calculateRowValue(this); });
    row.querySelector(".discount").addEventListener("input", function() { calculateRowValue(this); });
    row.querySelector(".sgst").addEventListener("input", function() { calculateRowValue(this); });
    row.querySelector(".cgst").addEventListener("input", function() { calculateRowValue(this); });
    row.querySelector(".igst").addEventListener("input", function() { calculateRowValue(this); });
}

window.addRow = function() {
    const table = document.getElementById("productTable").getElementsByTagName("tbody")[0];
    const idx = table.rows.length + 1;
    const row = document.createElement("tr");
    row.innerHTML = `
        <td>${idx}</td>
        <td><input type="text" class="material-code form-control"></td>
        <td><input type="text" class="hsn-code form-control"></td>
        <td><textarea class="description form-control" rows="1"></textarea></td>
        <td><textarea class="additional-details form-control" rows="1"></textarea></td>
        <td><input type="date" class="req-by-date form-control"></td>
        <td><input type="number" class="quantity form-control"></td>
        <td><input type="text" class="uom form-control"></td>
        <td><input type="number" class="rate form-control"></td>
        <td><input type="number" class="discount form-control"></td>
        <td><input type="number" class="value form-control" readonly></td>
        <td><input type="number" class="sgst form-control"></td>
        <td><input type="number" class="cgst form-control"></td>
        <td><input type="number" class="igst form-control"></td>
        <td><input type="number" class="amount form-control" readonly></td>
        <td><button class="btn btn-danger" type="button" onclick="deleteRow(this)">Delete</button></td>
    `;
    table.appendChild(row);
    addRowEventListeners(row);
};

window.deleteRow = function(btn) {
    btn.closest('tr').remove();
    calculateAllTotals();
};

// --- QUOTATION DROPDOWN AJAX LOAD AND AUTOFILL ---
document.addEventListener("DOMContentLoaded", function() {
    // Bind calculations to all rows
    document.querySelectorAll("#productTable tbody tr").forEach(row => addRowEventListeners(row));
    calculateAllTotals();

    fetch("{{ url('/admin/purchase/quotations') }}")
        .then(res => res.json())
        .then(data => {
            const select = document.getElementById("quotationSelect");
            select.innerHTML = '<option value="">Select Quotation</option>';
            let foundSelected = false;
            data.forEach(q => {
                const opt = document.createElement("option");
                opt.value = q.id;
                opt.textContent = q.quotation_no;
                if (
                    ("{{ $po->quotation_id ?? '' }}" && q.id == "{{ $po->quotation_id ?? '' }}") ||
                    ("{{ $po->quotation_no ?? '' }}" && q.quotation_no == "{{ $po->quotation_no ?? '' }}")
                ) {
                    opt.selected = true;
                    foundSelected = true;
                }
                select.appendChild(opt);
            });
            if (foundSelected) {
                select.dispatchEvent(new Event('change'));
            }
        });

    document.getElementById("quotationSelect").addEventListener("change", async function() {
        const quotationId = this.value;
        if (!quotationId) return;
        try {
            // const response = await fetch("{{ url('/admin/purchase/quotation') }}/" + quotationId);
            // const data = await response.json();
            if (data.customer) {
                document.getElementById("soCompanyId").value = data.customer.company || "";
                document.getElementById("soCompanyName").value = data.customer.id || "";
                document.getElementById("soCompanyAddress").value = data.address || "";
                document.getElementById("soCompanyGSTN").value = data.gst || "";
                document.getElementById("soCompanyPhone").value = data.phone || "";
                document.getElementById("soCompanyEmail").value = data.email || "";
                document.getElementById("billAddress").value = data.address || "";
                document.getElementById("shipAddress").value = data.address || "";
            }
            document.getElementById("quotationDate").value = data.quotation_date || "";
            document.getElementById("custRefNo").value = data.cust_ref_no || "";
            document.getElementById("rfqNo").value = data.rfq ? data.rfq.rfq_no : "";
            document.getElementById("rfqDate").value = data.rfq_date || "";
            document.getElementById("partNo").value = data.part_no || "";
            document.getElementById("projectMaterialNo").value = data.project_material_no || "";
            document.getElementById("drawingId").value = data.drawing_no || "";
            document.getElementById("drawingRevision").value = data.drawing_rev || "";
            document.getElementById("projectDescription").value = data.description || "";
            document.getElementById("productType").value = data.product_type || "";
            // Optionally: fill product table here if you want
        } catch (err) {
            console.error("Failed to load quotation data:", err);
        }
    });

    // On submit: serialize tableProducts and submit via AJAX
    document.getElementById('soForm').addEventListener('submit', async function(event) {
        event.preventDefault();
        document.getElementById('tableProducts').value = JSON.stringify(getTableData());
        let formData = new FormData(this);
        let plainData = {};
        formData.forEach((v, k) => { plainData[k] = v; });
        plainData['tableProducts'] = getTableData();

        Swal.fire({
            title: 'Updating...',
            text: 'Please wait while we update the purchase order.',
            allowOutsideClick: false,
            didOpen: () => Swal.showLoading()
        });

        try {
            const response = await fetch(this.action, {
                method: "POST",
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                },
                body: JSON.stringify({...plainData, _method: 'PUT'})
            });
            const data = await response.json();
            Swal.close();
            if (data.message && data.message.includes('updated')) {
                Swal.fire('Success!', data.message, 'success').then(() =>
                    window.location.href = "{{ url('admin/purchasedetails') }}"
                );
            } else {
                Swal.fire('Error!', data.message || data.error || 'Something went wrong.', 'error');
            }
        } catch (err) {
            Swal.close();
            Swal.fire('Error!', 'Failed to update purchase order.', 'error');
        }
    });
});
</script>
@endsection
