<?php
require_once __DIR__ . '/../../functions/logging.php';

if (defined('TENANT_URL') && !empty(TENANT_URL)) {
    $_REQUEST['tenant'] = TENANT_URL;
}


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

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


if (!function_exists('enrepReportPdfOptionsFromRequest')) {
    function enrepReportPdfOptionsFromRequest(array $request): array
    {
        $orientation = (string)($request['orientation'] ?? $request['pageMode'] ?? '1');
        $orientation = ($orientation === '0' || strtoupper($orientation) === 'L' || strtolower($orientation) === 'landscape') ? '0' : '1';

        return [
            'version' => 1,
            'orientation' => $orientation,
            'imageMode' => ((string)($request['imageMode'] ?? '0') === '1') ? '1' : '0',
            'tagMode' => ((string)($request['tagMode'] ?? '0') === '1') ? '1' : '0',
        ];
    }
}

if (!function_exists('enrepReportPdfOptionsFromRow')) {
    function enrepReportPdfOptionsFromRow(array $row): ?array
    {
        if (empty($row['report_pdf_options'])) {
            return null;
        }

        $options = json_decode((string)$row['report_pdf_options'], true);
        if (!is_array($options)) {
            return null;
        }

        return enrepReportPdfOptionsFromRequest($options);
    }
}

if (!function_exists('enrepSaveReportPdfOptions')) {
    function enrepSaveReportPdfOptions(mysqli $con, int $repnumber, array $request): void
    {
        if ($repnumber < 1) {
            return;
        }

        $json = json_encode(enrepReportPdfOptionsFromRequest($request), JSON_UNESCAPED_SLASHES);
        if ($json === false) {
            return;
        }

        try {
            $stmt = $con->prepare("UPDATE `reportitems` SET `report_pdf_options`=? WHERE `repnumber`=?");
        } catch (mysqli_sql_exception $e) {
            return;
        }

        $stmt->bind_param('si', $json, $repnumber);
        try {
            $stmt->execute();
        } catch (mysqli_sql_exception $e) {
            $stmt->close();
            return;
        }
        $stmt->close();
    }
}

if (!function_exists('enrepApplyReportPdfOptions')) {
    function enrepApplyReportPdfOptions(array $reportRow): void
    {
        $options = enrepReportPdfOptionsFromRow($reportRow);
        if (!$options) {
            return;
        }

        if (!isset($_REQUEST['orientation']) && !isset($_REQUEST['pageMode']) && isset($options['orientation'])) {
            $_REQUEST['orientation'] = (string)$options['orientation'];
        }
        if (!isset($_REQUEST['imageMode']) && isset($options['imageMode'])) {
            $_REQUEST['imageMode'] = (string)$options['imageMode'];
        }
        if (!isset($_REQUEST['tagMode']) && isset($options['tagMode'])) {
            $_REQUEST['tagMode'] = (string)$options['tagMode'];
        }
    }
}

if (!function_exists('enrepReportFixedFields')) {
    function enrepReportFixedFields(): array
    {
        return [
            'repitem',
            'repnumber',
            'master_report_id',
            'repnumberold',
            'olddate',
            'insdate',
            'nextDate',
            'repdate',
            'delivery',
            'clientnumber',
            'itemnumber',
            'esname',
            'frequency',
            'reptype',
            'result',
            'report_pdf_options',
        ];
    }
}

if (!function_exists('enrepReportDataFields')) {
    function enrepReportDataFields(): array
    {
        return [
            'adefect',
            'bdefect',
            'obs',
            'pnareason',
            'partialReason',
            'ffcomments',
            'code',
            'viewed',
            'history',
            'changeScheme',
            'resultOfExam',
            'lastReportSeen',
            'examType',
            'partsCovered',
            'lease_or_hire',
            'partsInaccessible',
            'conditionInternal',
            'conditionExternal',
            'conditionFittings',
            'protectiveDevices',
            '9b1',
            '9b2',
            '9b3',
            'processConditions',
            'class',
            'ebond',
            'ires',
            'volts',
            'nature',
            'test_procedure',
            'process_conditions',
            'effective',
            'particulars',
            'other_comments',
            'usage_comments',
            'noise',
            'intended_performance',
            'achieving_perfomance',
            'repair_details',
            'rack',
            'rackRun',
            'beam',
            'accessories',
            'handling',
            'stability',
            'clutch',
            'safety',
        ];
    }
}

if (!function_exists('enrepReportRequestControlFields')) {
    function enrepReportRequestControlFields(): array
    {
        return array_fill_keys(array_merge(
            enrepReportFixedFields(),
            enrepReportDataFields(),
            [
                'FUNCTION',
                'ajax',
                'data',
                'dataSet',
                'dest',
                'formnumber',
                'imageMode',
                'imageset',
                'item',
                'items',
                'mode',
                'oldnumber',
                'orientation',
                'p',
                'pageMode',
                'rep',
                'repnumberold',
                'savemode',
                't',
                'tagMode',
                'tagmode',
                'tenant',
                'view',
            ]
        ), true);
    }
}

if (!function_exists('enrepReportDataValueIsJsonSafe')) {
    function enrepReportDataValueIsJsonSafe($value): bool
    {
        if ($value === null || is_scalar($value)) {
            return true;
        }

        return is_array($value);
    }
}

if (!function_exists('enrepDecodeJsonArray')) {
    function enrepDecodeJsonArray($value): array
    {
        if (is_array($value)) {
            return $value;
        }

        if (!is_string($value) || trim($value) === '') {
            return [];
        }

        $decoded = json_decode($value, true);
        return is_array($decoded) ? $decoded : [];
    }
}

if (!function_exists('enrepReportDataFromRow')) {
    function enrepReportDataFromRow(array $row): array
    {
        $reportData = enrepDecodeJsonArray($row['reportdata'] ?? '');

        if (isset($reportData['version']) && isset($reportData['fields']) && is_array($reportData['fields'])) {
            $reportData = $reportData['fields'];
        }

        return $reportData;
    }
}

if (!function_exists('enrepReportFixedDataFromRequest')) {
    function enrepReportFixedDataFromRequest(array $request, bool $isCreate): array
    {
        $data = [];

        if ($isCreate) {
            $data['repnumberold'] = (string)($request['oldnumber'] ?? $request['repnumberold'] ?? '');
            $data['delivery'] = (int)($request['delivery'] ?? 0);
            $data['clientnumber'] = (int)($request['clientnumber'] ?? 0);
        } elseif (array_key_exists('oldnumber', $request) || array_key_exists('repnumberold', $request)) {
            $data['repnumberold'] = (string)($request['oldnumber'] ?? $request['repnumberold'] ?? '');
        }

        if (array_key_exists('olddate', $request)) {
            $oldDateString = trim((string)$request['olddate']);
            $data['olddate'] = ($oldDateString === 'Not Known' || $oldDateString === '')
                ? 'Not Known'
                : strtotime($oldDateString);
        }

        if (array_key_exists('insdate', $request)) {
            $data['insdate'] = strtotime((string)$request['insdate']);
        }

        if (array_key_exists('nextDate', $request)) {
            $data['nextDate'] = strtotime((string)$request['nextDate']);
        }

        if (array_key_exists('repdate', $request)) {
            $data['repdate'] = strtotime((string)$request['repdate']);
        }

        if (array_key_exists('itemnumber', $request)) {
            $data['itemnumber'] = (int)$request['itemnumber'];
        }

        if (array_key_exists('surveyor', $request) || array_key_exists('esname', $request)) {
            $data['esname'] = (string)($request['surveyor'] ?? $request['esname'] ?? '');
        }

        foreach (['frequency', 'reptype', 'result'] as $field) {
            if (array_key_exists($field, $request)) {
                $data[$field] = (string)$request[$field];
            }
        }

        return $data;
    }
}

if (!function_exists('enrepReportDataFromRequest')) {
    function enrepReportDataFromRequest(array $request, array $existing = []): array
    {
        $reportData = $existing;
        $controlFields = enrepReportRequestControlFields();

        foreach (enrepReportDataFields() as $field) {
            if (!array_key_exists($field, $request)) {
                continue;
            }

            $value = $request[$field];

            if ($field === 'process_conditions') {
                $decoded = enrepDecodeJsonArray($value);
                if (!empty($decoded)) {
                    foreach ($decoded as $decodedKey => $decodedValue) {
                        $reportData[(string)$decodedKey] = $decodedValue;
                    }
                    continue;
                }
            }

            $reportData[$field] = $value;
        }

        foreach ($request as $field => $value) {
            $field = (string)$field;

            if ($field === '' || isset($controlFields[$field])) {
                continue;
            }

            if (!enrepReportDataValueIsJsonSafe($value)) {
                continue;
            }

            $reportData[$field] = $value;
        }

        return $reportData;
    }
}

