<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="<?php echo base_url();?>public/assets/js/jquery.validate.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.bundle.min.js"></script>
<script src="<?php echo base_url();?>public/assets/js/choices.min.js"></script>	

<!-- Bootstrap Multiselect / Choices -->
<link rel="stylesheet" href="<?php echo base_url();?>public/assets/css/choices.min.css">

<style>
/* Fix for Document Group Form */
.group-form-container .form-group {
    margin-bottom: 1.5rem;
}
.group-form-container .form-label {
    display: block;
    margin-bottom: 0.5rem;
    font-weight: 600;
    color: #333;
    position: relative;
    top: auto;
    left: auto;
    transform: none;
    background: transparent;
    padding: 0;
}
.group-form-container .choices {
    margin-top: 0.25rem;
}
.group-form-container .choices__inner {
    min-height: 44px;
    padding: 0.5rem;
    border: 1px solid #ced4da;
    border-radius: 6px;
    background: #fff;
}
.group-form-container .choices__list--multiple .choices__item {
    background: #3b82f6;
    border: none;
    border-radius: 4px;
    margin: 2px;
}
.group-form-container .choices__input {
    margin-top: 4px;
    display: block;
    width: 100% !important;
}
.group-form-container select.form-control {
    height: 44px;
    border: 1px solid #ced4da;
    border-radius: 6px;
}
</style>

<?php $is_view_only = isset($is_view_only) && $is_view_only; ?>
<div class="content">
	<div class="formcard group-form-container">
		<?php if ($is_view_only): ?>
		<div class="alert alert-info mb-3">
			<i class="fas fa-eye"></i> <strong>View Only Mode:</strong> All documents in this group have been uploaded and cannot be edited.
		</div>
		<?php endif; ?>
		
		<form class="type_form" id="type_form" method="post" action="<?php echo base_url();?>document/updateGroup">
			<input type="hidden" name="id" value="<?php echo $group_data[0]['id'];?>">
			<div class="form-group">
				<label for="main_document" class="form-label">Group Document</label>
				<select name="main_document" class="form-control" id="main_document" <?= $is_view_only ? 'disabled' : '' ?>>
					<option value="">-- Select Document --</option>
					<?php foreach($document_data as $document) { ?>
					<?php if($group_data[0]['document_id']==$document['id']) { $selected = 'selected';} else {$selected = '';}?>
					<option value="<?php echo $document['id'];?>" <?php echo $selected;?>><?php echo $document['document_name'];?></option>
					<?php } ?>
				</select>
			</div>
			<?php 
				$document_types = explode(',', $group_data[0]['grouped_doc_id']); 
			?>
			<div class="form-group">
				<label for="choices-multiple-remove-button" class="form-label">Select Documents to Group</label>
				<select name="child_document[]" id="choices-multiple-remove-button" class="form-control" multiple <?= $is_view_only ? 'disabled' : '' ?>>
					<?php foreach($document_data as $document) { ?>
					<option value="<?php echo $document['id'];?>"
					<?php echo (is_array($document_types) && in_array($document['id'], $document_types)) ? 'selected' : ''; ?>>
					<?php echo $document['document_name'];?></option>
					<?php } ?>
				</select>
			</div>
			<div class="formbtn-group">
				<?php if (!$is_view_only): ?>
				<button type="submit" class="formbtn formbtn-save">Save</button>
				<?php endif; ?>
				<a href="javascript:history.back()" class="formbtn formbtn-cancel"><?= $is_view_only ? 'Back' : 'Cancel' ?></a>
			</div>
		</form>
	</div>
