<?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 = [];
$chains = [];
$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 and collect chain information
while ($row = mysqli_fetch_assoc($result)) {
    $linkedData = explode(':', $row['linked']);
    $chainNumber = intval($linkedData[0]);

    // Ensure that $linkedData[2] is set and doesn't have extra quotes
    $chainTitle = isset($linkedData[2]) ? trim($linkedData[2], '"') : '';

    $maxChainNumber = max($maxChainNumber, $chainNumber);

    if (!isset($chains[$chainNumber])) {
        $chains[$chainNumber] = $chainTitle;
    }
}

// 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 = isset($linkedData[2]) ? trim($linkedData[2], '"') : ''; // Ensure no extra quotes
        $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="col-12 alert warning-color-dark text-light text-center p-1">You can move items from one chain to another or remove them from a chain.</div>
    <div class="card">

        <div class="card-body">
            <form id="chainForm">
                <div class="row">
                    <div class="col-12 col-md-6">
                        <div class="mb-3" data-mdb-select-init>
                            <label for="actionType" class="form-label">Select Action</label>
                            <select class="form-control" id="actionType" name="actionType" required>
                                <option value="move">Move Items to Another Chain</option>
                                <option value="remove">Remove Items from Chain</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-12 col-md-6">
                        <div class="mb-3" id="targetChainContainer">
                            <label for="targetChain" class="form-label">Select Target Chain</label>
                            <select class="form-control" id="targetChain" name="targetChain">
                                <option value="">Select a Chain</option>
                                <?php foreach ($chains as $chainNumber => $chainTitle): ?>
                                <option value="<?= $chainNumber ?>"><?= $chainNumber ?>: <?= htmlspecialchars($chainTitle) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                </div>
                <h3>Items to Process:</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>
                            <?= htmlspecialchars($item['desc']) ?>
                        </div>
                        <?php if ($item['inChain']): ?>
                        <span class="badge bg-danger text-light">Already in chain: <?= $item['chainNumber'] ?>: <?= htmlspecialchars($item['chainTitle']) ?></span>
                        <?php endif; ?>
                    </li>
                    <?php endforeach; ?>
                </ul>

                <button type="button" class="btn btn-primary mt-4" onclick="processChain()">Process Items</button>
            </form>
        </div>
    </div>
</div>

<script>
var actionSelect = new mdb.Select(document.getElementById('actionType'), {
    container: '#modalContainer'
});

var targetSelect = new mdb.Select(document.getElementById('targetChain'), {
    filter: true,
    container: '#modalContainer'
});
document.getElementById('actionType').addEventListener('change', function() {
    const actionType = this.value;
    const targetChainContainer = document.getElementById('targetChainContainer');

    if (actionType === 'move') {
        targetChainContainer.style.display = 'block';
    } else {
        targetChainContainer.style.display = 'none';
    }
});

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

    // Check if at least one item is selected
    if (checkboxes.length < 1) {
        showResponse('warning', 'You must select at least one item to process.');
        return;
    }

    const actionType = document.getElementById('actionType').value;
    const targetChain = document.getElementById('targetChain').value;

    if (actionType === 'move' && !targetChain) {
        showResponse('warning', 'Please select a target 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('actionType', actionType);
    formData.append('chainNumber', targetChain); // Use the selected chain number if moving
    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/massMoveChainProcess.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>