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

// Get the list of item numbers
$items = isset($_REQUEST['items']) ? explode(',', $_REQUEST['items']) : [];
$clientnumber = $_REQUEST['clientnumber'];

// Initialize variables
$itemsInfo = [];
$maxChainNumber = 0;

// Fetch all existing chain numbers for this client
$query = "SELECT linked FROM itemdetails WHERE clientnumber='$clientnumber' AND linked != ''";
$result = mysqli_query($con, $query);

// Find the highest chain number
while ($row = mysqli_fetch_assoc($result)) {
    $linkedData = explode(':', $row['linked']);
    $chainNumber = intval($linkedData[0]);
    $maxChainNumber = max($maxChainNumber, $chainNumber);
}

// The new chain number should be one more than the highest existing chain number
$newChainNumber = $maxChainNumber + 1;

// Fetch item details and current highest chain number
foreach ($items as $itemValue) {
    $itemValue = trim($itemValue);
    $query = "SELECT itemnumber, `desc`, linked FROM itemdetails WHERE itemnumber='$itemValue' AND clientnumber='$clientnumber'";
    $result = mysqli_query($con, $query);
    $item = mysqli_fetch_assoc($result);
    
    // Check if the item is already part of a chain
    $inChain = !empty($item['linked']);
    
    // Extract chain number if item is part of a chain
    if ($inChain) {
        $linkedData = explode(':', $item['linked']);
        $chainNumber = intval($linkedData[0]);
        $chainTitle = $linkedData[2]; // Assuming title is at the third position
        $maxChainNumber = max($maxChainNumber, $chainNumber);
    }

    $itemsInfo[] = [
        'itemnumber' => $item['itemnumber'],
        'desc' => $item['desc'],
        'inChain' => $inChain,
        'chainNumber' => $chainNumber ?? null,
        'chainTitle' => $chainTitle ?? null,
        'linkedData' => $item['linked'] ?? '' // Pass the linked data for later use
    ];
}
?>

<div class="container">
    <div class="card">
        <div class="card-body">
            <form id="chainForm">
                <div class="mb-3">
                    <label for="chainTitle" class="form-label">Chain Title</label>
                    <input type="text" class="form-control" id="chainTitle" name="chainTitle" required>
                </div>

                <h3>Items to Link:</h3>
                <ul class="list-group">
                    <?php foreach ($itemsInfo as $item): ?>
                    <li class="list-group-item d-flex justify-content-between align-items-center">
                        <div>
                            <input type="checkbox" name="items[]" value="<?= $item['itemnumber'] ?>" class="form-check-input me-2" data-linked="<?= htmlspecialchars($item['linkedData']) ?>" checked>
                            <?= $item['desc'] ?>
                        </div>
                        <?php if ($item['inChain']): ?>
                        <span class="badge bg-danger text-light">Already in chain: <?= $item['chainNumber'] ?>: <?= $item['chainTitle'] ?></span>
                        <?php endif; ?>
                    </li>
                    <?php endforeach; ?>
                </ul>
            </form>
        </div>
    </div>
</div>

<script>
function processLinking() {
    const checkboxes = document.querySelectorAll('input[name="items[]"]:checked');
    const flaggedItems = [];

    // Check if fewer than two items are selected
    if (checkboxes.length < 2) {
        showResponse('warning', 'You must select at least two items to create a chain.');
        return;
    }

    // Collect all checked items and identify flagged items
    checkboxes.forEach(checkbox => {
        const itemNumber = checkbox.value;
        const linkedData = checkbox.getAttribute('data-linked');

        // If the item has existing chain data, consider it flagged
        if (linkedData && linkedData.trim() !== "") {
            flaggedItems.push(itemNumber);
        }
    });

    // Log the flagged items to the console
    console.log("Flagged Items:", flaggedItems);

    const form = document.getElementById('chainForm');
    const formData = new FormData(form);
    formData.append('chainNumber', <?= $newChainNumber ?>);
    formData.append('clientnumber', '<?= $clientnumber ?>');
    formData.append('tenant', TENANT_URL);
    formData.append('flaggedItems', JSON.stringify(flaggedItems)); // Send flagged items as JSON

    fetch(`${ROOT_URL}/includes/mass/massChainProcess.php`, {
            method: 'POST',
            body: formData
        })
        .then(response => response.text())
        .then(data => {
            if (data.toLowerCase().startsWith('success')) {
                showResponse('success', data);
                window.location.href = '<?= $_SESSION['returnLanding'] ?>';
            } else {
                showResponse('warning', data);
            }
        })
        .catch(error => console.error('Error:', error));
}
</script>
