<?php

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

function jumpTableExists(string $table): bool
{
    $table = $GLOBALS['con']->real_escape_string($table);
    $res = $GLOBALS['con']->query("SHOW TABLES LIKE '$table'");

    return $res && $res->num_rows > 0;
}

function jumpColumnExists(string $table, string $column): bool
{
    $table = $GLOBALS['con']->real_escape_string($table);
    $column = $GLOBALS['con']->real_escape_string($column);
    $res = $GLOBALS['con']->query("SHOW COLUMNS FROM `$table` LIKE '$column'");

    return $res && $res->num_rows > 0;
}

function jumpPhraseGroupsEnabled(): bool
{
    return jumpTableExists('dd_phrase_groups') && jumpColumnExists('dd_phrases', 'group_id');
}

function jumpResolvePhraseGroupId($groupId = null, string $groupName = ''): ?int
{
    if (!jumpPhraseGroupsEnabled()) {
        return null;
    }

    $gid = (int)$groupId;
    if ($gid > 0) {
        return $gid;
    }

    $groupName = trim($groupName);
    if ($groupName === '') {
        return null;
    }

    $stmt = $GLOBALS['con']->prepare("SELECT `id` FROM `dd_phrase_groups` WHERE `group_name` = ? AND `status` = 1 LIMIT 1");
    $stmt->bind_param('s', $groupName);
    $stmt->execute();
    $res = $stmt->get_result();
    $row = $res ? $res->fetch_assoc() : null;
    $stmt->close();

    return !empty($row['id']) ? (int)$row['id'] : null;
}

function normalisePlantRowColour(?string $value): ?string
{
    $value = trim((string)$value);

    if ($value === '') {
        return null;
    }

    $allowed = [
        'rose',
        'red',
        'orange',
        'amber',
        'yellow',
        'lime',
        'green',
        'mint',
        'cyan',
        'blue',
        'indigo',
        'purple'
    ];

    return in_array($value, $allowed, true) ? $value : null;
}

function jumpPlantDeliveryExclusionEnabled(): bool
{
    static $enabled = null;

    if ($enabled !== null) {
        return $enabled;
    }

    $enabled = false;

    try {
        $stmt = $GLOBALS['con']->prepare("SELECT `delivery_exclusion` FROM `dd_plant` LIMIT 1");
        if ($stmt) {
            $stmt->execute();
            $stmt->close();
            $enabled = true;
        }
    } catch (Throwable $e) {
        $enabled = false;
    }

    return $enabled;
}

function jumpPlantActiveItemCountById(int $id): int
{
    if ($id <= 0) {
        return 0;
    }

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

    $code = trim((string)($row['code'] ?? ''));
    if ($code === '') {
        return 0;
    }

    $stmt = $GLOBALS['con']->prepare("SELECT COUNT(*) AS c FROM `itemdetails` WHERE `statuslive` = 1 AND `code` = ?") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('s', $code);
    $stmt->execute();
    $rs = $stmt->get_result();
    $row = $rs ? $rs->fetch_assoc() : ['c' => 0];
    $stmt->close();

    return (int)($row['c'] ?? 0);
}

