<?php
$tenant = $_REQUEST['tenant'] ?? '';
if ($tenant !== '' && file_exists('../../../' . $tenant . '/config.php')) {
    require_once('../../../' . $tenant . '/config.php');
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}

header('Content-Type: application/json');

function linkedNameRespond(bool $ok, string $message, array $data = []): void
{
    echo json_encode(array_merge([
        'ok' => $ok,
        'message' => $message,
    ], $data));
    exit;
}

if (!isset($GLOBALS['con'])) {
    linkedNameRespond(false, 'Database connection unavailable.');
}

$function = strtolower((string)($_REQUEST['FUNCTION'] ?? $_REQUEST['function'] ?? ''));
if ($function !== 'rename') {
    linkedNameRespond(false, 'Unknown request.');
}

$clientnumber = (int)($_REQUEST['clientnumber'] ?? 0);
$chain = trim((string)($_REQUEST['chain'] ?? ''));
$name = trim((string)($_REQUEST['name'] ?? ''));

if ($clientnumber < 1 || !preg_match('/^[0-9]+$/', $chain) || (int)$chain < 1) {
    linkedNameRespond(false, 'Invalid chain details.');
}

$name = strip_tags($name);
$name = str_replace(':', ' - ', $name);
$name = preg_replace('/\s+/', ' ', $name);
$name = trim((string)$name);

if ($name === '') {
    linkedNameRespond(false, 'Please enter a chain name.');
}

if (strlen($name) > 120) {
    $name = substr($name, 0, 120);
}

$pattern = $chain . ':%';
$stmt = $GLOBALS['con']->prepare("SELECT `itemnumber`,`linked` FROM `itemdetails` WHERE `clientnumber`=? AND `linked` LIKE ?");
if (!$stmt) {
    linkedNameRespond(false, mysqli_error($GLOBALS['con']));
}

$stmt->bind_param('is', $clientnumber, $pattern);
$stmt->execute();
$rows = $stmt->get_result();
$stmt->close();

if (!$rows || $rows->num_rows < 1) {
    linkedNameRespond(false, 'No matching chain items were found.');
}

$updates = [];
while ($row = $rows->fetch_assoc()) {
    $linked = (string)($row['linked'] ?? '');
    if (!preg_match('/^\s*' . preg_quote($chain, '/') . '\s*:/', $linked)) {
        continue;
    }

    $rb = strrpos($linked, ']');
    if ($rb === false) {
        continue;
    }

    $updates[] = [
        'itemnumber' => (int)$row['itemnumber'],
        'linked' => substr($linked, 0, $rb + 1) . ':' . $name,
    ];
}

if (count($updates) < 1) {
    linkedNameRespond(false, 'No matching chain items were updated.');
}

$stmt = $GLOBALS['con']->prepare("UPDATE `itemdetails` SET `linked`=? WHERE `clientnumber`=? AND `itemnumber`=?");
if (!$stmt) {
    linkedNameRespond(false, mysqli_error($GLOBALS['con']));
}

$updated = 0;
$newLinked = '';
$itemnumber = 0;
$stmt->bind_param('sii', $newLinked, $clientnumber, $itemnumber);
foreach ($updates as $update) {
    $newLinked = $update['linked'];
    $itemnumber = $update['itemnumber'];
    if ($stmt->execute()) {
        $updated++;
    }
}
$stmt->close();

linkedNameRespond(true, 'Chain renamed.', [
    'name' => $name,
    'title' => 'C' . $chain . ': ' . $name,
    'updated' => $updated,
]);