if (!function_exists('enrepReportDataJson')) {
    function enrepReportDataJson(array $reportData): string
    {
        $json = json_encode($reportData, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        return $json === false ? '{}' : $json;
    }
}

if (!function_exists('enrepReportRowDataFromRequest')) {
    function enrepReportRowDataFromRequest(array $request, bool $isCreate, array $existingReportData = []): array
    {
        $data = enrepReportFixedDataFromRequest($request, $isCreate);
        $data['reportdata'] = enrepReportDataJson(enrepReportDataFromRequest($request, $existingReportData));

        return $data;
    }
}

if (!function_exists('enrepApplyReportDataToItemDetails')) {
    function enrepApplyReportDataToItemDetails(array $itemDetails, array $reportData): array
    {
        foreach (['pressure', 'lev'] as $group) {
            if (isset($reportData[$group]) && is_array($reportData[$group])) {
                $itemDetails = array_replace($itemDetails, $reportData[$group]);
            }
        }

        foreach (['changeScheme', 'lastReportSeen', 'lease_or_hire', 'scheme_number_alt', 'system_type'] as $field) {
            if (array_key_exists($field, $reportData) && $reportData[$field] !== '') {
                $itemDetails[$field] = $reportData[$field];
            }
        }

        return $itemDetails;
    }
}


if (empty($split)) {
    $split = '';
}
if (isset($_REQUEST['FUNCTION'])) {
    enrep_log_request_completion('reports', 'FUNCTION', [
        'update_item_details' => ['action' => 'asset_details_updated', 'message' => 'Updated report asset details', 'entity_type' => 'itemdetails'],
        'save_for_later' => ['action' => 'draft_saved', 'message' => 'Saved report for later', 'entity_type' => 'reportitems'],
        'create' => ['action' => 'created', 'message' => 'Created report', 'entity_type' => 'reportitems'],
        'createITE' => ['action' => 'item_test_created', 'message' => 'Created ITE report item', 'entity_type' => 'reportitems'],
        'createfromsaved' => ['action' => 'created_from_draft', 'message' => 'Created report from saved draft', 'entity_type' => 'reportitems'],
        'update' => ['action' => 'updated', 'message' => 'Updated report', 'entity_type' => 'reportitems'],
        'update_for_later' => ['action' => 'draft_updated', 'message' => 'Updated saved report draft', 'entity_type' => 'reportitems'],
        'removeInitial' => ['action' => 'initial_removed', 'message' => 'Removed initial report data', 'entity_type' => 'reportitems'],
    ]);
    switch ($_REQUEST['FUNCTION']) {
        default:
            break;
        case "setDate":
            $end_date = date("d-m-Y", strtotime("+" . $_REQUEST['offset'] . " month", strtotime(date("d-m-Y", strtotime($_REQUEST['date'])))));
            echo $end_date;
            break;

        case "removeInitial":
            $stmt = $GLOBALS['con']->prepare("DELETE FROM `lev_results_initial` WHERE `id`=?") or die(mysqli_error($GLOBALS['con']));
            $stmt->bind_param('i', $_REQUEST['item']);
            $stmt->execute();
            $stmt->close();
            echo "success";
            break;

        case "getLastInspection":
            $stmt = $GLOBALS['con']->prepare("SELECT `currdate` FROM `itemdetails` WHERE `itemnumber`=?") or die(mysqli_error($GLOBALS['con']));
            $stmt->bind_param('i', $_REQUEST['itemnumber']);
            $stmt->execute();
            $cr = $stmt->get_result();
            $stmt->close();
            $pd = mysqli_fetch_array($cr);
            if (!$pd || empty($pd['currdate']) || (int)$pd['currdate'] < 1) {
                echo 'Not Known';
            } else {
                echo date('d-m-Y', (int)$pd['currdate']);
            }
            break;


        case "update_item_details":
            $stmt = $GLOBALS['con']->prepare("UPDATE `itemdetails` SET `desc`=?,`plantnumber`=?,`model`=?,`serialnumber`=?,`subloc`=?,`manf`=?,`detailedloc`=?,`swl`=?,`locnumber`=?,`dateofmanf`=? WHERE `itemnumber`=?") or die(mysqli_error($GLOBALS['con']));
            $stmt->bind_param('ssssssssisi', $_REQUEST['desc'], $_REQUEST['plantnumber'], $_REQUEST['model'], $_REQUEST['serialnumber'], $_REQUEST['subloc'], $_REQUEST['manf'], $_REQUEST['detailedloc'], $_REQUEST['swl'], $_REQUEST['siteList'], $_REQUEST['dateofmanf'], $_REQUEST['itemnumber']);
            $stmt->execute();
            $stmt->close();
            //genSchedule($_REQUEST['clientnumber']);
            echo "success";
            break;

        case "save_for_later":

            foreach ($_REQUEST as $key => $val) {
                if ($key == "hidContent" || $key == "crypt") {
                } else {
                    $_REQUEST[$key] = str_replace("'", "&#39;", $_REQUEST[$key]);
                }
            }

            if (!empty($_REQUEST['protectiveDevicesNarrative'])) {
                $_REQUEST['protectiveDevices'] = $_REQUEST['protectiveDevices'] . "|" . $_REQUEST['protectiveDevicesNarrative'];
            }

            if ($_REQUEST['reptype'] == "800" || $_REQUEST['reptype'] == "801") {
                if ($_REQUEST['parts_2_alt'] == "on") {
                    $_REQUEST['parts_2'] = "100010";
                }
                if ($_REQUEST['parts_3_alt'] == "on") {
                    $_REQUEST['parts_3'] = "100020";
                }

                $_REQUEST['partsInaccessible'] = $_REQUEST['parts_1'] . "|" . $_REQUEST['parts_2'] . "|" . $_REQUEST['parts_3'];
                $_REQUEST['adefect'] = $_REQUEST['adefect_1'] . "|" . $_REQUEST['adefect_2'] . "|" . $_REQUEST['adefect_3'];
            }

            if ($_REQUEST['reptype'] == "802") {
                $_REQUEST['safety'] = $_REQUEST['safety_1'] . "|" . $_REQUEST['safety_2'] . "|" . $_REQUEST['safety_3'] . "|" . $_REQUEST['safety_4'] . "|" . $_REQUEST['safety_5'] . "|" . $_REQUEST['safety_6'] . "|" . $_REQUEST['safety_7'] . "|" . $_REQUEST['safety_8'] . "|" . $_REQUEST['safety_9'] . "|" . $_REQUEST['safety_10'] . "|" . $_REQUEST['safety_11'] . "|" . $_REQUEST['safety_12'] . "|" . $_REQUEST['safety_13'];
                $_REQUEST['repair_details'] = $_REQUEST['repair_1'] . "|" . $_REQUEST['repair_2'];
            }

            if (function_exists('tenantCustomProcessing')) {
                tenantCustomProcessing($_REQUEST['reptype']);
            }

            if (function_exists('tenantReportUsesMultiItemRows') && tenantReportUsesMultiItemRows($_REQUEST) && function_exists('puwerGetPrimaryResultFromRequest')) {
                $puwerPrimaryResult = puwerGetPrimaryResultFromRequest($_REQUEST);
                if ($puwerPrimaryResult !== null) {
                    $_REQUEST['result'] = $puwerPrimaryResult;
                }
            }

            $repnumber = strtotime('now');
            $data = enrepReportRowDataFromRequest($_REQUEST, true);

            $columns = implode(", ", array_keys($data));
            $placeholders = implode(", ", array_fill(0, count($data), '?'));
            $sql = "INSERT INTO `reportitems_temp` (repitem, repnumber, $columns) VALUES (NULL, '$repnumber', $placeholders)";
            $stmt = $GLOBALS['con']->prepare($sql) or die(mysqli_error($GLOBALS['con']));

            $types = '';
            $values = [];

            foreach ($data as $value) {
                if (is_int($value)) {
                    $types .= 'i';
                } elseif (is_float($value)) {
                    $types .= 'd';
                } else {
                    $types .= 's';
                }
                $values[] = $value;
            }

            $stmt->bind_param($types, ...$values);
            $stmt->execute();

            if ($stmt->error) {
                echo "Error: " . $stmt->error;
                $stmt->close();
                break;
            }

            $stmt->close();
            echo "success";
            break;


        case "create":

            foreach ($_REQUEST as $key => $val) {
                if ($key == "hidContent" || $key == "crypt") {
                } else {
                    $_REQUEST[$key] = str_replace("'", "&#39;", $_REQUEST[$key]);
                }
            }

            if (!empty($_REQUEST['protectiveDevicesNarrative'])) {
                $_REQUEST['protectiveDevices'] = $_REQUEST['protectiveDevices'] . "|" . $_REQUEST['protectiveDevicesNarrative'];
            }

            $e = '';
            $formClass = '';

            if ($_REQUEST['olddate'] == "Not Known" || $_REQUEST['olddate'] == "0"  || $_REQUEST['olddate'] == "") {
                $olddate = "Not Known";
            } else {
                $olddate = strtotime($_REQUEST['olddate']);
            }

            if ($_REQUEST['reptype'] == "800" || $_REQUEST['reptype'] == "801") {
                if ($_REQUEST['parts_2_alt'] == "on") {
                    $_REQUEST['parts_2'] = "100010";
                }
                if ($_REQUEST['parts_3_alt'] == "on") {
                    $_REQUEST['parts_3'] = "100020";
                }

                $_REQUEST['partsInaccessible'] = $_REQUEST['parts_1'] . "|" . $_REQUEST['parts_2'] . "|" . $_REQUEST['parts_3'];
                $_REQUEST['adefect'] = $_REQUEST['adefect_1'] . "|" . $_REQUEST['adefect_2'] . "|" . $_REQUEST['adefect_3'];
            }

            if ($_REQUEST['reptype'] == "802") {
                $_REQUEST['safety'] = $_REQUEST['safety_1'] . "|" . $_REQUEST['safety_2'] . "|" . $_REQUEST['safety_3'] . "|" . $_REQUEST['safety_4'] . "|" . $_REQUEST['safety_5'] . "|" . $_REQUEST['safety_6'] . "|" . $_REQUEST['safety_7'] . "|" . $_REQUEST['safety_8'] . "|" . $_REQUEST['safety_9'] . "|" . $_REQUEST['safety_10'] . "|" . $_REQUEST['safety_11'] . "|" . $_REQUEST['safety_12'] . "|" . $_REQUEST['safety_13'];
                $_REQUEST['repair_details'] = $_REQUEST['repair_1'] . "|" . $_REQUEST['repair_2'];
            }

            if (function_exists('tenantCustomProcessing')) {
                tenantCustomProcessing($_REQUEST['reptype']);
            }

            if (function_exists('tenantReportUsesMultiItemRows') && tenantReportUsesMultiItemRows($_REQUEST) && function_exists('puwerGetPrimaryResultFromRequest')) {
                $puwerPrimaryResult = puwerGetPrimaryResultFromRequest($_REQUEST);
                if ($puwerPrimaryResult !== null) {
                    $_REQUEST['result'] = $puwerPrimaryResult;
                }
            }

            $data = enrepReportRowDataFromRequest($_REQUEST, true);

            /*
    |--------------------------------------------------------------------------
    | Tenant multi-item report: one committed report row per linked item
    |--------------------------------------------------------------------------
    */
            if (function_exists('tenantReportUsesMultiItemRows') && tenantReportUsesMultiItemRows($_REQUEST) && function_exists('puwerExtractResultMapFromRequest') && function_exists('puwerInsertReportitemsRow') && function_exists('puwerUpdateLinkedItemdetails') && function_exists('puwerNormaliseResult')) {

                $resultMap = puwerExtractResultMapFromRequest($_REQUEST);

                if (empty($resultMap)) {
                    echo 'Error: no PUWER item result map was found in process_conditions';
                    break;
                }

                $masterReportId = (string) ((int) round(microtime(true) * 1000));
                $baseRepnumber = (int) $masterReportId;
                $primaryItemnumber = (int) ($_REQUEST['itemnumber'] ?? 0);
                $primaryRepnumber = 0;
                $seq = 0;

                $GLOBALS['con']->begin_transaction();

                try {
                    foreach ($resultMap as $itemnumber => $result) {
                        $itemnumber = (int) $itemnumber;
                        if ($itemnumber <= 0) {
                            continue;
                        }

                        $rowRepnumber = (string) ($baseRepnumber + $seq);
                        $seq++;

                        $rowData = $data;
                        $rowData['master_report_id'] = $masterReportId;
                        $rowData['clientnumber'] = (int) $_REQUEST['clientnumber'];
                        $rowData['itemnumber'] = $itemnumber;
                        $rowData['result'] = puwerNormaliseResult($result);

                        $insertError = puwerInsertReportitemsRow($GLOBALS['con'], (int) $rowRepnumber, $rowData, null);
                        if ($insertError !== '') {
                            throw new RuntimeException($insertError);
                        }

                        if ($itemnumber === $primaryItemnumber) {
                            $primaryRepnumber = (int) $rowRepnumber;
                        }

                        if ($primaryRepnumber === 0) {
                            $primaryRepnumber = (int) $rowRepnumber;
                        }
                    }

                    $itemdetailsError = puwerUpdateLinkedItemdetails($GLOBALS['con'], $_REQUEST, $resultMap);
                    if ($itemdetailsError !== '') {
                        throw new RuntimeException($itemdetailsError);
                    }

                    $GLOBALS['con']->commit();

                    enrepSaveReportPdfOptions($GLOBALS['con'], (int)$primaryRepnumber, $_REQUEST);

                    echo "success|" . $primaryRepnumber;
                    break;
                } catch (Throwable $e) {
                    $GLOBALS['con']->rollback();
                    echo 'Error: ' . $e->getMessage();
                    break;
                }
            }

            /*
    |--------------------------------------------------------------------------
    | Standard single-item create for all other report types
    |--------------------------------------------------------------------------
    */
            $repnumber = strtotime('now');

            $columns = implode(", ", array_keys($data));
            $placeholders = implode(", ", array_fill(0, count($data), '?'));
            $sql = "INSERT INTO `reportitems` (repitem, repnumber, $columns) VALUES (NULL, '$repnumber', $placeholders)";
            $stmt = $GLOBALS['con']->prepare($sql) or die(mysqli_error($GLOBALS['con']));

            $types = '';
            $values = [];

            foreach ($data as $key => $value) {
                if (is_int($value)) {
                    $types .= 'i';
                } elseif (is_float($value)) {
                    $types .= 'd';
                } else {
                    $types .= 's';
                }
                $values[] = $value;
            }

            $stmt->bind_param($types, ...$values);
            $stmt->execute();

            if ($stmt->error) {
                echo "Error: " . $stmt->error;
                $stmt->close();
                break;
            }

            $stmt->close();

            $stmt = $GLOBALS['con']->prepare("UPDATE `itemdetails` SET `currdate`=?,`duedate`=?,`history`=?,`lastReport`=? WHERE `itemnumber`=?") or die(mysqli_error($GLOBALS['con']));
            $stmt->bind_param('iissi', strtotime($_REQUEST['insdate']), strtotime($_REQUEST['nextDate']), $_REQUEST['history'], $_REQUEST['result'], $_REQUEST['itemnumber']);
            $stmt->execute();

            if ($stmt->error) {
                echo "Error: " . $stmt->error;
                $stmt->close();
                break;
            }

            $stmt->close();

            if ($_REQUEST['formClass'] == "lev_initial") {
                $stmtDeleteInitial = $GLOBALS['con']->prepare("DELETE FROM `lev_results_initial` WHERE `itemnumber`=?") or die(mysqli_error($GLOBALS['con']));
                $stmtDeleteInitial->bind_param('i', $_REQUEST['itemnumber']);
                $stmtDeleteInitial->execute();

                if ($stmtDeleteInitial->error) {
                    echo "Error: " . $stmtDeleteInitial->error;
                    $stmtDeleteInitial->close();
                    break;
                }

                $stmtDeleteInitial->close();

                foreach (range(1, $_REQUEST['pointRows']) as $r) {
                    if ($_REQUEST['point_number' . $r] !== "") {
                        $faceVelocityRequired = (string)($_REQUEST['face_velocity_required' . $r] ?? '');
                        $stmt = $GLOBALS['con']->prepare("INSERT INTO `lev_results_initial` (`report_number`, `point_number`, `point_detail`, `hoodDuct_size`, `faceDuct_velocity`, `face_velocity_required`, `static_pressure`, `volume_flow`, `itemnumber`) VALUES(?,?,?,?,?,?,?,?,?)") or die(mysqli_error($GLOBALS['con']));
                        $stmt->bind_param('isssssssi', $repnumber, $_REQUEST['point_number' . $r], $_REQUEST['point_detail' . $r], $_REQUEST['hoodDuct_size' . $r], $_REQUEST['faceDuct_velocity' . $r], $faceVelocityRequired, $_REQUEST['static_pressure' . $r], $_REQUEST['volume_flow' . $r], $_REQUEST['itemnumber']);
                        $stmt->execute();

                        if ($stmt->error) {
                            echo "Error: " . $stmt->error;
                            $stmt->close();
                            break 2;
                        }

                        $stmt->close();
                    }
                }
            }

            if ($_REQUEST['formClass'] == "lev_periodical") {
                foreach (range(1, $_REQUEST['pointRows']) as $r) {
                    if (!empty($_REQUEST['point_number' . $r])) {
                        $stmt = $GLOBALS['con']->prepare("INSERT INTO `lev_results` VALUES(
                    NULL,
                    '" . $repnumber . "',
                    '" . $_REQUEST['point_number' . $r] . "',
                    '" . $_REQUEST['point_detail' . $r] . "',
                    '" . $_REQUEST['hoodDuct_size' . $r] . "',
                    '" . $_REQUEST['faceDuct_velocity' . $r] . "',
                    '" . $_REQUEST['static_pressure' . $r] . "',
                    '" . $_REQUEST['volume_flow' . $r] . "',
                    '" . $_REQUEST['itemnumber'] . "',
                    '" . $_REQUEST['initial_number'] . "'
                )") or die(mysqli_error($GLOBALS['con']));
                        $stmt->execute();

                        if ($stmt->error) {
                            echo "Error: " . $stmt->error;
                            $stmt->close();
                            break 2;
                        }

                        $stmt->close();
                    }
                }
            }

            enrepSaveReportPdfOptions($GLOBALS['con'], (int)$repnumber, $_REQUEST);

            echo "success|" . $repnumber;
            break;

        case "createITE":
            ini_set('display_errors', 1);
            ini_set('display_startup_errors', 1);
            error_reporting(E_ALL);
            if ($_SERVER['REQUEST_METHOD'] === 'POST') {
                // Capture the unique identifier and index number from the form submission
                $uniqueIdentifier = $_POST['uniqueIdentifier'];
                $indexNumber = intval($_POST['indexNumber']);
                $clientNumber = $_REQUEST['clientnumber'];
                $surveyor = $_REQUEST['surveyor'];
                // Iterate over each card submitted
                for ($i = 1; $i <= $indexNumber; $i++) {
                    // Fetch card-specific data
                    $itemnumber = mysqli_real_escape_string($con, $_POST["C{$i}_itemnumber"]);
                    $testEquipment = mysqli_real_escape_string($con, $_POST["C{$i}_testEquipment"]);
                    $testApplied = mysqli_real_escape_string($con, $_POST["C{$i}_testApplied"]);
                    $testValueApplied = mysqli_real_escape_string($con, $_POST["C{$i}_testValueApplied"]);
                    $result = mysqli_real_escape_string($con, $_POST["C{$i}_outcome"]);
                    $survey = mysqli_real_escape_string($con, $_POST['surveyor']);
                    $frequency = mysqli_real_escape_string($con, $_POST['frequency']);
                    $observationDetail = isset($_POST["C{$i}_obs"]) ? mysqli_real_escape_string($con, $_POST["C{$i}_obs"]) : 'None';

                    // Dates
                    $insDate = strtotime($_POST['insdate']);
                    $nextDate = strtotime($_POST['nextDate']);
                    $repdate = $insDate;

                    $reportdata = enrepReportDataJson([
                        'test_procedure' => $testEquipment,
                        'process_conditions' => $testApplied,
                        'effective' => $testValueApplied,
                        'viewed' => $uniqueIdentifier,
                        'obs' => $observationDetail,
                    ]);
                    $repnumber = strtotime('now') + $i;

                    $stmt = $GLOBALS['con']->prepare("
                        INSERT INTO `reportitems`
                            (`repnumber`, `olddate`, `insdate`, `nextDate`, `clientnumber`, `itemnumber`, `result`, `esname`, `frequency`, `reptype`, `reportdata`)
                        VALUES
                            (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                    ") or die(mysqli_error($GLOBALS['con']));
                    $reptype = (string)($_REQUEST['reptype'] ?? '901');
                    $stmt->bind_param('iiiiiisssss', $repnumber, $insDate, $insDate, $nextDate, $clientNumber, $itemnumber, $result, $surveyor, $frequency, $reptype, $reportdata);
                    $stmt->execute();

                    if ($stmt->error) {
                        $error = $stmt->error;
                        $stmt->close();
                        die("Database insert failed: " . $error);
                    }

                    $stmt->close();
                }

                echo "success";
            }
            break;

        case "createfromsaved":

            foreach ($_REQUEST as $key => $val) {
                if ($key == "hidContent" || $key == "crypt") {
                } else {
                    $_REQUEST[$key] = str_replace("'", "&#39;", $_REQUEST[$key]);
                }
            }

            if (!empty($_REQUEST['protectiveDevicesNarrative'])) {
                $_REQUEST['protectiveDevices'] = $_REQUEST['protectiveDevices'] . "|" . $_REQUEST['protectiveDevicesNarrative'];
            }

            if ($_REQUEST['reptype'] == "800" || $_REQUEST['reptype'] == "801") {
                if ($_REQUEST['parts_2_alt'] == "on") {
                    $_REQUEST['parts_2'] = "100010";
                }
                if ($_REQUEST['parts_3_alt'] == "on") {
                    $_REQUEST['parts_3'] = "100020";
                }

                $_REQUEST['partsInaccessible'] = $_REQUEST['parts_1'] . "|" . $_REQUEST['parts_2'] . "|" . $_REQUEST['parts_3'];
                $_REQUEST['adefect'] = $_REQUEST['adefect_1'] . "|" . $_REQUEST['adefect_2'] . "|" . $_REQUEST['adefect_3'];
            }

            if ($_REQUEST['reptype'] == "802") {
                $_REQUEST['safety'] = $_REQUEST['safety_1'] . "|" . $_REQUEST['safety_2'] . "|" . $_REQUEST['safety_3'] . "|" . $_REQUEST['safety_4'] . "|" . $_REQUEST['safety_5'] . "|" . $_REQUEST['safety_6'] . "|" . $_REQUEST['safety_7'] . "|" . $_REQUEST['safety_8'] . "|" . $_REQUEST['safety_9'] . "|" . $_REQUEST['safety_10'] . "|" . $_REQUEST['safety_11'] . "|" . $_REQUEST['safety_12'] . "|" . $_REQUEST['safety_13'];
                $_REQUEST['repair_details'] = $_REQUEST['repair_1'] . "|" . $_REQUEST['repair_2'];
            }

            if (function_exists('tenantCustomProcessing')) {
                tenantCustomProcessing($_REQUEST['reptype']);
            }

            if (function_exists('tenantReportUsesMultiItemRows') && tenantReportUsesMultiItemRows($_REQUEST) && function_exists('puwerGetPrimaryResultFromRequest')) {
                $puwerPrimaryResult = puwerGetPrimaryResultFromRequest($_REQUEST);
                if ($puwerPrimaryResult !== null) {
                    $_REQUEST['result'] = $puwerPrimaryResult;
                }
            }

            $repnumber = strtotime('now');
            $data = enrepReportRowDataFromRequest($_REQUEST, true);

            $columns = implode(", ", array_keys($data));
            $placeholders = implode(", ", array_fill(0, count($data), '?'));
            $sql = "INSERT INTO `reportitems` (repitem, repnumber, $columns) VALUES (NULL, '$repnumber', $placeholders)";
            $stmt = $GLOBALS['con']->prepare($sql) or die(mysqli_error($GLOBALS['con']));

            $types = '';
            $values = [];

            foreach ($data as $value) {
                if (is_int($value)) {
                    $types .= 'i';
                } elseif (is_float($value)) {
                    $types .= 'd';
                } else {
                    $types .= 's';
                }
                $values[] = $value;
            }

            $stmt->bind_param($types, ...$values);
            $stmt->execute();

            if ($stmt->error) {
                echo "Error: " . $stmt->error;
                $stmt->close();
                break;
            }

            $stmt->close();

            if (function_exists('tenantReportUsesMultiItemRows') && tenantReportUsesMultiItemRows($_REQUEST) && function_exists('puwerRebuildCommittedReportitems')) {
                $puwerError = puwerRebuildCommittedReportitems($GLOBALS['con'], $_REQUEST, $data, null, (int)$repnumber);
                if ($puwerError !== '') {
                    echo $puwerError;
                    break;
                }
            } else {
                $stmt = $GLOBALS['con']->prepare("UPDATE `itemdetails` SET `currdate`=?,`duedate`=?,`history`=?,`lastReport`=? WHERE `itemnumber`=?") or die(mysqli_error($GLOBALS['con']));
                $stmt->bind_param('iissi', strtotime($_REQUEST['insdate']), strtotime($_REQUEST['nextDate']), $_REQUEST['history'], $_REQUEST['result'], $_REQUEST['itemnumber']);
                $stmt->execute();

                if ($stmt->error) {
                    echo "Error: " . $stmt->error;
                    $stmt->close();
                    break;
                }

                $stmt->close();
            }

            if ($_REQUEST['formClass'] == "lev_initial") {
                $stmtDeleteInitial = $GLOBALS['con']->prepare("DELETE FROM `lev_results_initial` WHERE `itemnumber`=?") or die(mysqli_error($GLOBALS['con']));
                $stmtDeleteInitial->bind_param('i', $_REQUEST['itemnumber']);
                $stmtDeleteInitial->execute();

                if ($stmtDeleteInitial->error) {
                    echo "Error: " . $stmtDeleteInitial->error;
                    $stmtDeleteInitial->close();
                    break;
                }

                $stmtDeleteInitial->close();

                foreach (range(1, $_REQUEST['pointRows']) as $r) {
                    if ($_REQUEST['point_number' . $r] !== "") {
                        $faceVelocityRequired = (string)($_REQUEST['face_velocity_required' . $r] ?? '');
                        $stmt = $GLOBALS['con']->prepare("INSERT INTO `lev_results_initial` (`report_number`, `point_number`, `point_detail`, `hoodDuct_size`, `faceDuct_velocity`, `face_velocity_required`, `static_pressure`, `volume_flow`, `itemnumber`) VALUES(?,?,?,?,?,?,?,?,?)") or die(mysqli_error($GLOBALS['con']));
                        $stmt->bind_param('isssssssi', $repnumber, $_REQUEST['point_number' . $r], $_REQUEST['point_detail' . $r], $_REQUEST['hoodDuct_size' . $r], $_REQUEST['faceDuct_velocity' . $r], $faceVelocityRequired, $_REQUEST['static_pressure' . $r], $_REQUEST['volume_flow' . $r], $_REQUEST['itemnumber']);
                        $stmt->execute();

                        if ($stmt->error) {
                            echo "Error: " . $stmt->error;
                            $stmt->close();
                            break 2;
                        }

                        $stmt->close();
                    }
                }
            }

            if ($_REQUEST['formClass'] == "lev_periodical") {
                foreach (range(1, $_REQUEST['pointRows']) as $r) {
                    if (!empty($_REQUEST['point_number' . $r])) {
                        $stmt = $GLOBALS['con']->prepare("INSERT INTO `lev_results` VALUES(
                    NULL,
                    '" . $repnumber . "',
                    '" . $_REQUEST['point_number' . $r] . "',
                    '" . $_REQUEST['point_detail' . $r] . "',
                    '" . $_REQUEST['hoodDuct_size' . $r] . "',
                    '" . $_REQUEST['faceDuct_velocity' . $r] . "',
                    '" . $_REQUEST['static_pressure' . $r] . "',
                    '" . $_REQUEST['volume_flow' . $r] . "',
                    '" . $_REQUEST['itemnumber'] . "',
                    '" . $_REQUEST['initial_number'] . "'
                )") or die(mysqli_error($GLOBALS['con']));
                        $stmt->execute();

                        if ($stmt->error) {
                            echo "Error: " . $stmt->error;
                            $stmt->close();
                            break 2;
                        }

                        $stmt->close();
                    }
                }
            }

            $stmt = $GLOBALS['con']->prepare("DELETE FROM `reportitems_temp` WHERE `repnumber`=?") or die(mysqli_error($GLOBALS['con']));
            $stmt->bind_param('i', $_REQUEST['repnumber']);
            $stmt->execute();

            if ($stmt->error) {
                echo "Error: " . $stmt->error;
                $stmt->close();
                break;
            }

            $stmt->close();

            enrepSaveReportPdfOptions($GLOBALS['con'], (int)$repnumber, $_REQUEST);

            echo "success|" . $repnumber . "|" . $_REQUEST['repnumber'];
            break;


        case "update":

            foreach ($_REQUEST as $key => $val) {
                if ($key == "hidContent" || $key == "crypt") {
                } else {
                    $_REQUEST[$key] = str_replace("'", "&#39;", $_REQUEST[$key]);
                }
            }

            if (!empty($_REQUEST['protectiveDevicesNarrative'])) {
                $_REQUEST['protectiveDevices'] = $_REQUEST['protectiveDevices'] . "|" . $_REQUEST['protectiveDevicesNarrative'];
            }

            if ($_REQUEST['olddate'] == "Not Known" || $_REQUEST['olddate'] == "") {
                $olddate = "Not Known";
            } else {
                $olddate = strtotime($_REQUEST['olddate']);
            }

            if ($_REQUEST['reptype'] == "800" || $_REQUEST['reptype'] == "801") {
                if ($_REQUEST['parts_2_alt'] == "on") {
                    $_REQUEST['parts_2'] = "100010";
                }
                if ($_REQUEST['parts_3_alt'] == "on") {
                    $_REQUEST['parts_3'] = "100020";
                }

                $_REQUEST['partsInaccessible'] = $_REQUEST['parts_1'] . "|" . $_REQUEST['parts_2'] . "|" . $_REQUEST['parts_3'];
                $_REQUEST['adefect'] = $_REQUEST['adefect_1'] . "|" . $_REQUEST['adefect_2'] . "|" . $_REQUEST['adefect_3'];
            }

            if ($_REQUEST['reptype'] == "802") {
                $_REQUEST['safety'] = $_REQUEST['safety_1'] . "|" . $_REQUEST['safety_2'] . "|" . $_REQUEST['safety_3'] . "|" . $_REQUEST['safety_4'] . "|" . $_REQUEST['safety_5'] . "|" . $_REQUEST['safety_6'] . "|" . $_REQUEST['safety_7'] . "|" . $_REQUEST['safety_8'] . "|" . $_REQUEST['safety_9'] . "|" . $_REQUEST['safety_10'] . "|" . $_REQUEST['safety_11'] . "|" . $_REQUEST['safety_12'] . "|" . $_REQUEST['safety_13'];
                $_REQUEST['repair_details'] = $_REQUEST['repair_1'] . "|" . $_REQUEST['repair_2'];
            }

            if (function_exists('tenantCustomProcessing')) {
                tenantCustomProcessing($_REQUEST['reptype']);
            }

            if (function_exists('tenantReportUsesMultiItemRows') && tenantReportUsesMultiItemRows($_REQUEST) && function_exists('puwerGetPrimaryResultFromRequest')) {
                $puwerPrimaryResult = puwerGetPrimaryResultFromRequest($_REQUEST);
                if ($puwerPrimaryResult !== null) {
                    $_REQUEST['result'] = $puwerPrimaryResult;
                }
            }

            $existingReportData = [];
            $existingReportStmt = $GLOBALS['con']->prepare("SELECT `reportdata` FROM `reportitems` WHERE `repnumber`=? LIMIT 1");
            if ($existingReportStmt) {
                $existingReportStmt->bind_param('i', $_REQUEST['repnumber']);
                if ($existingReportStmt->execute()) {
                    $existingReportRes = $existingReportStmt->get_result();
                    $existingReportRow = mysqli_fetch_assoc($existingReportRes);
                    if (is_array($existingReportRow)) {
                        $existingReportData = enrepReportDataFromRow($existingReportRow);
                    }
                }
                $existingReportStmt->close();
            }

            $data = enrepReportRowDataFromRequest($_REQUEST, false, $existingReportData);

            if (function_exists('tenantReportUsesMultiItemRows') && tenantReportUsesMultiItemRows($_REQUEST) && function_exists('puwerRebuildCommittedReportitems')) {
                $puwerError = puwerRebuildCommittedReportitems($GLOBALS['con'], $_REQUEST, $data, null, (int)$_REQUEST['repnumber']);
                if ($puwerError !== '') {
                    echo $puwerError;
                    break;
                }

                enrepSaveReportPdfOptions($GLOBALS['con'], (int)($_REQUEST['repnumber'] ?? 0), $_REQUEST);

                $puwerGenerationRows = function_exists('puwerGetCommittedReportGenerationRows')
                    ? puwerGetCommittedReportGenerationRows($GLOBALS['con'], (int)$_REQUEST['repnumber'])
                    : [];

                echo "update_success|" . json_encode($puwerGenerationRows, JSON_UNESCAPED_SLASHES);
                break;
            }

            $set_clause = implode(", ", array_map(function ($key) {
                return "`$key` = ?";
            }, array_keys($data)));

            $sql = "UPDATE `reportitems` SET $set_clause WHERE `repnumber` = ?";
            $stmt = $GLOBALS['con']->prepare($sql) or die(mysqli_error($GLOBALS['con']));

            $types = '';
            $values = [];

            foreach ($data as $value) {
                if (is_int($value)) {
                    $types .= 'i';
                } elseif (is_float($value)) {
                    $types .= 'd';
                } else {
                    $types .= 's';
                }
                $values[] = $value;
            }

            $types .= 'i';
            $values[] = $_REQUEST['repnumber'];

            $stmt->bind_param($types, ...$values);
            $stmt->execute();

            if ($stmt->error) {
                echo "Error: " . $stmt->error;
                $stmt->close();
                break;
            }

            $stmt->close();

            if (function_exists('tenantReportUsesMultiItemRows') && tenantReportUsesMultiItemRows($_REQUEST) && function_exists('puwerRebuildCommittedReportitems')) {
                $puwerError = puwerRebuildCommittedReportitems($GLOBALS['con'], $_REQUEST, $data, null, (int)$_REQUEST['repnumber']);
                if ($puwerError !== '') {
                    echo $puwerError;
                    break;
                }
            } else {
                $stmt = $GLOBALS['con']->prepare("UPDATE `itemdetails` SET `currdate`=?,`duedate`=?,`history`=?,`lastReport`=? WHERE `itemnumber`=?") or die(mysqli_error($GLOBALS['con']));
                $stmt->bind_param('iissi', strtotime($_REQUEST['insdate']), strtotime($_REQUEST['nextDate']), $_REQUEST['history'], $_REQUEST['result'], $_REQUEST['itemnumber']);
                $stmt->execute();

                if ($stmt->error) {
                    echo "Error: " . $stmt->error;
                    $stmt->close();
                    break;
                }

                $stmt->close();
            }

            if ($_REQUEST['formClass'] == "lev_initial") {
                $stmt = $GLOBALS['con']->prepare("DELETE FROM `lev_results_initial` WHERE `itemnumber`=?") or die(mysqli_error($GLOBALS['con']));
                $stmt->bind_param('i', $_REQUEST['itemnumber']);
                $stmt->execute();

                if ($stmt->error) {
                    echo "Error: " . $stmt->error;
                    $stmt->close();
                    break;
                }

                $stmt->close();

                foreach (range(1, $_REQUEST['pointRows']) as $r) {
                    if ($_REQUEST['point_number' . $r] != "") {
                        $faceVelocityRequired = (string)($_REQUEST['face_velocity_required' . $r] ?? '');
                        $stmt = $GLOBALS['con']->prepare("INSERT INTO `lev_results_initial` (`report_number`, `point_number`, `point_detail`, `hoodDuct_size`, `faceDuct_velocity`, `face_velocity_required`, `static_pressure`, `volume_flow`, `itemnumber`) VALUES(?,?,?,?,?,?,?,?,?)") or die(mysqli_error($GLOBALS['con']));
                        $stmt->bind_param('isssssssi', $_REQUEST['repnumber'], $_REQUEST['point_number' . $r], $_REQUEST['point_detail' . $r], $_REQUEST['hoodDuct_size' . $r], $_REQUEST['faceDuct_velocity' . $r], $faceVelocityRequired, $_REQUEST['static_pressure' . $r], $_REQUEST['volume_flow' . $r], $_REQUEST['itemnumber']);
                        $stmt->execute();

                        if ($stmt->error) {
                            echo "Error: " . $stmt->error;
                            $stmt->close();
                            break 2;
                        }

                        $stmt->close();
                    }
                }
            }

            if ($_REQUEST['formClass'] == "lev_periodical") {
                $stmtD = $GLOBALS['con']->prepare("DELETE FROM `lev_results` WHERE `report_number`='" . $_REQUEST['repnumber'] . "'") or die(mysqli_error($GLOBALS['con']));
                $stmtD->execute();

                if ($stmtD->error) {
                    echo "Error: " . $stmtD->error;
                    $stmtD->close();
                    break;
                }

                $stmtD->close();

                foreach (range(1, $_REQUEST['pointRows']) as $r) {
                    if (!empty($_REQUEST['point_number' . $r])) {
                        $stmtP = $GLOBALS['con']->prepare("INSERT INTO `lev_results` VALUES(
                    null,
                    '" . $_REQUEST['repnumber'] . "',
                    '" . $_REQUEST['point_number' . $r] . "',
                    '" . $_REQUEST['point_detail' . $r] . "',
                    '" . $_REQUEST['hoodDuct_size' . $r] . "',
                    '" . $_REQUEST['faceDuct_velocity' . $r] . "',
                    '" . $_REQUEST['static_pressure' . $r] . "',
                    '" . $_REQUEST['volume_flow' . $r] . "',
                    '" . $_REQUEST['itemnumber'] . "',
                    '" . $_REQUEST['initial_number'] . "'
                )") or die(mysqli_error($GLOBALS['con']));
                        $stmtP->execute();

                        if ($stmtP->error) {
                            echo "Error: " . $stmtP->error;
                            $stmtP->close();
                            break 2;
                        }

                        $stmtP->close();
                    }
                }
            }

            enrepSaveReportPdfOptions($GLOBALS['con'], (int)($_REQUEST['repnumber'] ?? 0), $_REQUEST);

            echo "update_success";
            break;

        case "update_for_later":

            foreach ($_REQUEST as $key => $val) {
                if ($key == "hidContent" || $key == "crypt") {
                } else {
                    $_REQUEST[$key] = str_replace("'", "&#39;", $_REQUEST[$key]);
                }
            }

            if (!empty($_REQUEST['protectiveDevicesNarrative'])) {
                $_REQUEST['protectiveDevices'] = $_REQUEST['protectiveDevices'] . "|" . $_REQUEST['protectiveDevicesNarrative'];
            }

            if ($_REQUEST['olddate'] == "Not Known" || $_REQUEST['olddate'] == "") {
                $olddate = "Not Known";
            } else {
                $olddate = strtotime($_REQUEST['olddate']);
            }

            if ($_REQUEST['reptype'] == "800" || $_REQUEST['reptype'] == "801") {
                if ($_REQUEST['parts_2_alt'] == "on") {
                    $_REQUEST['parts_2'] = "100010";
                }
                if ($_REQUEST['parts_3_alt'] == "on") {
                    $_REQUEST['parts_3'] = "100020";
                }

                $_REQUEST['partsInaccessible'] = $_REQUEST['parts_1'] . "|" . $_REQUEST['parts_2'] . "|" . $_REQUEST['parts_3'];
                $_REQUEST['adefect'] = $_REQUEST['adefect_1'] . "|" . $_REQUEST['adefect_2'] . "|" . $_REQUEST['adefect_3'];
            }

            if ($_REQUEST['reptype'] == "802") {
                $_REQUEST['safety'] = $_REQUEST['safety_1'] . "|" . $_REQUEST['safety_2'] . "|" . $_REQUEST['safety_3'] . "|" . $_REQUEST['safety_4'] . "|" . $_REQUEST['safety_5'] . "|" . $_REQUEST['safety_6'] . "|" . $_REQUEST['safety_7'] . "|" . $_REQUEST['safety_8'] . "|" . $_REQUEST['safety_9'] . "|" . $_REQUEST['safety_10'] . "|" . $_REQUEST['safety_11'] . "|" . $_REQUEST['safety_12'] . "|" . $_REQUEST['safety_13'];
                $_REQUEST['repair_details'] = $_REQUEST['repair_1'] . "|" . $_REQUEST['repair_2'];
            }

            if (function_exists('tenantCustomProcessing')) {
                tenantCustomProcessing($_REQUEST['reptype']);
            }

            if (function_exists('tenantReportUsesMultiItemRows') && tenantReportUsesMultiItemRows($_REQUEST) && function_exists('puwerGetPrimaryResultFromRequest')) {
                $puwerPrimaryResult = puwerGetPrimaryResultFromRequest($_REQUEST);
                if ($puwerPrimaryResult !== null) {
                    $_REQUEST['result'] = $puwerPrimaryResult;
                }
            }

            $existingReportData = [];
            $existingReportStmt = $GLOBALS['con']->prepare("SELECT `reportdata` FROM `reportitems_temp` WHERE `repnumber`=? LIMIT 1");
            if ($existingReportStmt) {
                $existingReportStmt->bind_param('i', $_REQUEST['repnumber']);
                if ($existingReportStmt->execute()) {
                    $existingReportRes = $existingReportStmt->get_result();
                    $existingReportRow = mysqli_fetch_assoc($existingReportRes);
                    if (is_array($existingReportRow)) {
                        $existingReportData = enrepReportDataFromRow($existingReportRow);
                    }
                }
                $existingReportStmt->close();
            }

            $data = enrepReportRowDataFromRequest($_REQUEST, false, $existingReportData);

            $set_clause = implode(", ", array_map(function ($key) {
                return "`$key` = ?";
            }, array_keys($data)));

            $sql = "UPDATE `reportitems_temp` SET $set_clause WHERE `repnumber` = ?";
            $stmt = $GLOBALS['con']->prepare($sql) or die(mysqli_error($GLOBALS['con']));

            $types = '';
            $values = [];

            foreach ($data as $value) {
                if (is_int($value)) {
                    $types .= 'i';
                } elseif (is_float($value)) {
                    $types .= 'd';
                } else {
                    $types .= 's';
                }
                $values[] = $value;
            }

            $types .= 'i';
            $values[] = $_REQUEST['repnumber'];

            $stmt->bind_param($types, ...$values);
            $stmt->execute();

            if ($stmt->error) {
                echo "Error: " . $stmt->error;
                $stmt->close();
                break;
            }

            $stmt->close();
            echo "update_success";
            break;
    }
}

function getItemReportDetails($repnumber, $type)
{
    $stmt = $GLOBALS['con']->prepare("SELECT `reptype`,`insdate`,`repdate`,`olddate`,`nextDate` FROM `reportitems` WHERE `repnumber`=?") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $repnumber);
    $stmt->execute();
    $rc = $stmt->get_result();
    $stmt->close();
    $cd = mysqli_fetch_array($rc);
    if ($cd['olddate'] == "Not Known" || $cd['olddate'] == "" || $cd['olddate'] == "None Recorded" || $cd['olddate'] == "0") {
        $od = "Not Known";
    } else {
        $od = date('d-m-Y', $cd['olddate']);
    }

    switch ($type) {
        case "REPNO":
            return $cd['reptype'];
            break;
        case "EXAM_DATE":
            return date('d-m-Y', $cd['insdate']);
            break;
        case "EXAM_PREVDATE":
            return $od;
            break;
        case "EXAM_NEXTDATE":
            return date('d-m-Y', $cd['nextDate']);
            break;
        case "REPORT_DATE":
            return date('d-m-Y', $cd['repdate']);
            break;
        case "REPDATA":
            return
                $cd['reptype'] . "|" .
                date('d-m-Y', $cd['insdate']) . "|" .
                $od . "|" . date('d-m-Y', $cd['nextDate']) . "|" .
                date('d-m-Y', $cd['insdate']);
    }
}

function getSurveyorDetails($repnumber, $type)
{
    $stmt = $GLOBALS['con']->prepare("SELECT `esname` FROM `reportitems` WHERE `repnumber`=?") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $repnumber);
    $stmt->execute();
    $rc = $stmt->get_result();
    $stmt->close();
    $cd = mysqli_fetch_array($rc);
    $stmt2 = $GLOBALS['con']->prepare("SELECT `id`,`surname`,`forename`,`qual` FROM `surveyor` WHERE `id`=?") or die(mysqli_error($GLOBALS['con']));
    $stmt2->bind_param('i', $cd['esname']);
    $stmt2->execute();
    $sc = $stmt2->get_result();
    $stmt2->close();
    $sd = mysqli_fetch_array($sc);
    switch ($type) {
        case "SURVEYOR_NAME":
            return $sd['forename'] . " " . $sd['surname'];
            break;
        case "SURVEYOR_QUAL":
            return $sd['qual'];
            break;
        case "SURVEYOR_SIGNITURE":
            return $sd['id'];
            break;
        case "REPDATA":
            return $sd['forename'] . " " . $sd['surname'] . "|" . $sd['qual'] . "|" . $sd['id'];
            break;
    }
}


function getItemReportType($repnumber)
{
    $stmt = $GLOBALS['con']->prepare("SELECT `reptype` FROM `reportitems` WHERE `repnumber`=?") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $repnumber);
    $stmt->execute();
    $rc = $stmt->get_result();
    $stmt->close();

    $cd = mysqli_fetch_array($rc);
    return $cd['reptype'];
}