</div>	
<script>
$(document).ready(function(){
    // Store all documents for reference
    const allDocuments = [
        <?php foreach($document_data as $document) { ?>
        { value: '<?php echo $document['id'];?>', label: '<?php echo addslashes($document['document_name']);?>' },
        <?php } ?>
    ];
    
    // Store all existing groups for circular reference prevention
    const allGroups = [
        <?php if (!empty($all_groups)): foreach($all_groups as $group) { ?>
        { 
            id: '<?php echo $group['id'];?>', 
            parent: '<?php echo $group['document_id'];?>', 
            children: [<?php echo "'" . implode("','", array_filter(explode(',', $group['grouped_doc_id']))) . "'"; ?>]
        },
        <?php } endif; ?>
    ];
    const currentGroupId = '<?php echo $current_group_id ?? '';?>';
    
    // Pre-selected values
    const initialParentId = '<?php echo $group_data[0]['document_id'];?>';
    const initialChildIds = [<?php echo "'" . implode("','", explode(',', $group_data[0]['grouped_doc_id'])) . "'"; ?>];

    // Function to get all descendants of a document (documents that have this doc as ancestor)
    function getDescendants(docId) {
        let descendants = new Set();
        
        // Find all groups where this document is a child
        allGroups.forEach(group => {
            if (group.id !== currentGroupId && group.children.includes(docId)) {
                // This document is a child in another group
                // The parent of that group cannot become our child
                descendants.add(group.parent);
            }
        });
        
        return Array.from(descendants);
    }
    
    // Function to get documents that would create circular reference if selected as child
    function getCircularRefDocs(selectedParentId) {
        if (!selectedParentId) return [];
        
        let forbidden = new Set();
        
        // Check all groups
        allGroups.forEach(group => {
            if (group.id === currentGroupId) return; // Skip current group
            
            // If our selected parent is a CHILD in another group,
            // then THAT group's parent cannot be our child
            if (group.children.includes(selectedParentId)) {
                forbidden.add(group.parent);
            }
            
            // If another group has our selected parent as its parent,
            // we can't select that group's parent as our child
            // (since that would make our parent be a child of its own child)
        });
        
        return Array.from(forbidden);
    }

    // Build initial choices with parent disabled and circular refs considered
    function buildChoices(parentId, selectedChildren) {
        let forbidden = getCircularRefDocs(parentId);
        
        return allDocuments.map(doc => {
            let isDisabled = doc.value === parentId || forbidden.includes(doc.value);
            return {
                value: doc.value,
                label: doc.label + (forbidden.includes(doc.value) ? ' (circular ref)' : ''),
                selected: selectedChildren.includes(doc.value),
                disabled: isDisabled
            };
        });
    }
    
    let initialChoices = buildChoices(initialParentId, initialChildIds);

    // Initialize Choices.js multi-select for child documents
    const childChoices = new Choices('#choices-multiple-remove-button', {
        removeItemButton: true,
        maxItemCount: 50,
        searchResultLimit: 50,
        renderChoiceLimit: 50,
        searchPlaceholderValue: 'Type to search...',
        placeholderValue: 'Select documents...',
        choices: initialChoices
    });

    // Disable children in parent dropdown on load
    $('#main_document option').each(function() {
        let optVal = $(this).val();
        if (optVal && initialChildIds.includes(optVal)) {
            $(this).prop('disabled', true);
        }
    });

    // When parent document is selected, disable it in child dropdown
    $('#main_document').on('change', function() {
        let parentId = $(this).val();
        
        // Get currently selected child values
        let selectedChildren = childChoices.getValue(true) || [];
        
        // If selected parent is in children, remove it
        if (parentId && selectedChildren.includes(parentId)) {
            selectedChildren = selectedChildren.filter(id => id !== parentId);
        }
        
        // Remove any circular ref violations
        let forbidden = getCircularRefDocs(parentId);
        selectedChildren = selectedChildren.filter(id => !forbidden.includes(id));
        
        // Clear and rebuild choices with parent and circular refs disabled
        childChoices.clearStore();
        childChoices.setChoices(buildChoices(parentId, selectedChildren), 'value', 'label', true);
    });

    // When child documents are selected, disable them in parent dropdown
    document.getElementById('choices-multiple-remove-button').addEventListener('change', function() {
        let selectedChildren = childChoices.getValue(true) || [];
        
        // Update parent dropdown - disable selected children
        $('#main_document option').each(function() {
            let optVal = $(this).val();
            if (optVal && selectedChildren.includes(optVal)) {
                $(this).prop('disabled', true);
            } else {
                $(this).prop('disabled', false);
            }
        });
        
        // If current parent is now in selected children, reset parent
        let currentParent = $('#main_document').val();
        if (currentParent && selectedChildren.includes(currentParent)) {
            $('#main_document').val('');
            alert('The selected parent document was added as a child. Please select a different parent.');
        }
    });

    // Form validation
    $('#type_form').on('submit', function(e) {
        let parentId = $('#main_document').val();
        let childIds = childChoices.getValue(true) || [];
        
        if (!parentId) {
            e.preventDefault();
            alert('Please select a Parent Document.');
            return false;
        }
        
        if (childIds.length === 0) {
            e.preventDefault();
            alert('Please select at least one Child Document.');
            return false;
        }
        
        if (childIds.includes(parentId)) {
            e.preventDefault();
            alert('Parent document cannot be the same as a child document.');
            return false;
        }
        
        // Check for circular reference
        let forbidden = getCircularRefDocs(parentId);
        let circularViolation = childIds.filter(id => forbidden.includes(id));
        if (circularViolation.length > 0) {
            e.preventDefault();
            alert('Circular reference detected! Some selected children would create a parent-child loop.');
            return false;
        }
        
        return true;
    });
});
</script>