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

$type = strtolower(trim((string)($_REQUEST['type'] ?? 'plant')));
if (!in_array($type, ['plant', 'phrases'], true)) {
    $type = 'plant';
}

$phraseGroups = [];
if ($type === 'phrases' && isset($GLOBALS['con']) && $GLOBALS['con'] instanceof mysqli) {
    $groupRes = mysqli_query($GLOBALS['con'], "SHOW TABLES LIKE 'dd_phrase_groups'");
    if ($groupRes && mysqli_num_rows($groupRes) > 0) {
        $stmt = $GLOBALS['con']->prepare("SELECT `id`, `group_name` FROM `dd_phrase_groups` WHERE `status`=1 ORDER BY `group_name` ASC");
        if ($stmt) {
            $stmt->execute();
            $res = $stmt->get_result();
            $stmt->close();
            while ($row = $res->fetch_assoc()) {
                $phraseGroups[] = $row;
            }
        }
    }
}
?>

<form id="jumpNewEntryForm">
    <div class="row">
        <?php if ($type === 'plant') { ?>
        <div class="col-12 col-md-6 mb-3">
            <h5 class="mb-2">Code</h5>
            <input type="text"
                   id="jumpNewCode"
                   name="code"
                   class="form-control form-control-sm"
                   aria-label="Code"
                   value="" />
        </div>

        <div class="col-12 col-md-6 mb-3">
            <h5 class="mb-2">Description</h5>
            <input type="text"
                   id="jumpNewDesc"
                   name="desc"
                   class="form-control form-control-sm"
                   aria-label="Description"
                   value="" />
        </div>

        <div class="col-12 col-md-4 mb-3">
            <h5 class="mb-2">Frequency</h5>
            <input type="text"
                   id="jumpNewFreq"
                   name="freq"
                   class="form-control form-control-sm"
                   aria-label="Frequency"
                   value="" />
        </div>

        <input type="hidden" name="size" value="" />

        <div class="col-12 col-md-4 mb-3">
            <h5 class="mb-2">IU</h5>
            <input type="text"
                   name="units"
                   class="form-control form-control-sm"
                   aria-label="Units"
                   value="" />
        </div>

        <div class="col-12 mb-3">
            <div class="form-check form-switch">
                <input class="form-check-input"
                       type="checkbox"
                       role="switch"
                       id="jumpNewDeliveryExclusion"
                       name="delivery_exclusion"
                       value="1">
                <label class="form-check-label" for="jumpNewDeliveryExclusion">
                    Delivery exclusion
                </label>
            </div>
        </div>

        <input type="hidden" name="mode" value="plant">
        <?php } ?>

        <?php if ($type === 'phrases') { ?>
        <div class="col-12 col-md-4 mb-3">
            <h5 class="mb-2">Code</h5>
            <input type="text"
                   id="jumpPhraseCode"
                   name="code"
                   class="form-control form-control-sm"
                   aria-label="Code"
                   maxlength="10"
                   value="" />
        </div>

        <div class="col-12 col-md-8 mb-3">
            <h5 class="mb-2">Group</h5>
            <select name="group_id" class="form-select form-select-sm">
                <option value="">No group</option>
                <?php foreach ($phraseGroups as $groupRow) { ?>
                    <option value="<?= (int)$groupRow['id'] ?>"><?= htmlspecialchars((string)$groupRow['group_name'], ENT_QUOTES, 'UTF-8') ?></option>
                <?php } ?>
            </select>
        </div>

        <div class="col-12 mb-3">
            <h5 class="mb-2">Phrase</h5>
            <textarea id="jumpPhraseText"
                      name="phrase"
                      class="form-control form-control-sm"
                      aria-label="Phrase"
                      rows="6"></textarea>
        </div>

        <input type="hidden" name="mode" value="phrase">
        <?php } ?>

        <input type="hidden" name="FUNCTION" value="save">
        <input type="hidden" name="tenant" value="<?= htmlspecialchars((string)TENANT_URL) ?>">
    </div>

    <div class="row">
        <div class="col-12 text-center">
            <button type="submit"
                    class="btn btn-success me-2"
                    data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Save entry">
                <i class="fad fa-save me-2" aria-hidden="true"></i>Save Entry
            </button>

            <button type="button"
                    class="btn btn-secondary"
                    onclick="killModal('popupBox')"
                    data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Close">
                <i class="fad fa-times me-2" aria-hidden="true"></i>Cancel
            </button>
        </div>
    </div>
</form>

<script>
(function() {
    const form = document.getElementById('jumpNewEntryForm');
    const type = '<?= $type ?>';

    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 validate() {
        if (type === 'plant') {
            const code = String((document.getElementById('jumpNewCode') || {}).value || '').trim();
            const desc = String((document.getElementById('jumpNewDesc') || {}).value || '').trim();
            const freq = String((document.getElementById('jumpNewFreq') || {}).value || '').trim();

            if (!code || !desc || !freq) {
                showResponse('warning', 'Please enter a code, description and frequency');
                return false;
            }
        }

        if (type === 'phrases') {
            const code = String((document.getElementById('jumpPhraseCode') || {}).value || '').trim();
            const phrase = String((document.getElementById('jumpPhraseText') || {}).value || '').trim();

            if (!code || !phrase) {
                showResponse('warning', 'Please enter a code and phrase');
                return false;
            }

            if (code.length > 10) {
                showResponse('warning', 'Phrase codes are limited to 10 characters');
                return false;
            }
        }

        return true;
    }

    async function submitForm(event) {
        if (event) event.preventDefault();

        if (!form) {
            showResponse('danger', 'Form not found');
            return;
        }

        if (!validate()) {
            return;
        }

        try {
            const response = await fetch(ROOT_URL + '/includes/jump/jump_functions.php', {
                method: 'POST',
                body: new FormData(form)
            });

            const ret = String(await response.text()).trim();

            if (ret === 's') {
                showResponse('success', 'Your entry has been saved successfully');
                document.dispatchEvent(new CustomEvent('jump:new:done', {
                    detail: {
                        type: type
                    }
                }));
                killModal('popupBox');
                return;
            }

            if (ret === 'e') {
                showResponse('warning', 'The code is already in the system');
                return;
            }

            showResponse('danger', ret || 'Save failed');
        } catch (error) {
            showResponse('danger', 'An error occurred while saving');
        }
    }

    if (form) {
        form.addEventListener('submit', submitForm);
    }

    initTooltips(document);
})();
</script>
