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

$id = isset($_REQUEST['id']) ? (int)$_REQUEST['id'] : 0;

$stmt = $GLOBALS['con']->prepare("SELECT * FROM `dd_plant` WHERE `id` = ? LIMIT 1") or die(mysqli_error($GLOBALS['con']));
$stmt->bind_param('i', $id);
$stmt->execute();
$rslt = $stmt->get_result();
$d = $rslt ? $rslt->fetch_assoc() : null;
$stmt->close();

if (!$d) {
    exit('<div class="note note-danger">Plant entry not found.</div>');
}

$selectedColour = trim((string)($d['row_colour'] ?? ''));
$deliveryExclusion = (int)($d['delivery_exclusion'] ?? 0) === 1;

$colourMap = [
    'rose'   => ['bg' => '#fce4ec', 'text' => '#6a1b3a', 'label' => 'Rose'],
    'red'    => ['bg' => '#fdecea', 'text' => '#7f1d1d', 'label' => 'Red'],
    'orange' => ['bg' => '#fff3e0', 'text' => '#8a3b12', 'label' => 'Orange'],
    'amber'  => ['bg' => '#fff8e1', 'text' => '#7a5600', 'label' => 'Amber'],
    'yellow' => ['bg' => '#fffde7', 'text' => '#6b5b00', 'label' => 'Yellow'],
    'lime'   => ['bg' => '#f1f8e9', 'text' => '#466a12', 'label' => 'Lime'],
    'green'  => ['bg' => '#e8f5e9', 'text' => '#1b5e20', 'label' => 'Green'],
    'mint'   => ['bg' => '#e6f7f1', 'text' => '#0f5c4d', 'label' => 'Mint'],
    'cyan'   => ['bg' => '#e0f7fa', 'text' => '#155e75', 'label' => 'Cyan'],
    'blue'   => ['bg' => '#e3f2fd', 'text' => '#0d47a1', 'label' => 'Blue'],
    'indigo' => ['bg' => '#e8eaf6', 'text' => '#283593', 'label' => 'Indigo'],
    'purple' => ['bg' => '#f3e5f5', 'text' => '#6a1b9a', 'label' => 'Purple']
];
?>
<form id="editForm">
    <div class="row">
        <div class="col-12 col-md-6 mb-3">
            <h5 class="mb-2">Code</h5>
            <input type="text"
                   class="form-control form-control-sm"
                   aria-label="Code"
                   name="code"
                   value="<?= htmlspecialchars((string)$d['code']) ?>" />
        </div>

        <div class="col-12 col-md-6 mb-3">
            <h5 class="mb-2">Description</h5>
            <input type="text"
                   class="form-control form-control-sm"
                   aria-label="Description"
                   name="desc"
                   value="<?= htmlspecialchars((string)$d['description']) ?>" />
        </div>

        <div class="col-12 col-md-6 mb-3">
            <h5 class="mb-2">Frequency</h5>
            <input type="text"
                   class="form-control form-control-sm"
                   aria-label="Frequency"
                   name="freq"
                   value="<?= htmlspecialchars((string)$d['frequency']) ?>" />
        </div>

        <input type="hidden" name="size" value="<?= htmlspecialchars((string)$d['size']) ?>" />

        <div class="col-12 col-md-6 mb-3">
            <h5 class="mb-2">IU</h5>
            <input type="text"
                   class="form-control form-control-sm"
                   aria-label="Units"
                   name="units"
                   value="<?= htmlspecialchars((string)$d['units']) ?>" />
        </div>

        <div class="col-12 col-md-6 mb-3">
            <h5 class="mb-2">Delivery Exclusion</h5>
            <div class="form-check form-switch">
                <input class="form-check-input"
                       type="checkbox"
                       role="switch"
                       id="editDeliveryExclusion"
                       name="delivery_exclusion"
                       value="1"
                       <?= $deliveryExclusion ? 'checked' : '' ?>>
                <label class="form-check-label" for="editDeliveryExclusion">
                    Exclude matching item codes from delivery report lists
                </label>
            </div>
        </div>

        <div class="col-12 col-md-6 mb-3">
            <h5 class="mb-2">Row Colour</h5>

            <input type="hidden" name="row_colour" id="row_colour" value="<?= htmlspecialchars($selectedColour) ?>" />

            <div class="d-flex flex-wrap align-items-center gap-2">
                <button type="button"
                        class="btn btn-info btn-sm"
                        id="openPlantColourPicker"
                        data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Choose row colour">
                    <i class="fad fa-palette"></i> Choose colour
                </button>

                <button type="button"
                        class="btn btn-secondary btn-sm"
                        id="clearPlantColour"
                        data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Clear row colour">
                    <i class="fad fa-eraser"></i> Clear
                </button>
            </div>

            <div id="plantColourPreview"
                 class="mt-3 border rounded-3 px-3 py-2"
                 style="min-height:44px;">
                Preview
            </div>
        </div>

        <input type="hidden" name="id" value="<?= (int)$d['id'] ?>">
        <input type="hidden" name="mode" value="plant">
        <input type="hidden" name="tenant" value="<?= htmlspecialchars(TENANT_URL) ?>">
        <input type="hidden" name="FUNCTION" value="update">
    </div>

    <div class="row">
        <div class="col-12 text-center">
            <a href="javascript:void(0)" class="btn btn-success" onclick="updateEntry()">Update Entry</a>
        </div>
    </div>
