<?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 rapidrepNewInsertReportItem(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']);
$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;
}

$cx['reptype'] = $_REQUEST['examType'];
$cx['adefect'] = "None";
$cx['bdefect'] = "None";

foreach ($_REQUEST['itemset'] as $_REQUEST['item']) {

    $stmt2 = $GLOBALS['con']->prepare("SELECT `clientnumber`,`code`,`linked`,`currdate` 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);
    $clientnumber = $cx2['clientnumber'];
    $chain = explode(":", $cx2['linked']);

    $e = '';
    $formClass = '';
    $repnumber = strtotime('now');

    $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'];
    $a = "None";
    $b = "None";

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

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


    $reportValues = $cx;
    $reportValues['repnumber'] = $repnumber;
    $reportValues['master_report_id'] = null;
    $reportValues['repnumberold'] = null;
    $reportValues['olddate'] = $startDate;
    $reportValues['insdate'] = $dt;
    $reportValues['nextDate'] = $nx;
    $reportValues['repdate'] = $nw;
    $reportValues['delivery'] = 0;
    $reportValues['clientnumber'] = $clientnumber;
    $reportValues['itemnumber'] = $_REQUEST['item'];
    $reportValues['esname'] = $_REQUEST['surveyor'];
    $reportValues['adefect'] = $a;
    $reportValues['bdefect'] = $b;
    $reportValues['obs'] = $obs;
    $reportValues['frequency'] = $freqNo;
    $reportValues['reptype'] = $_REQUEST['examType'];
    $reportValues['result'] = $stat;
    rapidrepNewInsertReportItem($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();

    sleep(1);

    //echo print_r($cx);

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


//genSchedule($cx['clientnumber']);
//echo $_REQUEST['date']."-".$_REQUEST['examType']."-";
echo "success|" . $repnumber;
