<?php
if (file_exists('../../' . ($_REQUEST['tenant'] ?? '') . '/config.php')) require_once('../../' . $_REQUEST['tenant'] . '/config.php');
if (file_exists('/config.php')) require_once('/config.php');

$clientnumber = intval($_POST['clientnumber'] ?? $_REQUEST['clientnumber'] ?? 0);
$entry = intval($_POST['entry'] ?? $_REQUEST['entry'] ?? 0);
$payloadRaw = (string)($_POST['payload'] ?? $_REQUEST['payload'] ?? '');

if ($clientnumber <= 0 || $entry <= 0 || $payloadRaw === '') die('Invalid rewind request');

$payload = json_decode($payloadRaw, true);
if (!is_array($payload)) die('Invalid payload');

function rr_deletePdf(int $clientnumber, int $rep, int $item, string $tenant) {
    $tenant = trim($tenant);
    if ($tenant === '') return;
    $path = '../..' . $tenant . '/output/reports/' . $clientnumber . '/' . $rep . '_' . $item . '.pdf';
    if (file_exists($path)) @unlink($path);
}

function rr_deleteReportRow(int $client, int $item, int $rep): int {
    $stmt = $GLOBALS['con']->prepare("DELETE FROM `reportitems` WHERE `clientnumber`=? AND `itemnumber`=? AND `repnumber`=?")
        or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('iii', $client, $item, $rep);
    $stmt->execute();
    $affected = $stmt->affected_rows;
    $stmt->close();
    return max(0, (int)$affected);
}

function rr_findReportRowByRep(int $rep): ?array {
    $stmt = $GLOBALS['con']->prepare("SELECT `clientnumber`,`itemnumber` FROM `reportitems` WHERE `repnumber`=? LIMIT 1")
        or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $rep);
    $stmt->execute();
    $r = $stmt->get_result();
    $stmt->close();
    if (!$r || $r->num_rows === 0) return null;
    return $r->fetch_assoc();
}

function rr_deleteReportRowByRep(int $rep): int {
    $stmt = $GLOBALS['con']->prepare("DELETE FROM `reportitems` WHERE `repnumber`=?")
        or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $rep);
    $stmt->execute();
    $affected = $stmt->affected_rows;
    $stmt->close();
    return max(0, (int)$affected);
}

function rr_fetchNewLastRow(int $client, int $item): ?array {
    $stmt = $GLOBALS['con']->prepare("SELECT `insdate`,`nextDate`,`result` FROM `reportitems` WHERE `clientnumber`=? AND `itemnumber`=? ORDER BY ABS(`repitem`) DESC LIMIT 1")
        or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('ii', $client, $item);
    $stmt->execute();
    $r = $stmt->get_result();
    $stmt->close();
    if (!$r || $r->num_rows === 0) return null;
    return $r->fetch_assoc();
}

function rr_restoreItemdetails(int $item, ?array $row) {
    if ($row) {
        $curr = intval($row['insdate'] ?? 0);
        $due = intval($row['nextDate'] ?? 0);
        $res = (string)($row['result'] ?? '');
        $stmt = $GLOBALS['con']->prepare("UPDATE `itemdetails` SET `currdate`=?, `duedate`=?, `lastReport`=? WHERE `itemnumber`=?")
            or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('iisi', $curr, $due, $res, $item);
        $stmt->execute();
        $stmt->close();
    } else {
        $curr = 0;
        $due = 0;
        $res = '';
        $stmt = $GLOBALS['con']->prepare("UPDATE `itemdetails` SET `currdate`=?, `duedate`=?, `lastReport`=? WHERE `itemnumber`=?")
            or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('iisi', $curr, $due, $res, $item);
        $stmt->execute();
        $stmt->close();
    }
}

$tenant = (string)($_REQUEST['tenant'] ?? $_POST['tenant'] ?? '');
$deleted = 0;
$requested = 0;

if (count($payload) > 0 && is_array($payload[0])) {
    foreach ($payload as $x) {
        $item = intval($x['item'] ?? 0);
        $rep = intval($x['rep'] ?? 0);
        if ($item <= 0 || $rep <= 0) continue;
        $requested++;

        $restoreClient = $clientnumber;
        rr_deletePdf($clientnumber, $rep, $item, $tenant);
        $removed = rr_deleteReportRow($clientnumber, $item, $rep);
        if ($removed === 0) {
            $actual = rr_findReportRowByRep($rep);
            if ($actual) {
                $item = intval($actual['itemnumber'] ?? $item);
                $restoreClient = intval($actual['clientnumber'] ?? $clientnumber);
                rr_deletePdf($restoreClient, $rep, $item, $tenant);
                $removed = rr_deleteReportRowByRep($rep);
            }
        }
        $deleted += $removed;

        $newLast = rr_fetchNewLastRow($restoreClient, $item);
        rr_restoreItemdetails($item, $newLast);
    }
} else {
    foreach ($payload as $item) {
        $item = intval($item);
        if ($item <= 0) continue;
        $requested++;

        $stmt = $GLOBALS['con']->prepare("SELECT `repnumber` FROM `reportitems` WHERE `clientnumber`=? AND `itemnumber`=? ORDER BY ABS(`repitem`) DESC LIMIT 1")
            or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('ii', $clientnumber, $item);
        $stmt->execute();
        $r = $stmt->get_result();
        $stmt->close();
        if ($r && $r->num_rows > 0) {
            $row = $r->fetch_assoc();
            $rep = intval($row['repnumber'] ?? 0);
            if ($rep > 0) {
                rr_deletePdf($clientnumber, $rep, $item, $tenant);
                $deleted += rr_deleteReportRow($clientnumber, $item, $rep);
            }
        }

        $newLast = rr_fetchNewLastRow($clientnumber, $item);
        rr_restoreItemdetails($item, $newLast);
    }
}

if ($requested > 0 && $deleted === 0) {
    die('No matching RapidRep report rows were found to rewind. History has been left in place.');
}

$stmt = $GLOBALS['con']->prepare("DELETE FROM `rapid_history` WHERE `id`=? AND `clientnumber`=?") or die(mysqli_error($GLOBALS['con']));
$stmt->bind_param('ii', $entry, $clientnumber);
$stmt->execute();
$stmt->close();

echo 'done';