</form>

<div class="modal fade" id="plantColourPickerModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-md">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Select Row Colour</h5>
                <button type="button" class="btn-close" data-mdb-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="row g-2">
                    <?php foreach ($colourMap as $key => $cfg): ?>
                    <div class="col-6 col-md-4">
                        <button type="button"
                                class="btn w-100 text-start plant-colour-option"
                                data-colour="<?= htmlspecialchars($key) ?>"
                                data-bg="<?= htmlspecialchars($cfg['bg']) ?>"
                                data-text="<?= htmlspecialchars($cfg['text']) ?>"
                                style="background:<?= htmlspecialchars($cfg['bg']) ?>; color:<?= htmlspecialchars($cfg['text']) ?>; border:1px solid rgba(0,0,0,0.08);"
                                data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Use <?= htmlspecialchars($cfg['label']) ?>">
                            <i class="fad fa-square-full me-2"></i><?= htmlspecialchars($cfg['label']) ?>
                        </button>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" id="cancelConfirm" class="btn btn-secondary" data-mdb-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<script>
function updateEntry() {
    updateItemData();
}

function addModalButton(modalId, btnId, label, className, onClick) {
    const modalEl = document.getElementById(modalId);
    if (!modalEl) return;

    const footer = modalEl.querySelector('.modal-footer');
    if (!footer) return;

    if (footer.querySelector('#' + btnId)) return;

    const btn = document.createElement('button');
    btn.type = 'button';
    btn.id = btnId;
    btn.className = className;
    btn.textContent = label;
    btn.addEventListener('click', onClick);

    const cancelBtn = footer.querySelector('#cancelConfirm');
    if (cancelBtn && cancelBtn.parentNode === footer) {
        footer.insertBefore(btn, cancelBtn);
    } else {
        footer.appendChild(btn);
    }
}