function getItemReportDesc($repnumber, $type)
{
    $stmt = $GLOBALS['con']->prepare("SELECT `reptype` FROM `reportitems` WHERE `repnumber`=?") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $repnumber);
    $stmt->execute();
    $rc = $stmt->get_result();
    $cd = mysqli_fetch_array($rc);
    $rep = $cd['reptype'];
    if (!empty($rep)) {
        $stmt = $GLOBALS['master']->prepare("SELECT * FROM  " . $GLOBALS['path'] . ".dd_formtypes WHERE `formnumber`=" . $rep);
        $stmt->execute();
        $rx = $stmt->get_result();
        $stmt->close();
        $cnum = mysqli_num_rows($rx);
        if ($cnum == 0) {
            $stmt2 = $GLOBALS['con']->prepare("SELECT * FROM  dd_formtypes WHERE `formnumber`=" . $rep);
            $stmt2->execute();
            $rx2 = $stmt2->get_result();
            $stmt2->close();
            $cx = mysqli_fetch_array($rx2);
        } else {
            $cx = mysqli_fetch_array($rx);
        }

        if ($type == "formtype") {
            return $cx['formtype'];
        }
        if ($type == "regs") {
            return $cx['regs'];
        }
    }
}

function getReportDesc($repnumber, $type)
{
    $stmt = $GLOBALS['master']->prepare("SELECT * FROM  " . $GLOBALS['path'] . ".dd_formtypes WHERE `formnumber`=" . $repnumber);
    $stmt->execute();
    $rx = $stmt->get_result();
    $stmt->close();
    $cnum = mysqli_num_rows($rx);
    if ($cnum == 0) {
        $stmt2 = $GLOBALS['con']->prepare("SELECT * FROM  dd_formtypes WHERE `formnumber`=" . $repnumber);
        $stmt2->execute();
        $rx2 = $stmt2->get_result();
        $stmt2->close();
        $cx = mysqli_fetch_array($rx2);
    } else {
        $cx = mysqli_fetch_array($rx);
    }
    if ($type == "formtype") {
        return $cx['formtype'];
    }
    if ($type == "formtypedesc") {
        if ($cx['formtype'] == $cx['description']) {
            return $cx['formtype'];
        } else {
            return $cx['formtype'] . " <small>(" . $cx['description'] . ")</small>";
        }
    }
    if ($type == "desc") {
        return $cx['description'];
    }
    if ($type == "regs") {
        return $cx['regs'];
    }
}

