<?php

if (file_exists('../../' . $_REQUEST['tenant'] . '/config.php')) {
    require_once('../../' . $_REQUEST['tenant'] . '/config.php');
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}
require_once __DIR__ . '/../includes/master/form_functions.php';

function rapidrepInsertReportItem(array $values): void
{
    $columns = array_values(array_filter(enrepReportFixedFields(), static function ($column): bool {
        return $column !== 'repitem';
    }));
    $reportData = [];
    foreach (enrepReportDataFields() as $field) {
        if (array_key_exists($field, $values)) {
            $reportData[$field] = $values[$field];
        }
    }
    $columns[] = 'reportdata';
    $values['reportdata'] = enrepReportDataJson($reportData);

    $params = [];
    foreach ($columns as $column) {
        $params[] = array_key_exists($column, $values) ? $values[$column] : null;
    }

    $quotedColumns = '`' . implode('`,`', $columns) . '`';
    $placeholders = implode(',', array_fill(0, count($columns), '?'));
    $stmt = $GLOBALS['con']->prepare("INSERT INTO `reportitems` (" . $quotedColumns . ") VALUES (" . $placeholders . ")") or die(mysqli_error($GLOBALS['con']));
    $types = str_repeat('s', count($params));
    $refs = [&$types];
    foreach ($params as $idx => &$param) {
        $refs[] = &$param;
    }
    unset($param);
    call_user_func_array([$stmt, 'bind_param'], $refs);
    $stmt->execute();
    echo $stmt->error;
    $stmt->close();
}

$clientNumber = $_REQUEST['clientnumber'];
$_REQUEST['itemset'] = explode(',', $_REQUEST['itemset']);