(function() {
    const colourMap = {
        rose: {
            bg: '#fce4ec',
            text: '#6a1b3a',
            label: 'Rose'
        },
        red: {
            bg: '#fdecea',
            text: '#7f1d1d',
            label: 'Red'
        },
        orange: {
            bg: '#fff3e0',
            text: '#8a3b12',
            label: 'Orange'
        },
        amber: {
            bg: '#fff8e1',
            text: '#7a5600',
            label: 'Amber'
        },
        yellow: {
            bg: '#fffde7',
            text: '#6b5b00',
            label: 'Yellow'
        },
        lime: {
            bg: '#f1f8e9',
            text: '#466a12',
            label: 'Lime'
        },
        green: {
            bg: '#e8f5e9',
            text: '#1b5e20',
            label: 'Green'
        },
        mint: {
            bg: '#e6f7f1',
            text: '#0f5c4d',
            label: 'Mint'
        },
        cyan: {
            bg: '#e0f7fa',
            text: '#155e75',
            label: 'Cyan'
        },
        blue: {
            bg: '#e3f2fd',
            text: '#0d47a1',
            label: 'Blue'
        },
        indigo: {
            bg: '#e8eaf6',
            text: '#283593',
            label: 'Indigo'
        },
        purple: {
            bg: '#f3e5f5',
            text: '#6a1b9a',
            label: 'Purple'
        }
    };

    const hiddenInput = document.getElementById('row_colour');
    const preview = document.getElementById('plantColourPreview');
    const openBtn = document.getElementById('openPlantColourPicker');
    const clearBtn = document.getElementById('clearPlantColour');
    const modalEl = document.getElementById('plantColourPickerModal');

    function initTooltips(scope) {
        if (typeof mdb === 'undefined' || !scope) return;
        scope.querySelectorAll('[data-mdb-tooltip-init]').forEach((el) => {
            try {
                if (mdb.Tooltip.getInstance && mdb.Tooltip.getInstance(el)) return;
            } catch (e) {}
            try {
                new mdb.Tooltip(el);
            } catch (e) {}
        });
    }

    function applyPreview(key) {
        const cfg = colourMap[key] || null;

        if (!cfg) {
            preview.style.background = '#f8f9fa';
            preview.style.color = '#495057';
            preview.style.border = '1px solid rgba(0,0,0,0.08)';
            preview.innerHTML = 'No row colour selected';
            return;
        }

        preview.style.background = cfg.bg;
        preview.style.color = cfg.text;
        preview.style.border = '1px solid rgba(0,0,0,0.08)';
        preview.innerHTML = '<i class="fad fa-square-full me-2"></i>' + cfg.label + ' preview';
    }

    if (openBtn && modalEl && typeof mdb !== 'undefined' && mdb.Modal) {
        openBtn.addEventListener('click', () => {
            const modal = mdb.Modal.getOrCreateInstance(modalEl);
            modal.show();
        });
    }

    if (clearBtn) {
        clearBtn.addEventListener('click', () => {
            if (hiddenInput) hiddenInput.value = '';
            applyPreview('');
        });
    }

    document.querySelectorAll('.plant-colour-option').forEach((btn) => {
        btn.addEventListener('click', () => {
            const key = String(btn.getAttribute('data-colour') || '').trim();
            if (hiddenInput) hiddenInput.value = key;
            applyPreview(key);

            if (modalEl && typeof mdb !== 'undefined' && mdb.Modal) {
                const modal = mdb.Modal.getOrCreateInstance(modalEl);
                modal.hide();
            }
        });
    });

    applyPreview(hiddenInput ? String(hiddenInput.value || '').trim() : '');
    initTooltips(document);
})();

async function updatePlantOnly(form) {
    const res = await fetch(ROOT_URL + '/includes/jump/jump_functions.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: new URLSearchParams(new FormData(form))
    });
    return (await res.text()).trim();
}

async function updateItemPlantData(oldCode, newCode, newDesc) {
    const res = await fetch(ROOT_URL + '/includes/jump/jump_plant_check.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: new URLSearchParams({
            action: 'updateItemPlantData',
            old_code: String(oldCode),
            new_code: String(newCode),
            new_desc: String(newDesc),
            tenant: String(TENANT_URL)
        })
    });
    return (await res.text()).trim();
}

async function getPlantUsageByCode(code) {
    const res = await fetch(ROOT_URL + '/includes/jump/jump_plant_check.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: new URLSearchParams({
            action: 'plantUsageByCode',
            code: String(code),
            tenant: String(TENANT_URL)
        })
    });
    return await res.json().catch(() => null);
}

