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

// Specify the file where errors will be logged
$errorLogFile = 'errors.txt'; // Update the path as needed

// Get the list of items to be linked and the flagged items
$items = isset($_POST['items']) ? $_POST['items'] : [];
$flaggedItems = isset($_POST['flaggedItems']) ? json_decode($_POST['flaggedItems'], true) : [];
$chainNumber = $_POST['chainNumber'];
$clientnumber = $_POST['clientnumber'];
$chainTitle = mysqli_real_escape_string($con, trim($_POST['chainTitle'], '"')); // Ensure chain title doesn't have extra quotes and escape it

// Function to log errors to the specified file
function logError($message) {
    global $errorLogFile;
    file_put_contents($errorLogFile, date('Y-m-d H:i:s') . " - " . $message . PHP_EOL, FILE_APPEND);
}

foreach ($flaggedItems as $flaggedItem) {
    $query = "SELECT linked FROM itemdetails WHERE itemnumber='$flaggedItem' AND clientnumber='$clientnumber'";
    $result = mysqli_query($con, $query);
    $item = mysqli_fetch_assoc($result);

    if (!empty($item['linked'])) {
        $linkedData = explode(':', $item['linked']);
        $existingChainNumber = $linkedData[0];

        // Attempt to fix the JSON format
        $linkedArrayString = $linkedData[1];

        // Replace any incorrect JSON formatting
        $linkedArrayString = str_replace(['[', ']'], '', $linkedArrayString); // Remove brackets
        $linkedArrayString = str_replace('"', '', $linkedArrayString); // Remove quotes around the numbers
        $linkedArrayString = '["' . implode('","', explode(',', $linkedArrayString)) . '"]'; // Properly format as JSON array

        $existingItems = json_decode($linkedArrayString, true);

        if (is_array($existingItems)) {
            // Continue with processing the array as before
            $updatedItems = array_filter($existingItems, function($item) use ($flaggedItem) {
                return $item !== $flaggedItem;
            });

            logError("Updated items for chain $existingChainNumber: " . implode(',', $updatedItems));

            if (count($updatedItems) <= 1) {
                $removeChainQuery = "UPDATE itemdetails SET linked='' WHERE linked LIKE '$existingChainNumber:%' AND clientnumber='$clientnumber'";
                logError("Removing chain $existingChainNumber as only one item remains.");
                mysqli_query($con, $removeChainQuery);
            } else {
                $updatedLinkedData = $existingChainNumber . ':"[' . implode('","', $updatedItems) . ']":"' . $linkedData[2] . '"';
                foreach ($updatedItems as $itemNumber) {
                    $updateQuery = "UPDATE itemdetails SET linked='$updatedLinkedData' WHERE itemnumber='$itemNumber' AND clientnumber='$clientnumber'";
                    mysqli_query($con, $updateQuery);
                    logError("Updated item $itemNumber with new linked data: $updatedLinkedData");
                }
            }
        } else {
            logError("Error: existingItems is still not an array for itemnumber: $flaggedItem, linked data: " . $item['linked']);
        }
    }
}

// Now proceed to create the new chain
$newChainData = $chainNumber . ':"[' . implode('","', $items) . ']":' . $chainTitle ;
foreach ($items as $item) {
    $updateQuery = "UPDATE itemdetails SET linked='$newChainData' WHERE itemnumber='$item' AND clientnumber='$clientnumber'";
    mysqli_query($con, $updateQuery);
    // Log the creation of the new chain
    logError("Created new chain $chainNumber for item $item with data: $newChainData");
}

// Return success response
echo "success: Chain created successfully.";
?>