foreach ($_REQUEST['itemset'] as $_REQUEST['item']) {
    $stmt = $GLOBALS['con']->prepare("SELECT * FROM `reportitems` WHERE `itemnumber`='" . $_REQUEST['item'] . "' AND `clientnumber`='" . $clientNumber . "' ORDER BY abs(insdate) DESC LIMIT 1") or die(mysqli_error($GLOBALS['con']));
    $stmt->execute();
    $get = $stmt->get_result();
    $stmt->close();
    $rnum = mysqli_num_rows($get);
    $cx = mysqli_fetch_array($get);
    if (is_array($cx)) {
        $cx = array_merge($cx, enrepReportDataFromRow($cx));
    }

    $stmt2 = $GLOBALS['con']->prepare("SELECT `clientnumber`,`code`,`linked` FROM `itemdetails` WHERE `itemnumber`=?") or die(mysqli_error($GLOBALS['con']));
    $stmt2->bind_param('i', $_REQUEST['item']);
    $stmt2->execute();
    $rc2 = $stmt2->get_result();
    $stmt2->close();
    $cx2 = mysqli_fetch_array($rc2);


    $chain = explode(":", $cx2['linked']);


    if (strtolower($cx['adefect']) == "none" && strtolower($cx['bdefect']) == "none" && strtolower($obs) == "none") {
        $cx['result'] = "PASS";
    }
    if (strtolower($cx['adefect']) != "none") {
        $cx['result'] = "URGENT";
    }
    if (strtolower($cx['bdefect']) != "none") {
        $cx['result'] = "DEFECTS";
    }
    if (strtolower($obs) != "none") {
        $cx['result'] = "OBS";
    }
    if ($_REQUEST['nir'] == "yes") {
        $cx['result'] = "PNA";
    }
    $e = '';
    $formClass = '';
    $repnumber = strtotime('now');
    if ($cx['olddate'] == "Not Known") {
        $olddate = "Not Known";
    } else {
        $olddate = strtotime($cx['olddate']);
    }

    if ($cx['repver'] == "800" || $cx['repver'] == "801") {
        $cx['partsInaccessible'] = $cx['parts_1'] . "|" . $cx['parts_2'] . "|" . $cx['parts_3'];
        $cx['adefect'] = $cx['adefect_1'] . "|" . $cx['adefect_2'] . "|" . $cx['adefect_3'];
    }

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

    $fn = mysqli_query($GLOBALS['con'], "SELECT * FROM `dd_plant` WHERE `code`='" . $cx2['code'] . "' ");
    $code = mysqli_fetch_array($fn);
    $freq = $code['frequency'] . ' months';
    $freqNo = $code['frequency'];

    $startDate = $_REQUEST['date'];
    $next = date('d-m-Y', strtotime('+' . $freq, strtotime($startDate)));

    $obs = $_REQUEST['obs'];

    if (strtolower($obs) == "none") {
        //echo "PASS LOADED".$obs;
        $stat = "PASS";
        $cx['result'] = "PASS";
        $obs = "None";
    } else { //echo "OBS LOADED".$obs;
        $stat = "OBS";
        $cx['result'] = "OBS";
        $obs = $obs;
    }

    $sd = strtotime($startDate);
    $dt = strtotime($_REQUEST['date']);
    $nx = strtotime($next);
    $nw = strtotime('now');

    $reportValues = $cx;
    $reportValues['repnumber'] = $repnumber;
    $reportValues['master_report_id'] = $cx['repnumber'] ?? null;
    $reportValues['repnumberold'] = $cx['repnumber'] ?? null;
    $reportValues['olddate'] = $cx['insdate'] ?? null;
    $reportValues['insdate'] = $dt;
    $reportValues['nextDate'] = $nx;
    $reportValues['repdate'] = $nw;
    $reportValues['delivery'] = 0;
    $reportValues['clientnumber'] = $clientNumber;
    $reportValues['itemnumber'] = $_REQUEST['item'];
    $reportValues['esname'] = $_REQUEST['surveyor'];
    $reportValues['obs'] = $obs;
    rapidrepInsertReportItem($reportValues);
    $insertID = mysqli_insert_id($GLOBALS['con']);

    $stmt = $GLOBALS['con']->prepare("UPDATE `itemdetails` SET `currdate`=?,`duedate`=?,`scheme_number_alt`=?,`history`=?, `lastReport`=? WHERE `itemnumber`=?") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('iisssi', $sd, $nx, $cx['scheme_number_alt'], $cx['history'], $cx['result'], $_REQUEST['item']);
    $stmt->execute();
    $stmt->close();

    if ($cx['formClass'] == "lev_initial") {
        foreach (range(1, $cx['pointRows']) as $r) {
            if ($cx['point_number' . $r] !== "") {
                $stmt = $GLOBALS['con']->prepare("INSERT INTO `lev_results_initial` VALUES('',?,?,?,?,?,?,?,?)") or die(mysqli_error($GLOBALS['con']));
                $stmt->bind_param('issssssi', $repnumber, $cx['point_number' . $r], $cx['point_detail' . $r], $cx['hoodDuct_size' . $r], $cx['faceDuct_velocity' . $r], $cx['static_pressure' . $r], $cx['volume_flow' . $r], $cx['itemnumber']);
                $stmt->execute();
                $stmt->close();
            }
        }
    }

    if ($cx['formClass'] == "lev_periodical") {
        foreach (range(1, $cx['pointRows']) as $r) {
            if ($cx['point_number' . $r] !== "") {
                $stmt = $GLOBALS['con']->prepare("INSERT INTO `lev_results` VALUES('',?,?,?,?,?,?,?,?,?)") or die(mysqli_error($GLOBALS['con']));
                $stmt->bind_param('issssssii', $repnumber, $cx['point_number' . $r], $cx['point_detail' . $r], $cx['hoodDuct_size' . $r], $cx['faceDuct_velocity' . $r], $cx['static_pressure' . $r], $cx['volume_flow' . $r], $cx['itemnumber'], $cx['initial_number']);
                $stmt->execute();
                $stmt->close();
            }
        }
    }
    sleep(1);
}
$reps = json_encode($_REQUEST['itemset']);
$now = strtotime('now');
$c = mysqli_query($GLOBALS['con'], "SELECT * FROM `rapid_history` WHERE `clientnumber`='" . $clientNumber . "'") or die($e = "CHAECK FAILURE: " . mysqli_error($GLOBALS['con']));
$n = mysqli_num_rows($c);
if ($n == 0) {
    $c = mysqli_query($GLOBALS['con'], "INSERT INTO `rapid_history` VALUES(NULL,'" . $clientNumber . "','" . $chain[0] . "','" . $reps . "','" . $now . "')") or die($e = "INSERT FAILURE: " . mysqli_error($GLOBALS['con']));
} else {
    $f = mysqli_fetch_array($c);
    $stmt = mysqli_query($GLOBALS['con'], "UPDATE `rapid_history` SET `chain`='" . $chain[0] . "', `reps`='" . $reps . "', `date`='" . $now . "' WHERE `id`='" . $f['id'] . "'") or die(mysqli_error($GLOBALS['con']));
}

echo "success|" . $repnumber;