function getSurveyorName($esname)
{
    $stmt = $GLOBALS['con']->prepare("SELECT `surname`,`forename` FROM `surveyor` WHERE `esname`=?") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $esname);
    $stmt->execute();
    $rc = $stmt->get_result();
    $stmt->close();
    $cd = mysqli_fetch_array($rc);
    return $cd['forename'] . " " . $cd['surname'];
}

function getSurveyorName2($esname)
{
    $stmt = $GLOBALS['con']->prepare("SELECT `surname`,`forename` FROM `surveyor` WHERE `id`=?") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $esname);
    $stmt->execute();
    $rc = $stmt->get_result();
    $stmt->close();
    $cd = mysqli_fetch_array($rc);
    return $cd['forename'] . " " . $cd['surname'];
}

function getItemName($itemnumber)
{
    $stmt = $GLOBALS['con']->prepare("SELECT `desc` FROM `itemdetails` WHERE `itemnumber`=?") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $itemnumber);
    $stmt->execute();
    $rc = $stmt->get_result();
    $stmt->close();
    $cd = mysqli_fetch_array($rc);
    return $cd['desc'];
}

function getItemOwner($itemnumber)
{
    $stmt = $GLOBALS['con']->prepare("SELECT `clientnumber` FROM `itemdetails` WHERE `itemnumber`=?") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $itemnumber);
    $stmt->execute();
    $rc = $stmt->get_result();
    $stmt->close();
    $cd = mysqli_fetch_array($rc);
    $stmt = $GLOBALS['con']->prepare("SELECT `clientname`,`contract_number` FROM `clientdetails` WHERE `clientnumber`=?") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $cd['clientnumber']);
    $stmt->execute();
    $la = $stmt->get_result();
    $stmt->close();
    $le = mysqli_fetch_array($la);
    return $le['clientname'] . "|" . $le['contract_number'];
}

