<?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 (empty($split)) {
    $split = '';
}
if (isset($_REQUEST['FUNCTION'])) {
    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);
            echo date('d-m-Y', $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'];
            }

            $e = '';
            $formClass = '';
            $repnumber = strtotime('now');
            if ($_REQUEST['olddate'] == "Not Known") {
                $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']);
            }


            $olddate = strtotime($_REQUEST['olddate']);
            $insdate = strtotime($_REQUEST['insdate']);
            $nextDate = strtotime($_REQUEST['nextDate']);

            // Prepare an array of column names and corresponding values
            $data = [
                'repnumberold' => $_REQUEST['oldnumber'],
                'olddate' => $olddate,
                'insdate' => $insdate,
                'nextDate' => $nextDate,
                'delivery' => 0,
                'clientnumber' => $_REQUEST['clientnumber'],
                'itemnumber' => $_REQUEST['itemnumber'],
                'esname' => $_REQUEST['surveyor'],
                'adefect' => $_REQUEST['adefect'],
                'bdefect' => $_REQUEST['bdefect'],
                'obs' => $_REQUEST['obs'],
                'pnareason' => $_REQUEST['pnareason'],
                'partialReason' => $_REQUEST['partialReason'],
                'ffcomments' => $_REQUEST['ffcomments'],
                'code' => $_REQUEST['code'],
                'viewed' => $_REQUEST['viewed'],
                'history' => $_REQUEST['history'],
                'changeScheme' => $_REQUEST['changeScheme'],
                'resultOfExam' => $_REQUEST['resultOfExam'],
                'lastReportSeen' => $_REQUEST['lastReportSeen'],
                'examType' => $_REQUEST['examType'],
                'partsCovered' => $_REQUEST['partsCovered'],
                'lease_or_hire' => $_REQUEST['lease_or_hire'],
                'partsInaccessible' => $_REQUEST['partsInaccessible'],
                'conditionInternal' => $_REQUEST['conditionInternal'],
                'conditionExternal' => $_REQUEST['conditionExternal'],
                'conditionFittings' => $_REQUEST['conditionFittings'],
                'protectiveDevices' => $_REQUEST['protectiveDevices'],
                '9b1' => $_REQUEST['9b1'],
                '9b2' => $_REQUEST['9b2'],
                '9b3' => $_REQUEST['9b3'],
                'processConditions' => $_REQUEST['processConditions'],
                'class' => $_REQUEST['class'],
                'ebond' => $_REQUEST['ebond'],
                'ires' => $_REQUEST['ires'],
                'volts' => $_REQUEST['volts'],
                'nature' => $_REQUEST['nature'],
                'test_procedure' => $_REQUEST['test_procedure'],
                'process_conditions' => $_REQUEST['process_conditions'],
                'effective' => $_REQUEST['effective'],
                'particulars' => $_REQUEST['particulars'],
                'other_comments' => $_REQUEST['other_comments'],
                'usage_comments' => $_REQUEST['usage_comments'],
                'noise' => $_REQUEST['noise'],
                'intended_performance' => $_REQUEST['intended_performance'],
                'achieving_perfomance' => $_REQUEST['achieving_perfomance'],
                'repair_details' => $_REQUEST['repair_details'],
                'rack' => $_REQUEST['rack'],
                'rackRun' => $_REQUEST['rackRun'],
                'beam' => $_REQUEST['beam'],
                'accessories' => $_REQUEST['accessories'],
                'handling' => $_REQUEST['handling'],
                'stability' => $_REQUEST['stability'],
                'clutch' => $_REQUEST['clutch'],
                'safety' => $_REQUEST['safety'],
                'frequency' => $_REQUEST['frequency'],
                'reptype' => $_REQUEST['reptype'],
                'result' => $_REQUEST['result'],
            ];

            // Dynamically build the query with placeholders for the values
            $columns = implode(", ", array_keys($data)); // Join column names
            $placeholders = implode(", ", array_fill(0, count($data), '?')); // Create the same number of placeholders

            // Complete SQL Query (including repnumber and NULL as the first value)
            $sql = "INSERT INTO `reportitems_temp` (repitem, repnumber, $columns) VALUES (NULL, '$repnumber', $placeholders)";

            // Prepare the statement
            $stmt = $GLOBALS['con']->prepare($sql) or die(mysqli_error($GLOBALS['con']));

            // Dynamically build the bind_param type string
            $types = '';
            $values = [];

            foreach ($data as $key => $value) {
                if (is_int($value)) {
                    $types .= 'i'; // Integer
                } elseif (is_float($value)) {
                    $types .= 'd'; // Double/Decimal
                } else {
                    $types .= 's'; // String
                }
                $values[] = $value; // Collect the values in the same order
            }

            // Use call_user_func_array to bind the parameters dynamically
            $stmt->bind_param($types, ...$values);

            // Execute the statement and check for errors
            $stmt->execute();
            if ($stmt->error) {
                echo "Error: " . $stmt->error;
            } else {

                $insertID = mysqli_insert_id($GLOBALS['con']);
            }

            // Close the statement
            $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 = '';
            $repnumber = strtotime('now');
            if ($_REQUEST['olddate'] == "Not Known") {
                $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']);
            }


            $olddate = strtotime($_REQUEST['olddate']);
            $insdate = strtotime($_REQUEST['insdate']);
            $nextDate = strtotime($_REQUEST['nextDate']);

            // Prepare an array of column names and corresponding values
            $data = [
                'repnumberold' => $_REQUEST['oldnumber'],
                'olddate' => $olddate,
                'insdate' => $insdate,
                'nextDate' => $nextDate,
                'delivery' => 0,
                'clientnumber' => $_REQUEST['clientnumber'],
                'itemnumber' => $_REQUEST['itemnumber'],
                'esname' => $_REQUEST['surveyor'],
                'adefect' => $_REQUEST['adefect'],
                'bdefect' => $_REQUEST['bdefect'],
                'obs' => $_REQUEST['obs'],
                'pnareason' => $_REQUEST['pnareason'],
                'partialReason' => $_REQUEST['partialReason'],
                'ffcomments' => $_REQUEST['ffcomments'],
                'code' => $_REQUEST['code'],
                'viewed' => $_REQUEST['viewed'],
                'history' => $_REQUEST['history'],
                'changeScheme' => $_REQUEST['changeScheme'],
                'resultOfExam' => $_REQUEST['resultOfExam'],
                'lastReportSeen' => $_REQUEST['lastReportSeen'],
                'examType' => $_REQUEST['examType'],
                'partsCovered' => $_REQUEST['partsCovered'],
                'lease_or_hire' => $_REQUEST['lease_or_hire'],
                'partsInaccessible' => $_REQUEST['partsInaccessible'],
                'conditionInternal' => $_REQUEST['conditionInternal'],
                'conditionExternal' => $_REQUEST['conditionExternal'],
                'conditionFittings' => $_REQUEST['conditionFittings'],
                'protectiveDevices' => $_REQUEST['protectiveDevices'],
                '9b1' => $_REQUEST['9b1'],
                '9b2' => $_REQUEST['9b2'],
                '9b3' => $_REQUEST['9b3'],
                'processConditions' => $_REQUEST['processConditions'],
                'class' => $_REQUEST['class'],
                'ebond' => $_REQUEST['ebond'],
                'ires' => $_REQUEST['ires'],
                'volts' => $_REQUEST['volts'],
                'nature' => $_REQUEST['nature'],
                'test_procedure' => $_REQUEST['test_procedure'],
                'process_conditions' => $_REQUEST['process_conditions'],
                'effective' => $_REQUEST['effective'],
                'particulars' => $_REQUEST['particulars'],
                'other_comments' => $_REQUEST['other_comments'],
                'usage_comments' => $_REQUEST['usage_comments'],
                'noise' => $_REQUEST['noise'],
                'intended_performance' => $_REQUEST['intended_performance'],
                'achieving_perfomance' => $_REQUEST['achieving_perfomance'],
                'repair_details' => $_REQUEST['repair_details'],
                'rack' => $_REQUEST['rack'],
                'rackRun' => $_REQUEST['rackRun'],
                'beam' => $_REQUEST['beam'],
                'accessories' => $_REQUEST['accessories'],
                'handling' => $_REQUEST['handling'],
                'stability' => $_REQUEST['stability'],
                'clutch' => $_REQUEST['clutch'],
                'safety' => $_REQUEST['safety'],
                'frequency' => $_REQUEST['frequency'],
                'reptype' => $_REQUEST['reptype'],
                'result' => $_REQUEST['result'],
            ];

            // Dynamically build the query with placeholders for the values
            $columns = implode(", ", array_keys($data)); // Join column names
            $placeholders = implode(", ", array_fill(0, count($data), '?')); // Create the same number of placeholders

            // Complete SQL Query (including repnumber and NULL as the first value)
            $sql = "INSERT INTO `reportitems` (repitem, repnumber, $columns) VALUES (NULL, '$repnumber', $placeholders)";

            // Prepare the statement
            $stmt = $GLOBALS['con']->prepare($sql) or die(mysqli_error($GLOBALS['con']));

            // Dynamically build the bind_param type string
            $types = '';
            $values = [];

            foreach ($data as $key => $value) {
                if (is_int($value)) {
                    $types .= 'i'; // Integer
                } elseif (is_float($value)) {
                    $types .= 'd'; // Double/Decimal
                } else {
                    $types .= 's'; // String
                }
                $values[] = $value; // Collect the values in the same order
            }

            // Use call_user_func_array to bind the parameters dynamically
            $stmt->bind_param($types, ...$values);

            // Execute the statement and check for errors
            $stmt->execute();
            if ($stmt->error) {
                echo "Error: " . $stmt->error;
            } else {

                $insertID = mysqli_insert_id($GLOBALS['con']);
            }

            // Close the statement
            $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();
            $stmt->close();
            //genSchedule($_REQUEST['clientnumber']);

            if ($_REQUEST['formClass'] == "lev_initial") {
                foreach (range(1, $_REQUEST['pointRows']) as $r) {
                    if ($_REQUEST['point_number' . $r] !== "") {
                        $stmt = $GLOBALS['con']->prepare("INSERT INTO `lev_results_initial` VALUES(NULL,?,?,?,?,?,?,?,?)") or die(mysqli_error($GLOBALS['con']));
                        $stmt->bind_param('issssssi', $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']);
                        $stmt->execute();
                        $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();
                        $stmt->close();
                    }
                }
            }
            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;

                    // Construct the SQL query for each card (plant item)
                    $sql = "
                INSERT INTO reportitems (
                    repnumber, olddate, insdate, nextDate, clientnumber, itemnumber, 
                    test_procedure, process_conditions, effective, result, viewed, 
                    esname, frequency, obs
                ) VALUES (
                    UNIX_TIMESTAMP(), '$insDate', '$insDate', '$nextDate', 
                    '$clientNumber', '$itemnumber', '$testEquipment', 
                    '$testApplied', '$testValueApplied', '$result', 
                    '$uniqueIdentifier', '$surveyor', '$frequency', '$observationDetail'
                )
            ";

                    // Execute the query
                    if (!mysqli_query($con, $sql)) {
                        die("Database insert failed: " . mysqli_error($con));
                    }
                }

                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'];
            }

            $e = '';
            $formClass = '';
            $repnumber = strtotime('now');
            if ($_REQUEST['olddate'] == "Not Known") {
                $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']);
            }

            $stmt = $GLOBALS['con']->prepare("INSERT INTO `reportitems` VALUES(NULL,'" . $repnumber . "',?,?,?,?,'','',?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)") or die(mysqli_error($GLOBALS['con']));
            $stmt->bind_param(
                'isiiissssssssssssssssssssssssssssssssssssssssssssssssssss',
                $_REQUEST['oldnumber'],
                $olddate,
                strtotime($_REQUEST['insdate']),
                strtotime($_REQUEST['nextDate']),
                $_REQUEST['clientnumber'],
                $_REQUEST['itemnumber'],

                $_REQUEST['surveyor'],
                $_REQUEST['adefect'],
                $_REQUEST['bdefect'],
                $_REQUEST['obs'],
                $_REQUEST['pnareason'],

                $_REQUEST['partialReason'],
                $_REQUEST['ffcomments'],
                $_REQUEST['code'],
                $_REQUEST['viewed'],
                $_REQUEST['history'],

                $_REQUEST['changeScheme'],
                $_REQUEST['resultOfExam'],
                $_REQUEST['lastReportSeen'],
                $_REQUEST['examType'],
                $_REQUEST['partsCovered'],

                $_REQUEST['lease_or_hire'],

                $_REQUEST['partsInaccessible'],
                $_REQUEST['conditionInternal'],
                $_REQUEST['conditionExternal'],
                $_REQUEST['conditionFittings'],
                $_REQUEST['protectiveDevices'],

                $_REQUEST['9b1'],
                $_REQUEST['9b2'],
                $_REQUEST['9b3'],
                $_REQUEST['processConditions'],
                $_REQUEST['class'],

                $_REQUEST['ebond'],
                $_REQUEST['ires'],
                $_REQUEST['volts'],
                $_REQUEST['nature'],
                $_REQUEST['test_procedure'],

                $_REQUEST['process_conditions'],
                $_REQUEST['effective'],
                $_REQUEST['particulars'],
                $_REQUEST['other_comments'],
                $_REQUEST['usage_comments'],

                $_REQUEST['noise'],
                $_REQUEST['intended_performance'],
                $_REQUEST['achieving_perfomance'],
                $_REQUEST['repair_details'],
                $_REQUEST['rack'],

                $_REQUEST['rackRun'],
                $_REQUEST['beam'],
                $_REQUEST['accessories'],
                $_REQUEST['handling'],
                $_REQUEST['stability'],

                $_REQUEST['clutch'],
                $_REQUEST['safety'],
                $_REQUEST['frequency'],
                $_REQUEST['reptype'],
                $_REQUEST['result']
            );
            $stmt->execute();
            echo $stmt->error;
            $insertID = mysqli_insert_id($GLOBALS['con']);
            $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();
            $stmt->close();
            //genSchedule($_REQUEST['clientnumber']);

            if ($_REQUEST['formClass'] == "lev_initial") {
                foreach (range(1, $_REQUEST['pointRows']) as $r) {
                    if ($_REQUEST['point_number' . $r] !== "") {
                        $stmt = $GLOBALS['con']->prepare("INSERT INTO `lev_results_initial` VALUES(NULL,?,?,?,?,?,?,?,?)") or die(mysqli_error($GLOBALS['con']));
                        $stmt->bind_param('issssssi', $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']);
                        $stmt->execute();
                        $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();
                        $stmt->close();
                    }
                }
            }
            $stmt = $GLOBALS['con']->prepare("DELETE FROM `reportitems_temp` WHERE `repnumber`='" . $_REQUEST['repnumber'] . "'") or die(mysqli_error($GLOBALS['con']));
            $stmt->execute();
            $stmt->close();
            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']);
            }

            $data = [
                'olddate' => strtotime($_REQUEST['olddate']),
                'insdate' => strtotime($_REQUEST['insdate']),
                'nextDate' => strtotime($_REQUEST['nextDate']),
                'itemnumber' => $_REQUEST['itemnumber'],
                'esname' => $_REQUEST['surveyor'],
                'adefect' => $_REQUEST['adefect'],
                'bdefect' => $_REQUEST['bdefect'],
                'obs' => $_REQUEST['obs'],
                'pnareason' => $_REQUEST['pnareason'],
                'partialReason' => $_REQUEST['partialReason'],
                'ffcomments' => $_REQUEST['ffcomments'],
                'code' => $_REQUEST['code'],
                'viewed' => $_REQUEST['viewed'],
                'history' => $_REQUEST['history'],
                'changeScheme' => $_REQUEST['changeScheme'],
                'resultOfExam' => $_REQUEST['resultOfExam'],
                'lastReportSeen' => $_REQUEST['lastReportSeen'],
                'examType' => $_REQUEST['examType'],
                'partsCovered' => $_REQUEST['partsCovered'],
                'lease_or_hire' => $_REQUEST['lease_or_hire'],
                'partsInaccessible' => $_REQUEST['partsInaccessible'],
                'conditionInternal' => $_REQUEST['conditionInternal'],
                'conditionExternal' => $_REQUEST['conditionExternal'],
                'conditionFittings' => $_REQUEST['conditionFittings'],
                'protectiveDevices' => $_REQUEST['protectiveDevices'],
                '9b1' => $_REQUEST['9b1'],
                '9b2' => $_REQUEST['9b2'],
                '9b3' => $_REQUEST['9b3'],
                'processConditions' => $_REQUEST['processConditions'],
                'class' => $_REQUEST['class'],
                'ebond' => $_REQUEST['ebond'],
                'ires' => $_REQUEST['ires'],
                'volts' => $_REQUEST['volts'],
                'nature' => $_REQUEST['nature'],
                'test_procedure' => $_REQUEST['test_procedure'],
                'process_conditions' => $_REQUEST['process_conditions'],
                'effective' => $_REQUEST['effective'],
                'particulars' => $_REQUEST['particulars'],
                'other_comments' => $_REQUEST['other_comments'],
                'usage_comments' => $_REQUEST['usage_comments'],
                'noise' => $_REQUEST['noise'],
                'intended_performance' => $_REQUEST['intended_performance'],
                'achieving_perfomance' => $_REQUEST['achieving_perfomance'],
                'repair_details' => $_REQUEST['repair_details'],
                'rack' => $_REQUEST['rack'],
                'rackRun' => $_REQUEST['rackRun'],
                'beam' => $_REQUEST['beam'],
                'accessories' => $_REQUEST['accessories'],
                'handling' => $_REQUEST['handling'],
                'stability' => $_REQUEST['stability'],
                'clutch' => $_REQUEST['clutch'],
                'safety' => $_REQUEST['safety'],
                'frequency' => $_REQUEST['frequency'],
                'reptype' => $_REQUEST['reptype'],
                'result' => $_REQUEST['result']
            ];

            // Build the SET clause dynamically
            $set_clause = implode(", ", array_map(function ($key) {
                return "`$key` = ?";
            }, array_keys($data)));

            // Prepare the SQL statement with the dynamic SET clause
            $sql = "UPDATE `reportitems` SET $set_clause WHERE `repnumber` = ?";

            // Prepare the statement
            $stmt = $GLOBALS['con']->prepare($sql) or die(mysqli_error($GLOBALS['con']));

            // Dynamically build the bind_param type string and values array
            $types = '';
            $values = [];

            foreach ($data as $key => $value) {
                if (is_int($value)) {
                    $types .= 'i'; // Integer
                } elseif (is_float($value)) {
                    $types .= 'd'; // Double/Decimal
                } else {
                    $types .= 's'; // String
                }
                $values[] = $value; // Collect the values in the same order
            }

            $types .= 'i';
            $values[] = $_REQUEST['repnumber']; // repnumber for the WHERE condition

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

            // Execute the statement and check for errors
            $stmt->execute();
            if ($stmt->error) {
                echo "Error: " . $stmt->error;
            }


            // Close the statement
            $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();
            $stmt->close();
            //genSchedule($_REQUEST['clientnumber']);


            //echo $_REQUEST['faceDuct_velocity2'];

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

                foreach (range(1, $_REQUEST['pointRows']) as $r) {
                    if ($_REQUEST['point_number' . $r] != "") {
                        $stmt = $GLOBALS['con']->prepare("INSERT INTO `lev_results_initial` 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'] . "'
                )") or die(mysqli_error($GLOBALS['con']));
                        $stmt->execute();
                        $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();
                $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();
                        $stmtP->close();
                    }
                }
            }



            echo "update_success" . $e;
            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']);
            }

            $data = [
                'olddate' => strtotime($_REQUEST['olddate']),
                'insdate' => strtotime($_REQUEST['insdate']),
                'nextDate' => strtotime($_REQUEST['nextDate']),
                'itemnumber' => $_REQUEST['itemnumber'],
                'esname' => $_REQUEST['surveyor'],
                'adefect' => $_REQUEST['adefect'],
                'bdefect' => $_REQUEST['bdefect'],
                'obs' => $_REQUEST['obs'],
                'pnareason' => $_REQUEST['pnareason'],
                'partialReason' => $_REQUEST['partialReason'],
                'ffcomments' => $_REQUEST['ffcomments'],
                'code' => $_REQUEST['code'],
                'viewed' => $_REQUEST['viewed'],
                'history' => $_REQUEST['history'],
                'changeScheme' => $_REQUEST['changeScheme'],
                'resultOfExam' => $_REQUEST['resultOfExam'],
                'lastReportSeen' => $_REQUEST['lastReportSeen'],
                'examType' => $_REQUEST['examType'],
                'partsCovered' => $_REQUEST['partsCovered'],
                'lease_or_hire' => $_REQUEST['lease_or_hire'],
                'partsInaccessible' => $_REQUEST['partsInaccessible'],
                'conditionInternal' => $_REQUEST['conditionInternal'],
                'conditionExternal' => $_REQUEST['conditionExternal'],
                'conditionFittings' => $_REQUEST['conditionFittings'],
                'protectiveDevices' => $_REQUEST['protectiveDevices'],
                '9b1' => $_REQUEST['9b1'],
                '9b2' => $_REQUEST['9b2'],
                '9b3' => $_REQUEST['9b3'],
                'processConditions' => $_REQUEST['processConditions'],
                'class' => $_REQUEST['class'],
                'ebond' => $_REQUEST['ebond'],
                'ires' => $_REQUEST['ires'],
                'volts' => $_REQUEST['volts'],
                'nature' => $_REQUEST['nature'],
                'test_procedure' => $_REQUEST['test_procedure'],
                'process_conditions' => $_REQUEST['process_conditions'],
                'effective' => $_REQUEST['effective'],
                'particulars' => $_REQUEST['particulars'],
                'other_comments' => $_REQUEST['other_comments'],
                'usage_comments' => $_REQUEST['usage_comments'],
                'noise' => $_REQUEST['noise'],
                'intended_performance' => $_REQUEST['intended_performance'],
                'achieving_perfomance' => $_REQUEST['achieving_perfomance'],
                'repair_details' => $_REQUEST['repair_details'],
                'rack' => $_REQUEST['rack'],
                'rackRun' => $_REQUEST['rackRun'],
                'beam' => $_REQUEST['beam'],
                'accessories' => $_REQUEST['accessories'],
                'handling' => $_REQUEST['handling'],
                'stability' => $_REQUEST['stability'],
                'clutch' => $_REQUEST['clutch'],
                'safety' => $_REQUEST['safety'],
                'frequency' => $_REQUEST['frequency'],
                'reptype' => $_REQUEST['reptype'],
                'result' => $_REQUEST['result']
            ];

            // Build the SET clause dynamically
            $set_clause = implode(", ", array_map(function ($key) {
                return "`$key` = ?";
            }, array_keys($data)));

            // Prepare the SQL statement with the dynamic SET clause
            $sql = "UPDATE `reportitems_temp` SET $set_clause WHERE `repnumber` = ?";

            // Prepare the statement
            $stmt = $GLOBALS['con']->prepare($sql) or die(mysqli_error($GLOBALS['con']));

            // Dynamically build the bind_param type string and values array
            $types = '';
            $values = [];

            foreach ($data as $key => $value) {
                if (is_int($value)) {
                    $types .= 'i'; // Integer
                } elseif (is_float($value)) {
                    $types .= 'd'; // Double/Decimal
                } else {
                    $types .= 's'; // String
                }
                $values[] = $value; // Collect the values in the same order
            }

            $types .= 'i';
            $values[] = $_REQUEST['repnumber']; // repnumber for the WHERE condition

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

            // Execute the statement and check for errors
            $stmt->execute();
            if ($stmt->error) {
                echo "Error: " . $stmt->error;
            }





            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['repdate']);
    }
}

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 ($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();
    $stmt->close();
    $cd = mysqli_fetch_array($rc);
    return $cd['desc'] . '|' . $cd['plantnumber'] . '|' . $cd['serialnumber'] . '|' . $cd['manf'] . '|' . $cd['dateofmanf'] . '|' . $cd['model'] . '|' . $cd['subloc'] . '|' . $cd['detailedloc'] . '|' . getItemLocation($itemnumber, 'name') . '|' . getItemInsp($repnumber, 'name') . '|' . $cd['swl'] . '|' . $cd['clientnumber'] . '|' . $cd['duedate'] . '|' . $cd['locnumber'] . '|' . $cd['cont_freq'] . '|' . $cd['make'] . '|' . $cd['code'];
}



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;
}