if (($_REQUEST['FUNCTION'] ?? '') === 'setPlantRowColour') {
    $id = (int)($_REQUEST['id'] ?? 0);
    $rowColour = normalisePlantRowColour($_REQUEST['row_colour'] ?? null);

    if ($id <= 0) {
        echo "e";
        exit;
    }

    $stmt = $GLOBALS['con']->prepare("
        UPDATE `dd_plant`
        SET `row_colour` = ?
        WHERE `id` = ?
    ") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('si', $rowColour, $id);
    $stmt->execute();
    $stmt->close();

    echo "s";
    exit;
}

if (($_REQUEST['FUNCTION'] ?? '') === 'setPlantDeliveryExclusion') {
    $id = (int)($_REQUEST['id'] ?? 0);
    $deliveryExclusion = (int)(($_REQUEST['delivery_exclusion'] ?? '0') === '1');

    if ($id <= 0) {
        echo "e";
        exit;
    }

    if (!jumpPlantDeliveryExclusionEnabled()) {
        echo "Delivery exclusion column missing";
        exit;
    }

    $stmt = $GLOBALS['con']->prepare("
        UPDATE `dd_plant`
        SET `delivery_exclusion` = ?
        WHERE `id` = ?
    ") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('ii', $deliveryExclusion, $id);
    $stmt->execute();
    $stmt->close();

    echo "s";
    exit;
}

function ensurePlantFilesDir(string $tenant): string {
    $base = rtrim($tenant, '/');
    $dir = '../../../' . $base . '/resources/plantFiles';
    if (!is_dir($dir)) {
        @mkdir($dir, 0755, true);
    }
    return $dir;
}

function safeFileName(string $name): string {
    $name = preg_replace('/[^A-Za-z0-9\.\-_]/', '_', $name);
    $name = preg_replace('/_+/', '_', $name);
    return trim($name, '_');
}

function phraseGroupsOptions(?int $selectedId = null): string {
    $html = '<option value="">All groups</option>';

    $stmt = $GLOBALS['con']->prepare("
        SELECT `id`, `group_name`
        FROM `dd_phrase_groups`
        WHERE `status`=1
        ORDER BY `group_name` ASC
    ");
    $stmt->execute();
    $res = $stmt->get_result();
    $stmt->close();

    while ($r = $res->fetch_assoc()) {
        $id = (int)$r['id'];
        $sel = ($selectedId !== null && $id === (int)$selectedId) ? ' selected' : '';
        $html .= '<option value="' . $id . '"' . $sel . '>' . htmlspecialchars($r['group_name']) . '</option>';
    }

    return $html;
}


if (($_REQUEST['FUNCTION'] ?? '') === 'uploadPlantDoc') {
    $id = (int)($_REQUEST['id'] ?? 0);
    $tenant = (string)($_REQUEST['tenant'] ?? '');

    if ($id <= 0 || $tenant === '') { echo "Invalid request"; exit; }
    if (!isset($_FILES['doc']) || $_FILES['doc']['error'] !== UPLOAD_ERR_OK) { echo "No file uploaded"; exit; }

    $dir = ensurePlantFilesDir($tenant);

    $orig = $_FILES['doc']['name'] ?? 'file';
    $tmp  = $_FILES['doc']['tmp_name'] ?? '';
    $ext  = strtolower(pathinfo($orig, PATHINFO_EXTENSION));

    // Allow common office + pdf + images
    $allowed = ['pdf','doc','docx','xls','xlsx','csv','png','jpg','jpeg','webp'];
    if (!in_array($ext, $allowed, true)) { echo "Unsupported file type"; exit; }

    $baseName = safeFileName(pathinfo($orig, PATHINFO_FILENAME));
    $stored = 'plant_' . $id . '_' . date('Ymd_His') . '_' . $baseName . '.' . $ext;
    $destPath = rtrim($dir, '/') . '/' . $stored;

    if (!@move_uploaded_file($tmp, $destPath)) { echo "Upload failed"; exit; }

    // Remove previous file if present
    $stmt = $GLOBALS['con']->prepare("SELECT doc_file FROM dd_plant WHERE id=? LIMIT 1");
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $res = $stmt->get_result();
    $old = $res ? $res->fetch_assoc() : null;
    $stmt->close();

    if (!empty($old['doc_file'])) {
        $oldPath = rtrim($dir, '/') . '/' . $old['doc_file'];
        if (is_file($oldPath)) @unlink($oldPath);
    }

    $stmt = $GLOBALS['con']->prepare("UPDATE dd_plant SET doc_file=? WHERE id=?");
    $stmt->bind_param('si', $stored, $id);
    $stmt->execute();
    $stmt->close();

    echo "s";
    exit;
}

if (($_REQUEST['FUNCTION'] ?? '') === 'deletePlantDoc') {
    $id = (int)($_REQUEST['id'] ?? 0);
    $tenant = (string)($_REQUEST['tenant'] ?? '');

    if ($id <= 0 || $tenant === '') { echo "Invalid request"; exit; }

    $dir = ensurePlantFilesDir($tenant);

    $stmt = $GLOBALS['con']->prepare("SELECT doc_file FROM dd_plant WHERE id=? LIMIT 1");
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $res = $stmt->get_result();
    $row = $res ? $res->fetch_assoc() : null;
    $stmt->close();

    if (!empty($row['doc_file'])) {
        $p = rtrim($dir, '/') . '/' . $row['doc_file'];
        if (is_file($p)) @unlink($p);
    }

    $stmt = $GLOBALS['con']->prepare("UPDATE dd_plant SET doc_file=NULL WHERE id=?");
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $stmt->close();

    echo "s";
    exit;
}

if (($_REQUEST['FUNCTION'] ?? '') === 'createPhraseGroup') {
    $name = trim((string)($_REQUEST['group_name'] ?? ''));
    if ($name === '') { echo "Group name required"; exit; }

    if (!jumpTableExists('dd_phrase_groups')) {
        echo "Phrase group table is missing";
        exit;
    }

    $stmt = $GLOBALS['con']->prepare("SELECT `id` FROM `dd_phrase_groups` WHERE `group_name` = ? LIMIT 1");
    $stmt->bind_param('s', $name);
    $stmt->execute();
    $res = $stmt->get_result();
    $exists = $res && $res->num_rows > 0;
    $stmt->close();

    if ($exists) {
        echo "Group already exists";
        exit;
    }

    $stmt = $GLOBALS['con']->prepare("INSERT INTO dd_phrase_groups (group_name, status) VALUES (?, 1)");
    $stmt->bind_param('s', $name);
    $ok = $stmt->execute();
    $stmt->close();

    if (!$ok) {
        $res = $GLOBALS['con']->query("SELECT COALESCE(MAX(`id`), 0) + 1 FROM `dd_phrase_groups`");
        $nextId = (int)($res ? $res->fetch_row()[0] : 1);
        $stmt = $GLOBALS['con']->prepare("INSERT INTO dd_phrase_groups (`id`, `group_name`, `status`) VALUES (?, ?, 1)");
        $stmt->bind_param('is', $nextId, $name);
        $ok = $stmt->execute();
        $stmt->close();
    }

    if (!$ok) {
        echo "Group could not be created";
        exit;
    }

    echo "s";
    exit;
}

if (($_REQUEST['FUNCTION'] ?? '') === 'deletePhraseGroup') {
    $gid = (int)($_REQUEST['group_id'] ?? 0);
    if ($gid <= 0) { echo "Invalid group"; exit; }

    if (jumpColumnExists('dd_phrases', 'group_id')) {
        $stmt = $GLOBALS['con']->prepare("UPDATE dd_phrases SET group_id=NULL WHERE group_id=?");
        $stmt->bind_param('i', $gid);
        $stmt->execute();
        $stmt->close();
    }

    $stmt = $GLOBALS['con']->prepare("DELETE FROM dd_phrase_groups WHERE id=?");
    $stmt->bind_param('i', $gid);
    $stmt->execute();
    $stmt->close();

    echo "s";
    exit;
}

if (($_REQUEST['FUNCTION'] ?? '') === 'bulkMovePhrases') {
    if (!jumpPhraseGroupsEnabled()) {
        echo "Phrase grouping is not fully configured";
        exit;
    }

    $gid = (int)($_REQUEST['group_id'] ?? 0);
    $ids = json_decode((string)($_REQUEST['ids'] ?? '[]'), true);
    if ($gid <= 0 || !is_array($ids)) {
        echo "Invalid move request";
        exit;
    }

    $cleanIds = [];
    foreach ($ids as $id) {
        $id = (int)$id;
        if ($id > 0) {
            $cleanIds[$id] = $id;
        }
    }

    if (empty($cleanIds)) {
        echo "No phrases selected";
        exit;
    }

    $stmt = $GLOBALS['con']->prepare("UPDATE `dd_phrases` SET `group_id` = ? WHERE `id` = ?");
    foreach ($cleanIds as $phraseId) {
        $stmt->bind_param('ii', $gid, $phraseId);
        $stmt->execute();
    }
    $stmt->close();

    echo "s";
    exit;
}
if (($_REQUEST['FCN'] ?? '') == 'genNewLists') {
    $stmt = $GLOBALS['con']->prepare("SELECT * FROM `dd_plant` ORDER BY `code` ASC") or die(mysqli_error($GLOBALS['con']));
    $stmt->execute();
    $cc = $stmt->get_result();
    $stmt->close();

    $ca = [];
    while ($pd = mysqli_fetch_array($cc)) {
        $ca[] = $pd;
    }

    $dat1 = '';
    foreach ($ca as $px) {
        $s = (($c ?? '') == $px['code']) ? 'SELECTED' : '';
        $dat1 .= '<option value="' . $px['code'] . '" title="' . $px['description'] . '" ' . $s . '>' . $px['code'] . '</option>';
    }

    $dat2 = '';
    foreach ($ca as $px) {
        $s = (($c ?? '') == $px['code']) ? 'SELECTED' : '';
        $dat2 .= '<option value="' . $px['description'] . '" title="' . $px['code'] . '" ' . $s . '>' . $px['description'] . '&nbsp;&nbsp;&nbsp;&nbsp;(' . $px['frequency'] . ' months)</option>';
    }

    echo $dat1 . '[SPLIT]' . $dat2;
    exit();
}

if ((($_REQUEST['FUNCTION'] ?? '') == 'save') || (($_REQUEST['FCN'] ?? '') == 'save')) {
    if (($_REQUEST['mode'] ?? '') == 'plant') {
        $code = trim((string)($_REQUEST['code'] ?? ''));
        $desc = trim((string)($_REQUEST['desc'] ?? ''));
        $freq = (int)($_REQUEST['freq'] ?? 0);
        $size = trim((string)($_REQUEST['size'] ?? ''));
        $units = (float)($_REQUEST['units'] ?? ($_REQUEST['unit'] ?? 0));
        $deliveryExclusion = (int)(($_REQUEST['delivery_exclusion'] ?? '0') === '1');

        $check = $GLOBALS['con']->prepare("SELECT `id` FROM `dd_plant` WHERE `code` = ? LIMIT 1") or die(mysqli_error($GLOBALS['con']));
        $check->bind_param('s', $code);
        $check->execute();
        $checkRs = $check->get_result();
        $exists = ($checkRs && $checkRs->num_rows > 0);
        $check->close();

        if ($exists) {
            echo 'e';
            exit();
        }

        if (jumpPlantDeliveryExclusionEnabled()) {
            $stmt = $GLOBALS['con']->prepare("INSERT INTO `dd_plant` (`code`, `description`, `frequency`, `size`, `units`, `delivery_exclusion`) VALUES (?, ?, ?, ?, ?, ?)") or die(mysqli_error($GLOBALS['con']));
            $stmt->bind_param('ssisdi', $code, $desc, $freq, $size, $units, $deliveryExclusion);
        } else {
            $stmt = $GLOBALS['con']->prepare("INSERT INTO `dd_plant` (`code`, `description`, `frequency`, `size`, `units`) VALUES (?, ?, ?, ?, ?)") or die(mysqli_error($GLOBALS['con']));
            $stmt->bind_param('ssisd', $code, $desc, $freq, $size, $units);
        }
        $ok = $stmt->execute();
        $stmt->close();

        echo $ok ? 's' : 'Save failed';
        exit();
    }

    if (($_REQUEST['mode'] ?? '') == 'phrase') {
        $code = trim((string)($_REQUEST['code'] ?? ''));
        $phrase = trim((string)($_REQUEST['phrase'] ?? ''));
        $groupId = jumpResolvePhraseGroupId($_REQUEST['group_id'] ?? null, (string)($_REQUEST['group_name'] ?? ''));

        $check = $GLOBALS['con']->prepare("SELECT `id` FROM `dd_phrases` WHERE `phrasecode` = ? LIMIT 1") or die(mysqli_error($GLOBALS['con']));
        $check->bind_param('s', $code);
        $check->execute();
        $checkRs = $check->get_result();
        $exists = ($checkRs && $checkRs->num_rows > 0);
        $check->close();

        if ($exists) {
            echo 'e';
            exit();
        }

        if (jumpPhraseGroupsEnabled()) {
            $stmt = $GLOBALS['con']->prepare("INSERT INTO `dd_phrases` (`phrasecode`, `phrase`, `group_id`) VALUES (?, ?, ?)") or die(mysqli_error($GLOBALS['con']));
            $stmt->bind_param('ssi', $code, $phrase, $groupId);
        } else {
            $stmt = $GLOBALS['con']->prepare("INSERT INTO `dd_phrases` (`phrasecode`, `phrase`) VALUES (?, ?)") or die(mysqli_error($GLOBALS['con']));
            $stmt->bind_param('ss', $code, $phrase);
        }
        $ok = $stmt->execute();
        $stmt->close();

        echo $ok ? 's' : 'Save failed';
        exit();
    }

    if (($_REQUEST['mode'] ?? '') == 'elecPhrase') {
        $check = mysqli_query($GLOBALS['con'], "SELECT `id` FROM `dd_elecphrases` WHERE `phrasecode`='" . $_REQUEST['code'] . "'");
        $cnum = mysqli_num_rows($check);
        if ($cnum == 0) {
            $_REQUEST['phrase'] = mysqli_real_escape_string($GLOBALS['con'], $_REQUEST['phrase']);
            $stmt = $GLOBALS['con']->prepare("INSERT INTO `dd_elecphrases` VALUES (NULL,'" . $_REQUEST['code'] . "','" . $_REQUEST['phrase'] . "',NULL)") or die($e = mysqli_error($GLOBALS['con']));
            $stmt->execute();
            echo 's';
        } else {
            echo 'e';
        }
        exit();
    }

    if (($_REQUEST['mode'] ?? '') == 'surveyorSkills') {
        $check = mysqli_query($GLOBALS['con'], "SELECT `id` FROM `dd_surveyorSkills` WHERE `description`='" . $_REQUEST['description'] . "' AND `discipline`='" . $_REQUEST['discipline'] . "'");
        $cnum = mysqli_num_rows($check);
        if ($cnum == 0) {
            $_REQUEST['description'] = mysqli_real_escape_string($GLOBALS['con'], $_REQUEST['description']);
            $stmt = $GLOBALS['con']->prepare("INSERT INTO `dd_surveyorSkills` VALUES (NULL,'" . $_REQUEST['discipline'] . "','" . $_REQUEST['description'] . "')") or die($e = mysqli_error($GLOBALS['con']));
            $stmt->execute();
            echo 's';
        } else {
            echo 'e';
        }
        exit();
    }
}

if (($_REQUEST['FUNCTION'] ?? '') == 'remove') {
    $table = (string)($_REQUEST['table'] ?? '');
    $id = (int)($_REQUEST['id'] ?? 0);
    $allowedTables = ['plant', 'phrases', 'elecphrases', 'surveyorSkills'];

    if ($id <= 0 || !in_array($table, $allowedTables, true)) {
        echo 'Invalid delete request';
        exit();
    }

    if ($table === 'plant') {
        $affectedItems = jumpPlantActiveItemCountById($id);
        if ($affectedItems > 0) {
            echo 'This plant is assigned to ' . $affectedItems . ' active item(s) and cannot be removed.';
            exit();
        }
    }

    $stmt = $GLOBALS['con']->prepare("DELETE FROM `dd_" . $table . "` WHERE `id` = ?") or die($e = mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $id);
    $stmt->execute();
    echo 's' . ($e ?? '');
    exit();
}

if (($_REQUEST['FUNCTION'] ?? '') == 'update') {
    if (($_REQUEST['mode'] ?? '') == 'plant') {
        $id = (int)($_REQUEST['id'] ?? 0);
        $code = trim((string)($_REQUEST['code'] ?? ''));
        $desc = trim((string)($_REQUEST['desc'] ?? ''));
        $freq = (int)($_REQUEST['freq'] ?? 0);
        $size = trim((string)($_REQUEST['size'] ?? ''));
        $units = (float)($_REQUEST['units'] ?? 0);
        $rowColour = normalisePlantRowColour($_REQUEST['row_colour'] ?? null);

        if ($id <= 0 || $code === '' || $desc === '') {
            echo 'Invalid plant update';
            exit();
        }

        if (jumpPlantDeliveryExclusionEnabled()) {
            $deliveryExclusion = (int)(($_REQUEST['delivery_exclusion'] ?? '0') === '1');
            $stmt = $GLOBALS['con']->prepare("
                UPDATE `dd_plant`
                SET `code` = ?,
                    `description` = ?,
                    `frequency` = ?,
                    `size` = ?,
                    `units` = ?,
                    `row_colour` = ?,
                    `delivery_exclusion` = ?
                WHERE `id` = ?
            ") or die($e = mysqli_error($GLOBALS['con']));
            $stmt->bind_param('ssisdsii', $code, $desc, $freq, $size, $units, $rowColour, $deliveryExclusion, $id);
        } else {
            $stmt = $GLOBALS['con']->prepare("
                UPDATE `dd_plant`
                SET `code` = ?,
                    `description` = ?,
                    `frequency` = ?,
                    `size` = ?,
                    `units` = ?,
                    `row_colour` = ?
                WHERE `id` = ?
            ") or die($e = mysqli_error($GLOBALS['con']));
            $stmt->bind_param('ssisdsi', $code, $desc, $freq, $size, $units, $rowColour, $id);
        }
        $stmt->execute();
        $stmt->close();
    }

    if (($_REQUEST['mode'] ?? '') == 'phrases') {
        $id = (int)($_REQUEST['id'] ?? 0);
        $phrasecode = trim((string)($_REQUEST['phrasecode'] ?? ''));
        $phrase = trim((string)($_REQUEST['phrase'] ?? ''));
        $groupId = jumpResolvePhraseGroupId($_REQUEST['group_id'] ?? null, (string)($_REQUEST['group_name'] ?? ''));

        if (jumpPhraseGroupsEnabled()) {
            $stmt = $GLOBALS['con']->prepare("UPDATE `dd_phrases` SET `phrasecode`=?, `phrase`=?, `group_id`=? WHERE `id`=?") or die(mysqli_error($GLOBALS['con']));
            $stmt->bind_param('ssii', $phrasecode, $phrase, $groupId, $id);
        } else {
            $stmt = $GLOBALS['con']->prepare("UPDATE `dd_phrases` SET `phrasecode`=?, `phrase`=? WHERE `id`=?") or die(mysqli_error($GLOBALS['con']));
            $stmt->bind_param('ssi', $phrasecode, $phrase, $id);
        }
        $stmt->execute();
        $stmt->close();
    }

    if (($_REQUEST['mode'] ?? '') == 'elecphrases') {
        $_REQUEST['phrase'] = mysqli_real_escape_string($GLOBALS['con'], $_REQUEST['phrase']);
        $stmt = $GLOBALS['con']->prepare("UPDATE `dd_elecphrases` SET
`phrasecode`='" . $_REQUEST['phrasecode'] . "',
`phrase`='" . $_REQUEST['phrase'] . "'
WHERE `id`='" . $_REQUEST['id'] . "'
") or die($e = mysqli_error($GLOBALS['con']));
        $stmt->execute();
    }

    if (($_REQUEST['mode'] ?? '') == 'surveyorSkills') {
        $_REQUEST['description'] = mysqli_real_escape_string($GLOBALS['con'], $_REQUEST['description']);
        $stmt = $GLOBALS['con']->prepare("UPDATE `dd_surveyorSkills` SET
`discipline`='" . $_REQUEST['discipline'] . "',
`description`='" . $_REQUEST['description'] . "'
WHERE `id`='" . $_REQUEST['id'] . "'
") or die(mysqli_error($GLOBALS['con']));
        $stmt->execute();
    }

    echo 's';
    exit();
}

function getItems($type, $format)
{
    $stmt = $GLOBALS['con']->prepare("SELECT * FROM `dd_" . $type . "`") or die(mysqli_error($GLOBALS['con']));
    $stmt->execute();
    $rslt = $stmt->get_result();
    switch ($type) {
        default:
            break;

        case 'phrases': ?>
<div class="col-md-12 pt-4">
    <table id="phraseTable" class="table table-striped table-hover responsive" style="width:100%">
        <thead>
            <tr>
                <th width="10%">Code</th>
                <th>Phrase</th>
                <th class="no-sort"></th>
            </tr>
        </thead>
        <tbody>
            <?php while ($d = mysqli_fetch_array($rslt)) { ?>
            <tr>
                <td width="10%">
                    <form id="phr<?= $d['id'] ?>"></form>
                    <span style="display: none"><?= $d['phrasecode'] ?></span>
                    <input type="text" class="form-control form-control-sm" aria-label="phrasecode" name="phrasecode" form="phr<?= $d['id'] ?>" value="<?= $d['phrasecode'] ?>" />
                </td>
                <td>
                    <span style="display: none"><?= $d['phrase'] ?></span>
                    <textarea type="text" class="form-control form-control-sm" aria-label="phrase" name="phrase" rows="3" form="phr<?= $d['id'] ?>"><?= universalDecode($d['phrase']) ?></textarea>
                </td>
                <td class="text-end"><button class="btn btn-outline-success me-3" onClick="update('phr<?= $d['id'] ?>','phrases','<?= $d['id'] ?>')" type="button"><i class="fad fa-save" aria-hidden="true"></i></button><button class="btn btn-outline-danger" type="button" onClick="remove('phrases','<?= $d['id'] ?>')"><i class="fad fa-trash" aria-hidden="true"></i></button>
                    <input type="hidden" form="phr<?= $d['id'] ?>" name="id" value="<?= $d['id'] ?>">
                    <input type="hidden" form="phr<?= $d['id'] ?>" name="table" value="phrases">
                    <input type="hidden" form="phr<?= $d['id'] ?>" name="mode" value="phrases">
                    <input type="hidden" form="phr<?= $d['id'] ?>" name="FUNCTION" value="update">
                    <input type="hidden" form="phr<?= $d['id'] ?>" name="tenant" value="<?= TENANT_URL ?>">
                </td>
            </tr>
            <?php } ?>
        </tbody>
    </table>
</div>
<?php
            $table = 'phraseTable';
            $pageTitle = 'Engineering Phrases List';
            $dateTarget = '';
            $length = '25';
            $sortTarget = '';
            $sortCell = 'nth-child(2)';
            $logo = 'yes';
            $scroller = '';
            require_once('../tables/single_table.php');
            break;

        case 'plant': ?>
<div class="col-md-12 pt-4">
    <table id="plantTable" class="table table-striped table-hover table-sm responsive" style="width:100%">
        <thead>
            <tr>
                <th width="10%">Code</th>
                <th>Description</th>
                <th>Frequency</th>
                <th>Size</th>
                <th>Units</th>
                <th class="no-sort"></th>
            </tr>
        </thead>
        <tbody>
            <?php while ($d = mysqli_fetch_array($rslt)) { ?>
            <tr id="R<?= $d['code'] ?>">
                <td><span><?= $d['code'] ?></span></td>
                <td><span><?= $d['description'] ?></span></td>
                <td><span><?= $d['frequency'] ?></span></td>
                <td><span><?= $d['size'] ?></span></td>
                <td><span><?= $d['units'] ?></span></td>
                <td class="text-end"><button class="btn btn-outline-info me-3" onClick="edit('<?= $d['id'] ?>')" type="button"><i class="fad fa-pencil" aria-hidden="true"></i></button><button class="btn btn-outline-danger" type="button" onClick="remove('plant','<?= $d['id'] ?>')"><i class="fad fa-trash" aria-hidden="true"></i></button></td>
            </tr>
            <?php } ?>
        </tbody>
    </table>
</div>
<?php
            $table = 'plantTable';
            $pageTitle = 'Plant List';
            $dateTarget = '';
            $length = '25';
            $sortTarget = '';
            $sortCell = 'nth-child(2)';
            $logo = 'yes';
            $scroller = '';
            require_once('../tables/single_table.php');
            break;
    }
    $stmt->free_result();
    $stmt->close();
}

if (isset($_REQUEST['FUNCTION'])) {
    echo getItems($_REQUEST['type'], $_REQUEST['format']);
}
?>
