<?php ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once __DIR__ . '/../../functions/security.php';
require_once __DIR__ . '/../../functions/logging.php';
require_once __DIR__ . '/../../functions/itemdetails_json.php';

$tenant = enrep_tenant_segment();
if ($tenant !== '' && file_exists('../../../' . $tenant . '/config.php')) {
    require_once('../../../' . $tenant . '/config.php');
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}

if (!isset($GLOBALS['con']) || !($GLOBALS['con'] instanceof mysqli)) {
    enrep_fail(400, 'Tenant config not found');
}

enrep_require_user();

function wsf_e($value): string
{
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

$clientnumber = enrep_request_int('clientnumber');
$wsnumber = enrep_request_int('wsnumber');
$itemnumber = enrep_request_int('itemnumber');
$mode = enrep_request_string('mode', '', 80);
$revisionLocked = enrep_request_int('revisionLock') === 1;

//GET CLIENT DETAILS
$cd = ['clientnumber' => $clientnumber, 'clientname' => ''];
if ($clientnumber > 0) {
    $stmt = $GLOBALS['con']->prepare("SELECT `clientnumber`,`clientname` FROM `clientdetails` WHERE `clientnumber`=? LIMIT 1") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $clientnumber);
    $stmt->execute();
    $cc = $stmt->get_result();
    $stmt->close();
    $row = mysqli_fetch_array($cc);
    if ($row) {
        $cd = $row;
    }
}

//CHECK STATUS
$wsd = ['id' => $wsnumber, 'no' => '', 'rev' => '0', 'surveyor' => 0, 'description' => ''];
if ($wsnumber > 0) {
    $stmt = $GLOBALS['con']->prepare("SELECT * FROM `writtenscheme` WHERE `id`=?") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $wsnumber);
    $stmt->execute();
    $ws = $stmt->get_result();
    $stmt->close();
    $row = mysqli_fetch_array($ws);
    if ($row) {
        $wsd = $row;
    }
}

