<?php

if (file_exists('../../' . $_REQUEST['tenant'] . '/config.php')) {
    require_once('../../' . $_REQUEST['tenant'] . '/config.php');
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}
$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);

    $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');

    $stmt = $GLOBALS['con']->prepare("INSERT INTO `reportitems` VALUES(NULL,'" . $repnumber . "',?,?,?,?,?,0,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param(
        'iiiiiissssssssssssssssssssssssssssssssssssssssssssssssssss',
        $cx['repnumber'],
        $cx['insdate'],
        $dt,
        $nx,
        $nw,
        $clientNumber,
        $_REQUEST['item'],

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

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

        $cx['changeScheme'],
        $cx['resultOfExam'],
        $cx['lastReportSeen'],
        $cx['examType'],
        $cx['partsCovered'],
        $cx['lease_or_hire'],


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

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

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

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

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

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

        $cx['clutch'],
        $cx['safety'],
        $cx['frequency'],
        $cx['reptype'],
        $cx['result']
    );
    $stmt->execute();
    echo $stmt->error;
    $insertID = mysqli_insert_id($GLOBALS['con']);
    $stmt->close();

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