async function updateItemData() {
    const form = document.getElementById('editForm');
    if (!form) {
        if (typeof showResponse === 'function') showResponse('danger', 'FORM NOT FOUND');
        return;
    }

    const codeEl = form.querySelector('[name="code"]');
    const descEl = form.querySelector('[name="desc"]');
    const idEl = form.querySelector('[name="id"]');

    const oldCode = codeEl ? String(codeEl.defaultValue || '').trim() : '';
    const newCode = codeEl ? String(codeEl.value || '').trim() : '';
    const oldDesc = descEl ? String(descEl.defaultValue || '').trim() : '';
    const newDesc = descEl ? String(descEl.value || '').trim() : '';
    const id = idEl ? String(idEl.value || '').trim() : '';

    const htmlEscape = (value) => String(value ?? '').replace(/[&<>"']/g, (ch) => ({
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#039;'
    }[ch]));

    const affectedItemsTable = (items) => {
        const rows = (Array.isArray(items) ? items : []).map((item) =>
            '<tr>' +
            '<td>' + htmlEscape(item.itemnumber) + '</td>' +
            '<td>' + htmlEscape(item.clientname) + '</td>' +
            '<td>' + htmlEscape(item.description) + '</td>' +
            '<td>' + htmlEscape(item.plantnumber) + '</td>' +
            '<td>' + htmlEscape(item.serialnumber) + '</td>' +
            '</tr>'
        ).join('');

        return '<div class="table-responsive" style="max-height:320px; overflow:auto;">' +
            '<table class="table table-sm table-striped mb-0">' +
            '<thead><tr><th>Item</th><th>Client</th><th>Description</th><th>Plant No.</th><th>Serial No.</th></tr></thead>' +
            '<tbody>' + rows + '</tbody>' +
            '</table>' +
            '</div>';
    };

    const savePlant = async () => {
        const res = await fetch(ROOT_URL + '/includes/jump/jump_functions.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: new URLSearchParams(new FormData(form))
        });
        return (await res.text()).trim();
    };

    const codeChanged = (oldCode !== '' && newCode !== '' && oldCode !== newCode);
    const descChanged = (oldDesc !== newDesc);
    const itemUpdateNeeded = codeChanged || descChanged;

    let count = 0;
    let affectedItems = [];
    if (itemUpdateNeeded && oldCode !== '') {
        const res = await fetch(ROOT_URL + '/includes/jump/jump_plant_check.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: new URLSearchParams({
                action: 'plantUsageByCode',
                code: oldCode,
                tenant: String(TENANT_URL)
            })
        });

        const j = await res.json().catch(() => null);
        count = (j && j.status === 'success') ? Number(j.count || 0) : 0;
        affectedItems = (j && Array.isArray(j.items)) ? j.items : [];
    }

    if (!itemUpdateNeeded || count === 0) {
        const msg = '<p class="text-center">Sure you wish to update this entry?</p>';

        loadModalContent(
            msg,
            'confirmBox',
            'modal-sm',
            1070,
            'false',
            'Confirm Save',
            'cancelConfirm',
            async () => {
                const r = await savePlant();
                if (r !== 's') {
                    if (typeof showResponse === 'function') showResponse('danger', 'UPDATE FAILED');
                    return;
                }

                if (typeof showResponse === 'function') showResponse('success', 'ENTRY UPDATED');
                if (typeof refreshPlantRow === 'function') refreshPlantRow(id);
                if (typeof killModal === 'function') {
                    killModal('confirmBox');
                    killModal('editBox');
                }
            }
        );

        return;
    }

    const html =
        '<p class="text-center mb-2">Sure you wish to update this entry?</p>' +
        '<div class="note note-warning text-center mb-3">' +
        '<strong>' + count + '</strong> active item(s) are currently registered with <strong>' + htmlEscape(oldCode) + '</strong>.' +
        '<br><small>Confirming will also update those items to code <strong>' + htmlEscape(newCode) + '</strong> and description <strong>' + htmlEscape(newDesc) + '</strong>.</small>' +
        '</div>' +
        affectedItemsTable(affectedItems);

    loadModalContent(
        html,
        'confirmBox',
        'modal-lg',
        1070,
        'false',
        'Confirm Save',
        'cancelConfirm',
        async () => {
            const r = await savePlant();
            if (r !== 's') {
                if (typeof showResponse === 'function') showResponse('danger', 'UPDATE FAILED');
                return;
            }

            const u = await updateItemPlantData(oldCode, newCode, newDesc);
            if (u !== 's') {
                if (typeof showResponse === 'function') showResponse('danger', 'ITEM UPDATE FAILED');
                return;
            } else {
                if (typeof showResponse === 'function') showResponse('success', 'ENTRY AND ITEMS UPDATED');
            }

            if (typeof refreshPlantRow === 'function') refreshPlantRow(id);
            if (typeof killModal === 'function') {
                killModal('confirmBox');
                killModal('editBox');
            }
        }
    );
}
</script>