function getItem($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 getItemsPlant($itemnumber)
{
    $stmt = $GLOBALS['con']->prepare("SELECT `plantnumber` 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['plantnumber'] ?? '';
}

function getItemsSerial($itemnumber)
{
    $stmt = $GLOBALS['con']->prepare("SELECT `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 $cd['serialnumber'] ?? '';
}

function renderWsRevisions(int $wsnumber): string
{
    $stmt = $GLOBALS['con']->prepare("SELECT * FROM `wsrevisions` WHERE `wsnumber`=? ORDER BY abs(date) DESC") or die($error = mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $wsnumber);
    $stmt->execute();
    $res = $stmt->get_result();
    $stmt->close();

    $ret = '';
    while ($d = mysqli_fetch_array($res)) {
        $stmt = $GLOBALS['con']->prepare("SELECT `forename`,`surname` FROM `surveyor` WHERE `id`=?") or die($error = mysqli_error($GLOBALS['con']));
        $stmt->bind_param('i', $d['surveyor']);
        $stmt->execute();
        $res2 = $stmt->get_result();
        $stmt->close();
        $e = mysqli_fetch_array($res2);

        $del = '';
        if (($_SESSION['usertype'] ?? '') == "admins") {
            $del = '<a href="javascript:void(0)" class="btn btn-danger btn-sm" onClick="remrevConfirm(\'' . (int)$d['id'] . '\')" data-toggle="tooltip" data-placement="left" title="Remove this revision entry"><i class="fad fa-times"></i></a>';
        }

        $ret .= '<tr id="Rr' . (int)$d['id'] . '"><td>' . date("d-m-Y", (int)$d['date']) . ' <small>' . date("H:m:i", (int)$d['date']) . '</small></td><td>' . wsf_e($d['description']) . '</td><td>' . wsf_e(($e['forename'] ?? '') . ' ' . ($e['surname'] ?? '')) . '</td><td>' . $del . '</td></tr>';
    }

    return $ret;
}

function getWsRevisionNumber(int $wsnumber): string
{
    $stmt = $GLOBALS['con']->prepare("SELECT `rev` FROM `writtenscheme` WHERE `id`=? LIMIT 1") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $wsnumber);
    $stmt->execute();
    $res = $stmt->get_result();
    $stmt->close();
    $row = mysqli_fetch_array($res);
    return (string)($row['rev'] ?? '0');
}

function wsFunctionsAttachItem(int $wsnumber, int $itemnumber): bool
{
    if ($wsnumber <= 0 || $itemnumber <= 0 || empty($GLOBALS['con']) || !($GLOBALS['con'] instanceof mysqli)) {
        return false;
    }

    $stmt = $GLOBALS['con']->prepare("DELETE FROM `wsitems` WHERE `itemnumber`=? AND `wsnumber`<>?") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('ii', $itemnumber, $wsnumber);
    $stmt->execute();
    $stmt->close();

    $stmt = $GLOBALS['con']->prepare("SELECT `id` FROM `wsitems` WHERE `wsnumber`=? AND `itemnumber`=? LIMIT 1") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('ii', $wsnumber, $itemnumber);
    $stmt->execute();
    $existing = $stmt->get_result();
    $stmt->close();
    if ($existing && mysqli_fetch_array($existing)) {
        return true;
    }

    $created = time();
    $type = 1;
    $desc = '';
    $swl = '';
    $stmt = $GLOBALS['con']->prepare("INSERT INTO `wsitems` (`wsnumber`,`itemnumber`,`date`,`type`,`desc`,`swl`) VALUES(?,?,?,?,?,?)") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('iiiiss', $wsnumber, $itemnumber, $created, $type, $desc, $swl);
    $ok = $stmt->execute();
    $stmt->close();

    return $ok;
}


define('WS_ADD', 'Created a new WS entry for ' . $cd['clientname']);
define('WS_REMOVE', 'Deleted WS entry for ' . $cd['clientname']);
define('WS_SET', 'Committed WS entry (' . $wsd['no'] . ') for ' . $cd['clientname']);
define('WSI_UPDATE', 'Updated WS entry (' . $wsd['no'] . ') for ' . $cd['clientname']);
define('WS_UPDATE', 'Updated WS entry (' . $wsd['no'] . ') for ' . $cd['clientname']);
define('WSI_ADD', 'Added a new item (' . getItem($itemnumber) . ' - ' . getItemsPlant($itemnumber) . ' - ' . getItemsSerial($itemnumber) . ') to ' . $wsd['no'] . ' at ' . $cd['clientname']);
define('WSI_REMOVE', 'Removed item (' . getItem($itemnumber) . ' - ' . getItemsPlant($itemnumber) . ' - ' . getItemsSerial($itemnumber) . ') from ' . $wsd['no'] . ' at ' . $cd['clientname']);
define('REV_REMOVE', 'Removed revision entry from ' . $wsd['no'] . ' for ' . $cd['clientname']);
define('WS_DELIVER', 'Written Scheme ' . $wsd['no'] . ' for ' . $cd['clientname'] . ' was delivered successfully');
define('WS_REVIEW', 'No changes');
if (!defined('WSIE_ADD')) {
    define('WSIE_ADD', 'Added external WS item');
}
if (!defined('WSIE_REMOVE')) {
    define('WSIE_REMOVE', 'Removed external WS item');
}




switch ($mode) {
    default:
        break;

    case "delWS":
        $id = enrep_request_int('id');
        $stmt = $GLOBALS['con']->prepare("DELETE FROM `writtenscheme` WHERE `id`=?") or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('i', $id);
        $stmt->execute();
        $stmt->close();
        $stmt = $GLOBALS['con']->prepare("DELETE FROM `wsitems` WHERE `wsnumber`=?") or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('i', $id);
        $stmt->execute();
        $stmt->close();
        enrep_log('written_schemes', 'deleted', WS_REMOVE, ['entity_type' => 'writtenscheme', 'entity_id' => $id, 'clientnumber' => $clientnumber]);
        echo "success";
        break;

    case "setWS":
        $setClientnumber = enrep_request_int('clientnumber');
        $wsDesc = enrep_request_string('wsDesc', '', 255);
        $locnumber = enrep_request_int('locnumber');
        $wstype = enrep_request_int('wstype');
        $schemeNumberAlt = enrep_request_string('scheme_number_alt', '', 80);
        $renewal = strtotime(enrep_request_string('renewal_date', '', 40));
        if ($renewal === false) {
            $renewal = 0;
        }
        $attachItemnumber = enrep_request_int('itemnumber');

        // CHECK NUMBERING
        $stmt = $GLOBALS['con']->prepare("SELECT `no` FROM `writtenscheme` WHERE `clientnumber`=?") or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('i', $setClientnumber);
        $stmt->execute();
        $s = $stmt->get_result();
        $stmt->close();

        $number_array = array();
        while ($nrow = mysqli_fetch_array($s)) {
            $d = explode(":", $nrow['no']);
            $number = str_replace('WS', '', $d[0]);
            if ($number != "00") {
                $number_array[] = $number;
            }
        }
        if (empty($number_array)) {
            $number_array[] = 0;
        }
        $current = max($number_array);
        $new = $current + 1;
        $n = sprintf('%02d', $new);
        $wsn = "WS" . $n;

        $insertId = 0;
        $created = time();
        $revisionDate = $created;

        // INSERT RECORD
        if ($schemeNumberAlt !== '') {

            $stmt = $GLOBALS['con']->prepare(
                "INSERT INTO `writtenscheme` (`clientnumber`,`title`,`description`,`location`,`no`,`surveyor`,`date`,`rev`,`wSol`,`wCat`,`del`,`wstype`,`scheme_number_alt`,`renewal`) VALUES(?,?,NULL,?,?,NULL,?,'0',NULL,NULL,'0',?,?,?)"
            ) or die(mysqli_error($GLOBALS['con']));

            $stmt->bind_param(
                'isisiisi',
                $setClientnumber,
                $wsDesc,
                $locnumber,
                $wsn,
                $revisionDate,
                $wstype,
                $schemeNumberAlt,
                $renewal
            );

            $stmt->execute();
            $insertId = (int)$GLOBALS['con']->insert_id;
            $stmt->close();
        } else {

            $stmt = $GLOBALS['con']->prepare(
                "INSERT INTO `writtenscheme` (`clientnumber`,`title`,`description`,`location`,`no`,`surveyor`,`date`,`rev`,`wSol`,`wCat`,`del`,`wstype`,`scheme_number_alt`,`renewal`) VALUES(?,?,NULL,?,?,NULL,?,'0',NULL,NULL,'0',?,NULL,?)"
            ) or die(mysqli_error($GLOBALS['con']));

            $stmt->bind_param(
                'isisiii',
                $setClientnumber,
                $wsDesc,
                $locnumber,
                $wsn,
                $revisionDate,
                $wstype,
                $renewal
            );

            $stmt->execute();
            $insertId = (int)$GLOBALS['con']->insert_id;
            $stmt->close();
        }

        enrep_log('written_schemes', 'created', WS_SET, ['entity_type' => 'writtenscheme', 'entity_id' => $insertId, 'clientnumber' => $setClientnumber, 'locnumber' => $locnumber, 'subject' => $wsn]);

        if ($insertId > 0) {
            if ($attachItemnumber > 0 && wsFunctionsAttachItem($insertId, $attachItemnumber)) {
                enrep_log('written_scheme_items', 'created', 'Attached item to newly created written scheme', ['entity_type' => 'wsitems', 'entity_id' => $insertId, 'clientnumber' => $setClientnumber, 'itemnumber' => $attachItemnumber]);
            }
            echo "success|" . $insertId . "|" . $wsn . " " . $wsDesc;
        } else {
            echo "error";
        }
        exit;

    case "saveAlt":
        $id = enrep_request_int('id');
        $schemeNumberAlt = enrep_request_string('scheme_number_alt', '', 80);
        $stmt = $GLOBALS['con']->prepare("UPDATE `writtenscheme` SET `scheme_number_alt`=? WHERE `id`=?") or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('si', $schemeNumberAlt, $id);
        $stmt->execute();
        $stmt->close();
        echo "success";
        break;

    case "saveSurv":
        $id = enrep_request_int('id');
        $surveyor = enrep_request_int('surveyor');
        $stmt = $GLOBALS['con']->prepare("UPDATE `writtenscheme` SET `surveyor`=? WHERE `id`=?") or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('ii', $surveyor, $id);
        $stmt->execute();
        $stmt->close();
        echo "success";
        break;

    case "saveRev":
        $id = enrep_request_int('id');
        $revision = enrep_request_int('rev');
        if ($revision < 0) {
            $revision = 0;
        }

        $stmt = $GLOBALS['con']->prepare("UPDATE `writtenscheme` SET `rev`=? WHERE `id`=?") or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('ii', $revision, $id);
        $stmt->execute();
        $stmt->close();
        echo "success|" . $revision;
        break;


    case "addRevision":
        $revisionWsnumber = enrep_request_int('wsnumber');
        $revisionSurveyor = enrep_request_int('surveyor');
        $revisionDesc = enrep_request_string('desc', '', 5000);
        $revisionDate = strtotime(enrep_request_string('date', '', 40));
        if ($revisionDate === false) {
            $revisionDate = time();
        }

        if (!$revisionLocked) {
            $stmt = $GLOBALS['con']->prepare("UPDATE `writtenscheme` SET `rev`=rev+1,`del`='1' WHERE `id`=?") or die(mysqli_error($GLOBALS['con']));
            $stmt->bind_param('i', $revisionWsnumber);
            $stmt->execute();
            $stmt->close();
        }

        $stmt = $GLOBALS['con']->prepare("INSERT INTO `wsrevisions` VALUES(NULL,?,?,?,?)") or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('isii', $revisionWsnumber, $revisionDesc, $revisionSurveyor, $revisionDate);
        $stmt->execute();
        $stmt->close();
        enrep_log('written_schemes', 'revision_added', WS_UPDATE, ['entity_type' => 'writtenscheme', 'entity_id' => $revisionWsnumber, 'clientnumber' => $clientnumber]);


        echo "success|" . renderWsRevisions($revisionWsnumber) . "|" . getWsRevisionNumber($revisionWsnumber);
        exit();
        break;



    case "addWSI":
        $addWsnumber = enrep_request_int('wsnumber');
        $addItemnumber = enrep_request_int('itemnumber');
        $wsSurveyor = (int)($wsd['surveyor'] ?? 0);
        $created = time();

        if (!$revisionLocked) {
            $stmt = $GLOBALS['con']->prepare("UPDATE `writtenscheme` SET `rev`=IF(CAST(`rev` AS UNSIGNED)<1,1,CAST(`rev` AS UNSIGNED)+1),`del`='1' WHERE `id`=?") or die(mysqli_error($GLOBALS['con']));
            $stmt->bind_param('i', $addWsnumber);
            $stmt->execute();
            $stmt->close();
        }

        if (!$revisionLocked) {
            $revisionText = WSI_ADD;
            $stmt = $GLOBALS['con']->prepare("INSERT INTO `wsrevisions` VALUES(NULL,?,?,?,?)") or die(mysqli_error($GLOBALS['con']));
            $stmt->bind_param('isii', $addWsnumber, $revisionText, $wsSurveyor, $created);
            $stmt->execute();
            $stmt->close();
            enrep_log('written_schemes', 'item_added', WSI_ADD, ['entity_type' => 'writtenscheme', 'entity_id' => $addWsnumber, 'clientnumber' => $clientnumber, 'itemnumber' => $addItemnumber]);
        }

        $stmt = $GLOBALS['con']->prepare("INSERT INTO `wsitems` VALUES(NULL,?,?,?,'1',NULL,NULL)") or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('iii', $addWsnumber, $addItemnumber, $created);
        $stmt->execute();
        $stmt->close();

        enrep_log('written_scheme_items', 'created', WSI_ADD, ['entity_type' => 'wsitems', 'entity_id' => $addWsnumber, 'clientnumber' => $clientnumber, 'itemnumber' => $addItemnumber]);
        echo "success|" . renderWsRevisions($addWsnumber);
        break;

    case "removeWSI":
        $removeWsnumber = enrep_request_int('wsnumber');
        $removeItemnumber = enrep_request_int('itemnumber');
        $wsSurveyor = (int)($wsd['surveyor'] ?? 0);
        $created = time();

        if (!$revisionLocked) {
            $stmt = $GLOBALS['con']->prepare("UPDATE `writtenscheme` SET `rev`=IF(CAST(`rev` AS UNSIGNED)<1,1,CAST(`rev` AS UNSIGNED)+1),`del`='1' WHERE `id`=?") or die(mysqli_error($GLOBALS['con']));
            $stmt->bind_param('i', $removeWsnumber);
            $stmt->execute();
            $stmt->close();
        }

        if (!$revisionLocked) {
            $revisionText = WSI_REMOVE;
            $stmt = $GLOBALS['con']->prepare("INSERT INTO `wsrevisions` VALUES(NULL,?,?,?,?)") or die(mysqli_error($GLOBALS['con']));
            $stmt->bind_param('isii', $removeWsnumber, $revisionText, $wsSurveyor, $created);
            $stmt->execute();
            $stmt->close();
            enrep_log('written_schemes', 'item_removed', WSI_REMOVE, ['entity_type' => 'writtenscheme', 'entity_id' => $removeWsnumber, 'clientnumber' => $clientnumber, 'itemnumber' => $removeItemnumber]);
        }

        $stmt = $GLOBALS['con']->prepare("DELETE FROM `wsitems` WHERE `wsnumber`=? AND `itemnumber`=?") or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('ii', $removeWsnumber, $removeItemnumber);
        $stmt->execute();
        $stmt->close();
        enrep_log('written_scheme_items', 'deleted', WSI_REMOVE, ['entity_type' => 'wsitems', 'entity_id' => $removeWsnumber, 'clientnumber' => $clientnumber, 'itemnumber' => $removeItemnumber]);

        $stmt = $GLOBALS['con']->prepare("SELECT * FROM `itemdetails` WHERE `itemnumber`=? LIMIT 1");
        if ($stmt) {
            $stmt->bind_param('i', $removeItemnumber);
            $stmt->execute();
            $res = $stmt->get_result();
            $stmt->close();
            $row = mysqli_fetch_array($res);
            if (is_array($row)) {
                $pressure = enrep_itemdetails_pressure_from_record($row);
                unset($pressure['scheme_number'], $pressure['scheme_number_alt'], $pressure['system_type']);
                $lev = enrep_itemdetails_lev_from_record($row);
                enrep_itemdetails_try_save_json(
                    $GLOBALS['con'],
                    $removeItemnumber,
                    json_encode(enrep_itemdetails_clean_array($pressure), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
                    json_encode(enrep_itemdetails_clean_array($lev), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
                );
            }
        }
        echo "success|" . renderWsRevisions($removeWsnumber);
        break;

    case "setWSI":
        $setWsnumber = enrep_request_int('wsnumber');
        $stmt = $GLOBALS['con']->prepare("UPDATE `writtenscheme` SET `rev`='1' WHERE `id`=?") or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('i', $setWsnumber);
        $stmt->execute();
        $stmt->close();
        genWSI($setWsnumber);
        echo "success";
        break;

    case "addWSIE":
        $addWsnumber = enrep_request_int('wsnumber');
        $created = time();
        $desc = enrep_request_string('desc', '', 1000);
        $swl = enrep_request_string('swl', '', 255);
        $stmt = $GLOBALS['con']->prepare("INSERT INTO `wsitems` VALUES('',?,'',?,'0',?,?)") or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('iiss', $addWsnumber, $created, $desc, $swl);
        $stmt->execute();
        $stmt->close();
        enrep_log('written_schemes', 'external_item_added', WSIE_ADD, ['entity_type' => 'writtenscheme', 'entity_id' => $addWsnumber, 'clientnumber' => $clientnumber, 'subject' => $desc]);
        break;

    case "removeWSIE":
        $id = enrep_request_int('id');
        $stmt = $GLOBALS['con']->prepare("DELETE FROM `wsitems` WHERE `id`=?") or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('i', $id);
        $stmt->execute();
        $stmt->close();
        enrep_log('written_scheme_items', 'external_item_removed', WSIE_REMOVE, ['entity_type' => 'wsitems', 'entity_id' => $id, 'clientnumber' => $clientnumber]);
        echo "success";
        break;

    case "updateWSI":
        $updateWsnumber = enrep_request_int('wsnumber');
        $updateSurveyor = enrep_request_int('surveyor');
        $updateDate = strtotime(enrep_request_string('date', '', 40));
        if ($updateDate === false) {
            $updateDate = 0;
        }
        $updateDescription = enrep_request_string('description', '', 5000);
        $updateTitle = enrep_request_string('title', '', 255);
        $updateLocnumber = enrep_request_string('locnumber', '', 80);
        $updateWCat = enrep_request_string('wCat', '', 255);
        $updateWSol = enrep_request_string('wSol', '', 255);
        $updateSchemeAlt = enrep_request_string('scheme_number_alt', '', 80);
        $updateRenewal = strtotime(enrep_request_string('renewal_date', '', 40));
        if ($updateRenewal === false) {
            $updateRenewal = 0;
        }

        if ($wsd['rev'] == "0") {
        } else {
            if ($wsd['description'] == $updateDescription) {
            } else {
                if (!$revisionLocked) {
                    $stmt = $GLOBALS['con']->prepare("UPDATE `writtenscheme` SET `rev`=rev+1,`del`='1' WHERE `id`=?") or die(mysqli_error($GLOBALS['con']));
                    $stmt->bind_param('i', $updateWsnumber);
                    $stmt->execute();
                    $stmt->close();
                }

                //$stmt = $GLOBALS['con']->prepare("INSERT INTO `wsrevisions` VALUES('',?,'".WS_UPDATE."',?,'".strtotime('now')."')")or die(mysqli_error($e="CREATE WS ENTRY: ".$GLOBALS['con']));
                //$stmt->bind_param('ii',$_REQUEST['wsnumber'],$_REQUEST['surveyor']);$stmt->execute();$stmt->close();

                if (!$revisionLocked) {
                    enrep_log('written_schemes', 'revision_added', WS_UPDATE, ['entity_type' => 'writtenscheme', 'entity_id' => $updateWsnumber, 'clientnumber' => $clientnumber]);
                }
            }
        }

        $stmt = $GLOBALS['con']->prepare("UPDATE `writtenscheme` SET `surveyor`=?, `date`=?, `description`=?, `title`=?,`location`=?, `wCat`=?, `wSol`=?, `scheme_number_alt`=?, `renewal`=? WHERE `id`=?") or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('iissssssii', $updateSurveyor, $updateDate, $updateDescription, $updateTitle, $updateLocnumber, $updateWCat, $updateWSol, $updateSchemeAlt, $updateRenewal, $updateWsnumber);
        $stmt->execute();
        $stmt->close();
        enrep_log('written_schemes', 'updated', WS_UPDATE, ['entity_type' => 'writtenscheme', 'entity_id' => $updateWsnumber, 'clientnumber' => $clientnumber, 'locnumber' => (int)$updateLocnumber, 'subject' => $updateTitle]);
        echo "success";
        break;


    case "remRev":
        $entry = enrep_request_int('entry');
        $nextRevision = null;
        $stmt = $GLOBALS['con']->prepare("DELETE FROM `wsrevisions` WHERE `id`=?") or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('i', $entry);
        $stmt->execute();
        $stmt->close();

        if (!$revisionLocked) {
            $stmt = $GLOBALS['con']->prepare("UPDATE `writtenscheme` SET `rev`=GREATEST(CAST(`rev` AS SIGNED)-1,0),`del`='1' WHERE `id`=?") or die(mysqli_error($GLOBALS['con']));
            $stmt->bind_param('i', $wsnumber);
            $stmt->execute();
            $stmt->close();

            $stmt = $GLOBALS['con']->prepare("SELECT `rev` FROM `writtenscheme` WHERE `id`=? LIMIT 1") or die(mysqli_error($GLOBALS['con']));
            $stmt->bind_param('i', $wsnumber);
            $stmt->execute();
            $res = $stmt->get_result();
            $stmt->close();
            $row = mysqli_fetch_array($res);
            $nextRevision = (string)($row['rev'] ?? '0');
        }

        enrep_log('written_schemes', 'revision_deleted', REV_REMOVE, ['entity_type' => 'wsrevisions', 'entity_id' => $entry, 'clientnumber' => $clientnumber]);
        echo "success" . ($nextRevision !== null ? "|" . $nextRevision : "");
        break;

    case "setWSIDel":
        $deliverWsnumber = enrep_request_int('wsnumber');
        $stmt = $GLOBALS['con']->prepare("UPDATE `writtenscheme` SET `del`='0' WHERE `id`=?") or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('i', $deliverWsnumber);
        $stmt->execute();
        $stmt->close();
        enrep_log('written_schemes', 'delivered', WS_DELIVER, ['entity_type' => 'writtenscheme', 'entity_id' => $deliverWsnumber, 'clientnumber' => $clientnumber]);
        echo "success";
        break;

    case "addReview":
        $reviewWsnumber = enrep_request_int('wsnumber');
        $reviewSurveyor = enrep_request_int('surveyor');
        $created = time();
        if (!$revisionLocked) {
            $stmt = $GLOBALS['con']->prepare("UPDATE `writtenscheme` SET `rev`=rev+1,`del`='1' WHERE `id`=?") or die(mysqli_error($GLOBALS['con']));
            $stmt->bind_param('i', $reviewWsnumber);
            $stmt->execute();
            $stmt->close();
        }

        $reviewText = WS_REVIEW;
        $stmt = $GLOBALS['con']->prepare("INSERT INTO `wsrevisions` VALUES('',?,?,?,?)") or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('isii', $reviewWsnumber, $reviewText, $reviewSurveyor, $created);
        $stmt->execute();
        $stmt->close();

        enrep_log('written_schemes', 'review_added', WS_REVIEW, ['entity_type' => 'writtenscheme', 'entity_id' => $reviewWsnumber, 'clientnumber' => $clientnumber]);
        echo "Rsuccess";
        break;
}