function getItemData($itemnumber)
{
    //require_once('includes/connection.php');
    $stmt = $GLOBALS['con']->prepare("SELECT `itemnumber`,`DESC`,`serialnumber` FROM `itemdetails` WHERE `itemnumber`=?") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $itemnumber);
    $stmt->execute();
    $rc = $stmt->get_result();
    $stmt->close();
    $cd = mysqli_fetch_array($rc);
    return '
<tr>
<td><div class="checkbox"><label class="">
<div class="icheckbox_flat-blue checked" style="position: relative;">

<input type="checkbox" class="flat" checked="checked" style="position: absolute; opacity: 0;" name="items[]" id="ITEM-' . $cd['itemnumber'] . '" value="' . $cd['itemnumber'] . '">

</div>
</label></div></td>
<td>' . $cd['itemnumber'] . '</td><td>' . $cd['desc'] . '</td><td>' . $cd['serialnumber'] . '</td>
</tr>';
}

function getItemLastInsp($itemnumber)
{
    $stmt = $GLOBALS['con']->prepare("SELECT `insdate` FROM `reportitems` WHERE `itemnumber`=? ORDER BY `repitem` DESC LIMIT 1") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $itemnumber);
    $stmt->execute();
    $rc = $stmt->get_result();
    $stmt->close();
    $cd = mysqli_fetch_array($rc);
    if (!$cd['insdate']) {
        return "None Recorded";
    } else {
        return date('d-m-Y', $cd['insdate']);
    }
}

