<?php
if(file_exists('../../../../'.$_REQUEST['tenant'].'/config.php')) {
    require_once('../../../../'.$_REQUEST['tenant'].'/config.php');
}
if(file_exists('/config.php')) {
    require_once('/config.php');
}

$clientnumber = intval($_REQUEST['clientnumber']);
$items = [];
if ($clientnumber > 0) {
    $stmt = $con->prepare("SELECT itemnumber, `desc`, plantnumber, serialnumber FROM itemdetails WHERE statuslive = 1 AND clientnumber = ?");
    $stmt->bind_param("i", $clientnumber);
    $stmt->execute();
    $result = $stmt->get_result();
    while ($r = $result->fetch_assoc()) {
        $items[] = $r;
    }
}
?>

<div class="modal-body position-relative" id="start">
    <div id="modalToastContainer" class="position-absolute top-0 start-50 translate-middle-x mt-n5" style="z-index: 1056; width: auto; max-width: 90%;"></div>

    <form id="newInvoiceItemForm">
        <div class="mb-3">
            <label class="form-label">Service Description</label>
            <select name="service" id="service" class="form-select" required>
                <option value="">Blank</option>
                <option value="Consultancy Work">Consultancy Work</option>
                <option value="In Service Inspection">In Service Inspection</option>
                <option value="Inspection">Inspection</option>
                <option value="Prior to purchase Inspection">Prior to purchase Inspection</option>
                <option value="Purchase Order">Purchase Order</option>
                <option value="Special Service">Special Service</option>
                <option value="Technical Service">Technical Service</option>

            </select>
        </div>

        <div class="mb-3" id="itemSelectContainer" style="display:none;">
            <label class="form-label">Item</label>
            <select name="itemnumber" id="itemnumber" class="form-select filterSelect">
                <option value="">Select item</option>
                <?php foreach ($items as $item): ?>
                <option value="<?= $item['itemnumber'] ?>">
                    <?= $item['itemnumber'] ?> | <?= $item['desc'] ?> | <?= $item['plantnumber'] ?> (<?= $item['serialnumber'] ?>)
                </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="mb-3">
            <label class="form-label">Detailed Notes</label>
            <textarea name="notes" id="notes" class="form-control" rows="3"></textarea>
        </div>

        <div class="mb-3">
            <label class="form-label">Fee</label>
            <input type="number" name="fee" id="fee" class="form-control" step="0.01" required />
        </div>

        <div class="mb-3">
            <label class="form-label">Quantity</label>
            <input type="number" name="qty" id="qty" class="form-control" step="1" value="1" required />
        </div>
    </form>

</div>

<script>
try {
    (function() {
        const serviceSelect = document.getElementById("service");
        const itemContainer = document.getElementById("itemSelectContainer");
        const itemSelect = document.getElementById("itemnumber");
        const notesField = document.getElementById("notes");

        if (serviceSelect) {
            serviceSelect.addEventListener("change", function() {
                const isInspection = this.value === "Inspection";
                itemContainer.style.display = isInspection ? "block" : "none";
            });
        }

        if (itemSelect) {
            new mdb.Select(itemSelect, {
                filter: true
            });

            itemSelect.addEventListener("change", function() {
                const selected = this.options[this.selectedIndex];
                if (selected && notesField) {
                    const parts = selected.textContent.trim().split('|');
                    const desc = parts[1]?.trim() || '';
                    const plantInfo = parts[2]?.trim() || '';
                    const plantNumber = plantInfo.split('(')[0]?.trim() || '';
                    notesField.value = `${desc}, Plant Number: ${plantNumber}`;
                }
            });
        }
    })();
} catch (err) {
    console.error("Modal init error:", err);
}

function showModalToast(message) {
    const container = document.getElementById("modalToastContainer");
    if (!container) return;

    const toast = document.createElement("div");
    toast.className = "toast align-items-center text-white bg-danger border-0 fade show shadow";
    toast.setAttribute("role", "alert");
    toast.setAttribute("aria-live", "assertive");
    toast.setAttribute("aria-atomic", "true");
    toast.style.minWidth = "300px";

    toast.innerHTML = `
        <div class="d-flex p-2">
            <div class="toast-body">
                ${message}
            </div>
            <button type="button" class="btn-close btn-close-white me-2 m-auto" data-mdb-dismiss="toast" aria-label="Close"></button>
        </div>
    `;

    container.innerHTML = ""; // Clear any existing toast
    container.appendChild(toast);

    // Auto-remove after 3 seconds
    setTimeout(() => {
        toast.classList.remove("show");
        toast.classList.add("hide");
    }, 3000);
}
</script>