<?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 processed and the flagged items
$items = isset($_POST['items']) ? $_POST['items'] : [];
$flaggedItems = isset($_POST['flaggedItems']) ? json_decode($_POST['flaggedItems'], true) : [];
$actionType = $_POST['actionType'];
$targetChainNumber = $_POST['chainNumber'] ?? null;
$clientnumber = $_POST['clientnumber'];

// 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);
}

// Fetch the title for the target chain if moving items
$targetChainTitle = '';
if ($actionType === 'move') {
    $chainQuery = "SELECT linked FROM itemdetails WHERE linked LIKE '$targetChainNumber:%' AND clientnumber='$clientnumber' LIMIT 1";
    $chainResult = mysqli_query($con, $chainQuery);
    $chainData = mysqli_fetch_assoc($chainResult);
    $linkedData = explode(':', $chainData['linked']);
    $targetChainTitle = trim($linkedData[2], '"'); // Get the chain title and remove extra quotes
}

// Handle flagged items - remove them from their current chain
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");
                }
            }

            // If removing items, clear their linked data
            if ($actionType === 'remove') {
                $clearLinkedQuery = "UPDATE itemdetails SET linked='' WHERE itemnumber='$flaggedItem' AND clientnumber='$clientnumber'";
                mysqli_query($con, $clearLinkedQuery);
                //logError("Removed item $flaggedItem from any chain.");
            }
        } else {
            //logError("Error: existingItems is not an array for itemnumber: $flaggedItem, linked data: " . $item['linked']);
        }
    }
}

// If moving items, add them to the selected target chain
if ($actionType === 'move') {
    $targetChainQuery = "SELECT linked FROM itemdetails WHERE linked LIKE '$targetChainNumber:%' AND clientnumber='$clientnumber' LIMIT 1";
    $targetChainResult = mysqli_query($con, $targetChainQuery);
    $targetChainItem = mysqli_fetch_assoc($targetChainResult);

    if ($targetChainItem) {
        $targetLinkedData = explode(':', $targetChainItem['linked']);
        $targetChainItemsString = $targetLinkedData[1];

        // Ensure proper JSON format for target chain items
        $targetChainItemsString = str_replace(['[', ']'], '', $targetChainItemsString); // Remove brackets
        $targetChainItemsString = str_replace('"', '', $targetChainItemsString); // Remove quotes around the numbers
        $targetChainItems = json_decode('["' . implode('","', explode(',', $targetChainItemsString)) . '"]', true);

        if (is_array($targetChainItems)) {
            $newChainItems = array_merge($targetChainItems, $items); // Merge existing items with new items
            $updatedTargetChainData = $targetChainNumber . ':"[' . implode('","', $newChainItems) . ']":"' . $targetChainTitle . '"';

            foreach ($newChainItems as $itemNumber) {
                $updateQuery = "UPDATE itemdetails SET linked='$updatedTargetChainData' WHERE itemnumber='$itemNumber' AND clientnumber='$clientnumber'";
                mysqli_query($con, $updateQuery);
                //logError("Moved item $itemNumber to existing chain $targetChainNumber with updated data: $updatedTargetChainData");
            }

            echo "success: Items moved to chain $targetChainNumber successfully.";
        } else {
            //logError("Error: targetChainItems is not an array for chain $targetChainNumber.");
            echo "error: Unable to process the selected chain.";
        }
    } else {
        //logError("Error: Could not find chain data for chain $targetChainNumber.");
        echo "error: Target chain not found.";
    }
} else {
    echo "success: Items removed from their chains successfully.";
}