function getItemExamType($repnumber)
{
    $stmt = $GLOBALS['con']->prepare("SELECT `reptype` FROM `reportdetails` WHERE `repnumber`=?") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $repnumber);
    $stmt->execute();
    $rc = $stmt->get_result();
    $stmt->close();
    $cd = mysqli_fetch_array($rc);
    if ($cd['reptype'] == "") {
        return "none recorded";
    } else {
        return $cd['reptype'];
    }
}

function getItemInsp($repnumber, $type)
{

    $stmt = $GLOBALS['con']->prepare("SELECT `repnumber`,`esname`,`insdate` FROM `reportitems` WHERE `itemnumber`=? ORDER BY abs(repitem) DESC LIMIT 1 ") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $repnumber);
    $stmt->execute();
    $rc = $stmt->get_result();
    $stmt->close();
    $cd = mysqli_fetch_array($rc);
    if (!is_array($cd) || ($cd['repnumber'] ?? '') == "") {
        return "0";
    } else {
        $stmt = $GLOBALS['con']->prepare("SELECT * FROM `surveyor` WHERE `id`=? ") or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('i', $cd['esname']);
        $stmt->execute();
        $lc = $stmt->get_result();
        $stmt->close();
        $ld = mysqli_fetch_array($lc);

        if ($type == "name") {
            return $ld['forename'] . ' ' . $ld['surname'] . " on " . date('d-m-Y', $cd['insdate']);
        }
        if ($type == "full") {
            //return '<tr><td>'.$cd['ITEMNUMBER'].'</td><td>'.$cd['DESC'].'</td><td>'.$cd['SERIALNUMBER'].'</td></tr>';	
        }
    }
}


function getItemReportCount($repnumber)
{
    $stmt = $GLOBALS['con']->prepare("SELECT `repitem` FROM `reportitems` WHERE `repnumber`=?") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $repnumber);
    $stmt->execute();
    $rcx = $stmt->get_result();
    $data = mysqli_num_rows($rcx);
    if ($data > 1) {
        return "multi";
    } else {
        return "single";
    }
}

function getItemDetailed($repnumber, $itemnumber)
{


    $stmt = $GLOBALS['con']->prepare("SELECT * FROM `itemdetails` WHERE `itemnumber` = ?")  or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $itemnumber);
    $stmt->execute();
    $rc = $stmt->get_result();
    $cd = $rc->fetch_assoc();
    $stmt->close();

    if (!$cd) {
        return json_encode([
            'success' => false,
            'message' => 'Item not found',
            'itemnumber' => $itemnumber
        ]);
    }

    $cd['location_name'] = getItemLocation($itemnumber, 'name');
    $cd['inspector_name'] = getItemInsp($repnumber, 'name');

    return json_encode([
        'success' => true,
        'item' => $cd
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}


if (!function_exists('autofillLabelForField')) {
    function autofillLabelForField(string $fieldName): string
    {
        $labels = [
            'adefect' => 'A Defect',
            'bdefect' => 'B Defect',
            'obs' => 'Observations',
            'pnareason' => 'PNA Reason',
        ];

        if (isset($labels[$fieldName])) {
            return $labels[$fieldName];
        }

        $label = preg_replace('/[_\-]+/', ' ', $fieldName);
        $label = preg_replace('/(?<!^)([A-Z])/', ' $1', (string)$label);
        $label = preg_replace('/\s+/', ' ', trim((string)$label));

        return $label !== '' ? ucwords($label) : 'Text';
    }
}

if (!function_exists('autofillJsArg')) {
    function autofillJsArg(string $value): string
    {
        return htmlspecialchars(json_encode($value, JSON_UNESCAPED_SLASHES), ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('autofillAllowedGroups')) {
    function autofillAllowedGroups(): array
    {
        return [
            'adefect',
            'bdefect',
            'obs',
            'pnareason',
        ];
    }
}

if (!function_exists('formApplyDefaultText')) {
    function formDefaultTextData($formNumber): array
    {
        static $defaultTextCache = [];

        if (!isset($GLOBALS['con']) || !($GLOBALS['con'] instanceof mysqli)) {
            return [];
        }

        $formNumber = preg_replace('/\D+/', '', (string)$formNumber);
        if ($formNumber === '') {
            return [];
        }

        if (array_key_exists($formNumber, $defaultTextCache)) {
            return $defaultTextCache[$formNumber];
        }

        $formNumberWithPrefix = 'F' . $formNumber;
        $stmt = $GLOBALS['con']->prepare("SELECT `data` FROM `default_text` WHERE `formNumber` = ? OR `formNumber` = ? LIMIT 1");
        if (!$stmt) {
            $defaultTextCache[$formNumber] = [];
            return [];
        }

        $stmt->bind_param('ss', $formNumber, $formNumberWithPrefix);
        $stmt->execute();
        $res = $stmt->get_result();
        $row = $res ? $res->fetch_assoc() : null;
        $stmt->close();

        $defaults = [];
        if (!empty($row['data'])) {
            $decoded = json_decode((string)$row['data'], true);
            if (is_array($decoded)) {
                $defaults = $decoded;
            }
        }

        $defaultTextCache[$formNumber] = $defaults;

        return $defaults;
    }

    function formApplyDefaultText($formNumber, $currentValues = []): array
    {
        $values = is_array($currentValues) ? $currentValues : [];
        $defaults = formDefaultTextData($formNumber);

        foreach ($defaults as $field => $defaultValue) {
            $field = (string)$field;
            if ($field === '' || $field === 'formNumber') {
                continue;
            }

            if (!preg_match('/^[A-Za-z0-9_\-]+$/', $field)) {
                continue;
            }

            if (empty($values[$field])) {
                $values[$field] = (string)$defaultValue;
            }
        }

        return $values;
    }
}

if (!function_exists('autofill')) {
    function autofill(string $fieldName, string $table = 'phrases', string $group = '', $rows = 8): string
    {
        global $cx, $rd, $d;

        $fieldName = preg_replace('/[^A-Za-z0-9_\-]/', '', $fieldName);
        $table = preg_replace('/[^A-Za-z0-9_\-]/', '', $table);
        $group = preg_replace('/[^A-Za-z0-9_\-]/', '', $group);
        if ($group !== '' && !in_array($group, autofillAllowedGroups(), true)) {
            $group = '';
        }

        $rows = is_numeric($rows) ? (int)$rows : 8;
        $rows = max(2, min(20, $rows));

        if ($fieldName === '') {
            return '';
        }

        $formId = 'F' . (string)($d[2] ?? '');
        $rd = formApplyDefaultText($_REQUEST['formnumber'] ?? '', isset($rd) && is_array($rd) ? $rd : []);
        $value = '';
        if (isset($rd) && is_array($rd) && array_key_exists($fieldName, $rd)) {
            $value = (string)$rd[$fieldName];
        }

        $isAdmin = (string)($_SESSION['usertype'] ?? '') === 'admins';
        $fieldEsc = htmlspecialchars($fieldName, ENT_QUOTES, 'UTF-8');
        $valueEsc = htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
        $formArg = autofillJsArg($formId);
        $fieldArg = autofillJsArg($fieldName);
        $tableArg = autofillJsArg($table);
        $groupArg = autofillJsArg($group);

        $html = '<div class="col-md-12 d-flex">';
        $html .= '<textarea class="form-control form-control-sm" type="text" name="' . $fieldEsc . '" id="' . $fieldEsc . '" rows="' . $rows . '" data-original-value="' . $valueEsc . '">' . $valueEsc . '</textarea>';
        $html .= '<div class="d-flex flex-column">';

        $html .= '<button type="button" class="btn btn-secondary  mb-1" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Clear Field" onClick="clearbox(' . $fieldArg . ')">';
        $html .= '<i class="fad fa-eraser"></i></button>';

        if ($isAdmin) {
            $html .= '<button type="button" class="btn btn-info  mb-1" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="View List" onClick="autofill(' . $formArg . ',' . $fieldArg . ',' . $tableArg . ',' . $groupArg . ')">';
            $html .= '<i class="fad fa-edit"></i></button>';
            $html .= '<button type="button" class="btn btn-success  mb-1" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Save field as new entry" onClick="savebox(' . $fieldArg . ',' . $tableArg . ',' . $groupArg . ')">';
            $html .= '<i class="fad fa-save"></i></button>';
        } else {
            $html .= '<button type="button" class="btn btn-success  mb-1" onClick="javascript:void(0)"></button>';
            $html .= '<button type="button" class="btn btn-info  mb-1" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="View List" onClick="autofill(' . $formArg . ',' . $fieldArg . ',' . $tableArg . ',' . $groupArg . ')">';
            $html .= '<i class="fad fa-edit"></i></button>';
        }

        $html .= '<button type="button" class="btn btn-danger btn-info-alt" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Reset Field" onClick="resetBox(' . $fieldArg . ')">';
        $html .= '<i class="fad fa-refresh"></i></button>';

        $html .= '</div></div>';

        return $html;
    }
}


function listPlant($c, $n, $t)
{
    switch ($t) {
        default:
            break;

        case "select":
            //$sql="SELECT * FROM `reporting_master`.`dd_plant` UNION ALL SELECT * FROM `reporting`.`dd_plant`  ORDER BY `code` ASC";
            $stmt = $GLOBALS['master']->prepare("SELECT * FROM " . $GLOBALS['path'] . ".dd_plant UNION ALL SELECT * FROM `dd_plant`  ORDER BY `code` ASC") or die(mysqli_error($GLOBALS['master']));
            $stmt->execute();
            $cc = $stmt->get_result();
            $stmt->close();
            while ($pd = mysqli_fetch_array($cc)) {
                $ca[] = $pd;
            }

            $ret = '<select class="form-control form-control-sm autocomplete" id="' . $n . '" name="' . $n . '">';
            if (mysqli_num_rows($cc) != 0) {
                foreach ($ca as $px) {
                    if ($c == $px['code']) {
                        $s = "SELECTED";
                    } else {
                        $s = "";
                    }
                    $ret .= '<option value="' . $px['code'] . '" title="' . $px['description'] . '" ' . $s . '>' . $px['code'] . '</option>'; //.PHP_EOL;
                }
            }
            $ret .= '</select>';
            return ($ret);
            break;

        case "name":
            $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();
            while ($pd = mysqli_fetch_array($cc)) {
                $ca[] = $pd;
            }

            $ret = '<select class="form-control form-control-sm" id="' . $n . '" name="' . $n . '">';
            foreach ($ca as $px) {
                if ($c == $px['code']) {
                    $s = "SELECTED";
                } else {
                    $s = "";
                }
                $ret .= '<option value="' . $px['description'] . '" title="' . $px['code'] . '" ' . $s . '>' . $px['description'] . '</option>'; //.PHP_EOL;
            }
            $ret .= '</select>';
            return ($ret);
            break;
    }
}

function getSites($s, $c)
{
    $stmt = $GLOBALS['con']->prepare("SELECT `locnumber`,`locname`,`postcode` FROM `locations` WHERE `clientnumber`=?") or die($error = mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $s);
    $stmt->execute();
    $res = $stmt->get_result();
    $stmt->close();
    $ret = '<select data-mdb-select-init class="form-control form-control-sm" id="siteList" name="siteList" data-mdb-placeholder="Filter by location" data-mdb-filter="true">';
    $ret .= '<option value=""></option>';
    $ret .= '<option value="" onclick="clearSearch()">RESET ALL FILTERS</option>';
    $ret .= '<optgroup label="Available Locations">';
    while ($d = mysqli_fetch_array($res)) {
        if ($c == $d['locnumber']) {
            $s = "SELECTED";
        } else {
            $s = "";
        }
        $ret .= '<option value="' . $d['postcode'] . '" ' . $s . '>' . strtoupper($d['postcode']) . ' -' . $d['locname'] . '</option>';
    }
    $ret .= '</optgroup>';
    $ret .= '</select>';
    return $ret;
}


function getSites2($s, $c)
{
    $stmt = $GLOBALS['con']->prepare("SELECT `locnumber`,`locname`,`postcode`  FROM `locations` WHERE `clientnumber`=?") or die($error = mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $s);
    $stmt->execute();
    $res = $stmt->get_result();
    $stmt->close();
    $ret = '<select data-mdb-select-init class="form-control" id="siteList" name="siteList" data=mdb-placeholder="Select site" data-mdb-filter="true">';
    $ret .= '<option value="">Select site</option>';
    $ret .= '<optgroup label="Active Sites">';
    while ($d = mysqli_fetch_array($res)) {
        if ($c == $d['locnumber']) {
            $s = "SELECTED";
        } else {
            $s = "";
        }
        $ret .= '<option value="' . $d['locnumber'] . '" ' . $s . '>' . $d['postcode'] . '-' . $d['locname'] . '</option>';
    }
    $ret .= '</optgroup>';
    $ret .= '</select>';
    return $ret;
}

function listSurveyor($c, $n, $t)
{
    if (!empty($_SESSION['contractorNumber'])) {
        $filter = "AND `contractor`='" . $_SESSION['contractorNumber'] . "'";
    }
    switch ($t) {
        default:
            break;

        case "select":
            $ca = array();
            $stmt = $GLOBALS['con']->prepare("SELECT `id`,`esname`,`forename`,`surname` FROM `surveyor` WHERE `statuslive`='1' $filter ORDER BY `forename` ASC") or die(mysqli_error($GLOBALS['con']));
            $stmt->execute();
            $cc = $stmt->get_result();
            $stmt->close();
            while ($pd = mysqli_fetch_array($cc)) {
                $ca[] = $pd;
            }
            $ret = '<select class="form-control form-control-sm" data-mdb-select-init data-mdb-filter="true" id="' . $n . '" name="' . $n . '">';
            $ret .= '<option value="NULL">Select primary Surveyor</option>'; //.PHP_EOL;	
            foreach ($ca as $px) {
                $name = $px['forename'] . ' ' . $px['surname'];
                if ($c == $px['id']) {
                    $s = "SELECTED";
                } else {
                    $s = "";
                }
                $ret .= '<option value="' . $px['id'] . '" ' . $s . '>' . $name . '</option>'; //.PHP_EOL;
            }
            $ret .= '</select>';
            return ($ret);
            break;

        case "name":
            $stmt = $GLOBALS['con']->prepare("SELECT `id`,`esname`,`forename`,`surname` FROM `surveyor` WHERE `statuslive`='1'  ORDER BY `forename` ASC") or die(mysqli_error($GLOBALS['con']));
            $stmt->execute();
            $cc = $stmt->get_result();
            $stmt->close();
            while ($pd = mysqli_fetch_array($cc)) {
                $ca[] = $pd;
            }
            $ret = '<select class="form-control form-control-sm" id="' . $n . '" name="' . $n . '">';
            $ret .= '<option value="NULL">Select Surveyor</option>'; //.PHP_EOL;	
            foreach ($ca as $px) {
                $name = $px['forename'] . ' ' . $px['surname'];
                if ($c == $name) {
                    $s = "SELECTED";
                } else {
                    $s = "";
                }
                $ret .= '<option value="' . $name . '" ' . $s . '>' . $name . '</option>'; //.PHP_EOL;
            }
            $ret .= '</select>';
            return ($ret);
            break;

        case "ajax":
            $stmt = $GLOBALS['con']->prepare("SELECT `id`,`esname`,`forename`,`surname` FROM `surveyor` WHERE `statuslive`='1'  ORDER BY `forename` ASC") or die(mysqli_error($GLOBALS['con']));
            $stmt->execute();
            $cc = $stmt->get_result();
            $stmt->close();
            $cnt = mysqli_num_rows($cc);
            while ($pd = mysqli_fetch_array($cc)) {
                $ca[] = $pd;
            }

            $co = 0;
            $ret = 'var clientList = [';
            foreach ($ca as $px) {
                $name = $px['forename'] . ' ' . $px['surname'];
                $name = str_replace('"', '', $name);
                $name = str_replace('\&', 'and', $name);
                $co++;
                if ($co == $cnt) {
                    $s = "";
                } else {
                    $s = ",";
                }
                $ret .= '{"value":"' . $name . '","name":"' . $px['id'] . '"}' . $s . PHP_EOL;
            }
            $ret .= '];';
            return ($ret);
            break;
    }
}

function checkAuto($client)
{
    $stmt = $GLOBALS['con']->prepare("SELECT * FROM `address_book` WHERE `clientnumber`='" . $client . "' AND `auto`='1' ") or die(mysqli_error($GLOBALS['con']));
    $stmt->execute();
    $cr = $stmt->get_result();
    $stmt->close();
    $c = mysqli_num_rows($cr);
    if ($c == 0) {
        return '<div class="alert alert-warning text-center alert-dismissible fade show"><span class="lead">You have no default recipients.</span><br><a class="btn btn-dark btn-sm" href="index.php?t=includes/master&p=client_addressbook.php&clientnumber=' . $client . '">Assign Defaults</a> <a class="btn btn-danger btn-sm" href="javascript:void(0)" data-dismiss="alert">No thanks</a></div>';
    } else {
    }
}

function checkTemp($c)
{
    $stmt = $GLOBALS['con']->prepare("SELECT `repitem` FROM `reportitems_temp` WHERE `clientnumber`='" . $c . "'") or die(mysqli_error($GLOBALS['con']));
    $stmt->execute();
    $cc = $stmt->get_result();
    $stmt->close();
    $cnt = mysqli_num_rows($cc);
    if ($cnt > 0) {
        return "1";
    } else {
    }
}

function getFreq($c)
{
    $stmt = $GLOBALS['con']->prepare("SELECT * FROM `dd_plant` WHERE `code`='" . $c . "' ") or die($e = mysqli_error($GLOBALS['con']));
    $stmt->execute();
    $cr = $stmt->get_result();
    $stmt->close();
    $pd = mysqli_fetch_array($cr);
    return $pd['frequency'] . $e;
}
