<?php
// groups.php
// Administration Bootstrap 
error_reporting(E_ALL);
ini_set('display_errors', 1);
//session_start();
chdir('../');
include($_SERVER['DOCUMENT_ROOT'] . '/includes/include_all.inc.php');
/* **************** HEADER FROM MAIN (REQUIRED FOR MENU) **************/
include($_SERVER['DOCUMENT_ROOT'] . '/menu.php');
$userDetails = menuUserDetails($_SESSION['front_user_id']);
$user = null;
if (isset($_SESSION['front_user_id'])) {
    $stmt = $pdo->prepare("SELECT * FROM wp_users WHERE id = ?");
    $stmt->execute([$_SESSION['front_user_id']]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
}
/* ***************** END HEADER FROM MAIN *****************************/
include($_SERVER['DOCUMENT_ROOT'] . '/admin/inc/header_logic.inc.php');

// current page variable
$current_page = 'groups';

$showHidden = isset($_GET['show_hidden']) ? (bool)$_GET['show_hidden'] : false;
$userType = $_SESSION['user_type'] ?? '';
$groupWhere = "";

if($usertype == 'admin'){
    // Admin sees their group regardless of hidden status
    $groupWhere = " WHERE group_name = '" . $_SESSION['user_group'] . "' ";
} else if ($usertype == 'super') {
    // Only super admin is affected by hidden status
    if (!$showHidden) {
        $groupWhere = " WHERE (is_hidden = 0 OR is_hidden IS NULL)";
    }
}

// Handle AJAX visibility toggle
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'toggle_visibility') {
    header('Content-Type: application/json');
    
    try {
        if (empty($_POST['id']) || empty($_POST['status'])) {
            throw new Exception('Missing required parameters');
        }
        
        $id = $_POST['id'];
        $isHidden = ($_POST['status'] === 'hidden') ? 1 : 0;
        
        // Check permissions
        $canModify = false;
        if ($_SESSION['user_type'] === 'super') {
            $canModify = true;
        } elseif ($_SESSION['user_type'] === 'admin') {
            $stmt = $pdo->prepare("SELECT group_name FROM wp_groups WHERE id = ?");
            $stmt->execute([$id]);
            $groupName = $stmt->fetchColumn();
            $canModify = ($groupName === $_SESSION['user_group']);
        }
        
        if (!$canModify) {
            throw new Exception('Permission denied');
        }
        
        $stmt = $pdo->prepare("UPDATE wp_groups SET is_hidden = ? WHERE id = ?");
        $success = $stmt->execute([$isHidden, $id]);
        
        if (!$success) {
            throw new Exception('Failed to update group visibility');
        }
        
        echo json_encode(['success' => true]);
        exit(); // Make sure to exit here
        
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
        exit(); // Make sure to exit here
    }
}

// Sorting logic for all columns
$sortColumns = [
    'groupname' => 'group_name',
    'adminname' => 'group_admin',
    'adminemail' => 'group_email',
    'institution' => 'expiration_date',
    'datecreated' => 'group_registered',
    'expiration' => 'expiration_date',
    'status' => 'group_status'
];
$orderBy = "ORDER BY group_name ASC"; // Default sorting

foreach ($sortColumns as $param => $column) {
    if (isset($_GET["{$param}sort"])) {
        $direction = ($_GET["{$param}sort"] === "asc") ? "ASC" : "DESC";
        $orderBy = "ORDER BY $column $direction";
        ${$param . "SortNext"} = ($_GET["{$param}sort"] === "asc") ? "desc" : "asc";
        ${$param . "Label"} = ($_GET["{$param}sort"] === "asc") ? "Sort Z-A" : "Sort A-Z";
    } else {
        ${$param . "SortNext"} = "asc";
        ${$param . "Label"} = "Sort A-Z";
    }
}
include($_SERVER['DOCUMENT_ROOT'] . '/admin/header.php');

// Fetch groups data without visibility condition
$baseQuery = "SELECT * FROM wp_groups $groupWhere";
if (!str_contains($baseQuery, 'WHERE')) {
    $baseQuery .= " WHERE 1=1";
}

// Fetch visible groups for main table
if ($usertype == 'admin') {
    // Admin sees their group regardless of hidden status
    $visibleQuery = $baseQuery . " " . $orderBy;
    $stmt = $pdo->prepare($visibleQuery);
    $stmt->execute();
    $visibleGroups = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $hiddenGroups = []; // Empty array since admin shouldn't see separate hidden table
} else {
    // Super admin - apply hidden filters
    $visibleQuery = $baseQuery;
    $visibleQuery .= " AND (is_hidden = 0 OR is_hidden IS NULL)";
    $visibleQuery .= " " . $orderBy;
    $stmt = $pdo->prepare($visibleQuery);
    $stmt->execute();
    $visibleGroups = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Fetch hidden groups for secondary table (super admin only)
    $hiddenGroups = [];
    if ($showHidden) {
        $hiddenQuery = $baseQuery;
        $hiddenQuery .= " AND is_hidden = 1";
        $hiddenQuery .= " " . $orderBy;
        $stmt = $pdo->prepare($hiddenQuery);
        $stmt->execute();
        $hiddenGroups = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
}

// check super admin privileges
// $isSuperAdmin = ($usertype == 'super');
$isSuperAdmin = ($usertype == 'nullll'); // disabling it for now

?>

	<style>
        .edit_area {
            min-height: 1em;
            min-width: 50px;
            display: inline-block;
            border: 1px solid transparent;
            padding: 2px;
        }
		<?php if ($isSuperAdmin): ?>
			.edit_area:hover {
				border-color: #ccc;
				cursor: pointer;
			}
			.edit_area:empty:before {
				content: 'Click to add';
				color: #999;
				font-style: italic;
			}
        <?php endif; ?>
    </style>
    <script type="text/javascript">
        $(document).ready(function() {
            <?php if ($isSuperAdmin): ?>
            $('.edit_area').on('click', function() {
                var $this = $(this);
                var currentValue = $this.text().trim();
                var inputField = $('<input type="text">').val(currentValue);
                
                $this.html(inputField);
                inputField.focus();

                inputField.on('blur', function() {
                    var newValue = $(this).val().trim();
                    if (newValue === '') {
                        $this.empty();  // This will trigger the :empty pseudo-class
                    } else {
                        $this.text(newValue);
                    }
                    
                    // Send AJAX request to save the change
                    $.ajax({
                        url: '../save-groups.php',
                        method: 'POST',
                        data: {
                            id: $this.attr('id'),
                            value: newValue
                        },
                        success: function(response) {
                            console.log('Update successful:', response);
                        },
                        error: function(xhr, status, error) {
                            console.error('Update failed:', error);
                            $this.text(currentValue); // Revert to original value on error
                        }
                    });
                });
            });
            <?php endif; ?>
        });

        function confirmDeleteGeneric() {
            return confirm("Are You Sure You Want To Delete? There is no undo!");
        }
    </script>
	
	<div class="table-cont">
		<h2 class="top-title<?php if ($usertype == 'super') { ?> 95-table<?php } ?>">Group Details</h2>
		<?php if ($usertype == 'super') { ?>
		<div class="visibility-toggle-container">
			<label class="switch">
				<input type="checkbox" id="showHiddenToggle" <?php echo $showHidden ? 'checked' : ''; ?>>
				<span class="slider round"></span>
			</label>
			<span>Show Hidden Groups</span>
		</div>
		<?php } ?>
		
		<?php /* hidden table */ ?>
		<?php if ($showHidden && !empty($hiddenGroups)): ?>
			<h2 class="overview-title">Hidden Groups</h3>
			<table class="home-table<?php if ($usertype == 'super') { ?> 95-table<?php } ?>">
				<tr>
					<?php if ($usertype == 'super') { ?><th style="width:5%;">ID</th><?php } ?>
					<th width="20%">Group Name<?php if ($usertype == 'super') { ?>&nbsp;&nbsp;<a class="sort" href="groups.php?groupnamesort=<?= htmlspecialchars($groupnameSortNext ?? '') ?>"><?= htmlspecialchars($groupnameLabel ?? '') ?></a><?php } ?></th>
					<th width="20%">Admin Name<?php if ($usertype == 'super') { ?>&nbsp;&nbsp;<a class="sort" href="groups.php?adminnamesort=<?= htmlspecialchars($adminnameSortNext ?? '') ?>"><?= htmlspecialchars($adminnameLabel ?? '') ?></a><?php } ?></th>
					<th width="20%">Admin Email<?php if ($usertype == 'super') { ?>&nbsp;&nbsp;<a class="sort" href="groups.php?adminemailsort=<?= htmlspecialchars($adminemailSortNext ?? '') ?>"><?= htmlspecialchars($adminemailLabel ?? '') ?></a><?php } ?></th>
					<th style="text-align:center;" style="width:6%;text-align:center;">Group Password</th>
					<th style="width:20%;">Expires<?php if ($usertype == 'super') { ?>&nbsp;&nbsp;<a class="sort" href="groups.php?expirationsort=<?= htmlspecialchars($expirationSortNext ?? '') ?>"><?= htmlspecialchars($expirationLabel ?? '') ?></a><?php } ?></th>
					<?php if ($usertype == 'super') { ?><th width="20%">Group Address &amp; Contact</th><?php } ?>
					<th style="text-align:center;" width="3%">Edit</th>
					<?php if ($usertype == 'super') { ?><!-- <th width="3%">Delete</th> --><?php } ?>
					<?php if ($userType == 'super'): ?>
						<th style="text-align:center;">Visibility</th>
					<?php endif; ?>
				</tr>
				<?php foreach ($hiddenGroups as $group): ?>
					<tr>
						<?php if ($usertype == 'super') { ?><td><?= htmlspecialchars($group['id']); ?></td><?php } ?>
						<td><span class="edit_area" id="name_<?= htmlspecialchars($group['id'] ?? '') ?>"><?= htmlspecialchars($group['group_name'] ?? '') ?></span></td>
						<td><span class="edit_area" id="admin_<?= htmlspecialchars($group['id'] ?? '') ?>"><?= htmlspecialchars($group['group_admin'] ?? '') ?></span></td>
						<td><span class="edit_area" id="email_<?= htmlspecialchars($group['id'] ?? '') ?>"><?= htmlspecialchars($group['group_email'] ?? '') ?></span></td>
						<td><?= htmlspecialchars($group['group_pass_clear'] ?? '') ?></td>
						<td>
							<?php
								$expiration_date = htmlspecialchars($group['expiration_date'] ?? '');
								if ($expiration_date == '0000-00-00') {
									echo 'Unknown';
								} elseif ($expiration_date == '9999-12-31') {
									echo 'Never';
								} else {
									if ($usertype == 'super') { 
										echo $expiration_date;
									} else {
										$date = new DateTime($expiration_date);
										echo $date->format('F j, Y');
									}
								}
							?>
						</td>
						<?php if ($usertype == 'super') { ?><td><?= nl2br(urldecode($group['group_institution_address'] ?? '')); ?></td><?php } ?>
						<td style="text-align:center;"><a href="#" class="edit-group" data-id="<?= htmlspecialchars($group['id'] ?? '') ?>" onclick="event.stopPropagation();">Edit</a></td>
						<?php if ($usertype == 'super') { ?><!-- <td><a href="deletegroup.php?id=<?= htmlspecialchars($group['id'] ?? '') ?>" onclick="return confirmDeleteGeneric();">Delete</a></td> --><?php } ?>
						<?php if ($userType == 'super'): ?>
							<td style="text-align:center;">
								<button class="visibility-toggle-btn" 
										data-id="<?= htmlspecialchars($group['id']) ?>" 
										data-type="group"
										data-status="<?= $group['is_hidden'] ? 'hidden' : 'visible' ?>">
									<?= $group['is_hidden'] ? 'Show' : 'Hide' ?>
								</button>
							</td>
						<?php endif; ?>
					</tr>
				<?php endforeach; ?>
			</table>
		<?php endif; ?>
		
		<?php /* main table */ ?>
        <table class="home-table<?php if ($usertype == 'super') { ?> 95-table<?php } ?>">
            <tr>
				<?php if ($usertype == 'super') { ?><th style="width:5%;">ID</th><?php } ?>
                <th width="20%">Group Name<?php if ($usertype == 'super') { ?>&nbsp;&nbsp;<a class="sort" href="groups.php?groupnamesort=<?= htmlspecialchars($groupnameSortNext ?? '') ?>"><?= htmlspecialchars($groupnameLabel ?? '') ?></a><?php } ?></th>
                <th width="20%">Admin Name<?php if ($usertype == 'super') { ?>&nbsp;&nbsp;<a class="sort" href="groups.php?adminnamesort=<?= htmlspecialchars($adminnameSortNext ?? '') ?>"><?= htmlspecialchars($adminnameLabel ?? '') ?></a><?php } ?></th>
                <th width="20%">Admin Email<?php if ($usertype == 'super') { ?>&nbsp;&nbsp;<a class="sort" href="groups.php?adminemailsort=<?= htmlspecialchars($adminemailSortNext ?? '') ?>"><?= htmlspecialchars($adminemailLabel ?? '') ?></a><?php } ?></th>
				<th style="text-align:center;" style="width:6%;text-align:center;">Group Password</a></th>
				<th style="width:20%;">Expires<?php if ($usertype == 'super') { ?>&nbsp;&nbsp;<a class="sort" href="groups.php?expirationsort=<?= htmlspecialchars($expirationSortNext ?? '') ?>"><?= htmlspecialchars($expirationLabel ?? '') ?></a><?php } ?></th>
                <?php if ($usertype == 'super') { ?><th width="20%">Group Address &amp; Contact</th><?php } ?>
                <th style="text-align:center;" width="3%">Edit</th>
                <?php if ($usertype == 'super') { ?><!-- <th width="3%">Delete</th> --><?php } ?>
				<?php if ($userType == 'super'): ?>
					<th style="text-align:center;">Visibility</th>
				<?php endif; ?>
            </tr>
            <?php foreach ($visibleGroups as $group): ?>
				<tr class="<?php echo $user['is_hidden'] ? 'hidden-row' : ''; ?>">
					<?php if ($usertype == 'super') { ?><td><?= htmlspecialchars($group['id']); ?></td><?php } ?>
                    <td><span class="edit_area" id="name_<?= htmlspecialchars($group['id'] ?? '') ?>"><?= htmlspecialchars($group['group_name'] ?? '') ?></span></td>
                    <td><span class="edit_area" id="admin_<?= htmlspecialchars($group['id'] ?? '') ?>"><?= htmlspecialchars($group['group_admin'] ?? '') ?></span></td>
					<td><span class="edit_area" id="email_<?= htmlspecialchars($group['id'] ?? '') ?>"><?= htmlspecialchars($group['group_email'] ?? '') ?></span></td>
					<td><?= htmlspecialchars($group['group_pass_clear'] ?? '') ?></td>
                    <td>
						<?php
							$expiration_date = htmlspecialchars($group['expiration_date'] ?? '');
							if ($expiration_date == '0000-00-00') {
								echo 'Unknown';
							} elseif ($expiration_date == '9999-12-31') {
								echo 'Never';
							} else {
								if ($usertype == 'super') { 
									echo $expiration_date;
								} else {
									$date = new DateTime($expiration_date);
									echo $date->format('F j, Y');
								}
							}
						?>
					</td>
                    <?php if ($usertype == 'super') { ?><td><?= nl2br(urldecode($group['group_institution_address'] ?? '')); ?></td><?php } ?>
                    <td style="text-align:center;"><a href="#" class="edit-group" data-id="<?= htmlspecialchars($group['id'] ?? '') ?>" onclick="event.stopPropagation();">Edit</a></td>
                    <?php if ($usertype == 'super') { ?><!-- <td><a href="deletegroup.php?id=<?= htmlspecialchars($group['id'] ?? '') ?>" onclick="return confirmDeleteGeneric();">Delete</a></td> --><?php } ?>
                	<?php if ($userType === 'super' || ($userType === 'admin' && isset($user['user_group']) && $group['group_name'] === $user['user_group'])): ?>
					<?php if ($usertype == 'super') { ?>
					<td style="text-align:center;">
						<button class="visibility-toggle-btn" 
								data-id="<?= htmlspecialchars($group['id']) ?>" 
								data-type="group"
								data-status="<?= $group['is_hidden'] ? 'hidden' : 'visible' ?>">
							<?= $group['is_hidden'] ? 'Show' : 'Hide' ?>
						</button>
					</td>
					<?php } ?>
				<?php endif; ?>
				</tr>
            <?php endforeach; ?>
        </table>
    </div>
	
<div id="editGroupModal" class="modal" style="display:none;">
    <div class="modal-content">
        <span class="close">&times;</span>
        <h2>Edit Group</h2>
        <form id="editGroupForm">
            <input type="hidden" id="groupId" name="groupId">
            <?php if ($usertype == 'super') { ?>
                <?php /* <label for="groupName">Group Name:</label>
                <select name="groupName" id="groupName" class="form-control">
                    <?php foreach ($groups as $group): ?>
                        <option value="<?= htmlspecialchars($group['group_name']); ?>">
                            <?= htmlspecialchars($group['group_name']); ?>
                        </option>
                    <?php endforeach; ?>
                </select> */ ?>
				<div id="groupName" name="groupName" class="modal-static"><?= htmlspecialchars($group['group_name']); ?></div>
				<label for="expirationDate">Expiration Date:</label>
				<input type="date" id="expirationDate" name="expirationDate">
				<label for="groupStatus">Group Status:</label>
				<select id="groupStatus" name="groupStatus">
					<option value="Active">Active</option>
					<option value="Expired">Expired</option>
				</select>
             <?php } else { /* non-editable for everyone but super admins */ ?>
				<div id="groupStatus" name="groupStatus" class="modal-static license-<?= htmlspecialchars(strtolower($license)); ?>"><?= htmlspecialchars($license); ?> License</div>
				<div id="groupName" name="groupName" class="modal-static"><?= htmlspecialchars($group['group_name']); ?></div>
             <?php } ?>
            <label for="groupAdmin">Admin Name:</label>
            <input type="text" id="groupAdmin" name="groupAdmin">
            <label for="groupEmail">Admin Email:</label>
            <input type="email" id="groupEmail" name="groupEmail" required>
             <?php if ($usertype == 'super') { ?>
				<label for="groupPassword">Group Password (only super admin can change):</label>
				<input type="text" id="groupPassword" name="groupPassword">
             <?php } ?>
			<label for="groupInstitutionAddress">Group Address & Contact:</label>
			<textarea id="groupInstitutionAddress" name="groupInstitutionAddress"></textarea>
            <button type="submit">Save Changes</button>
        </form>
    </div>
</div>

<script>
$(document).ready(function() {
    var modal = document.getElementById("editGroupModal");
    var span = document.getElementsByClassName("close")[0];
    var isSuper = $('body').hasClass('super-admin');

    $('.edit-group').on('click', function(e) {
        e.preventDefault();
        var groupId = $(this).data('id');
        $.get('../api/get-group-details.php', {id: groupId}, function(data) {
            try {
                data = JSON.parse(data);
                $('#groupId').val(data.id);
                $('#groupName').text(data.group_name);
                $('#groupAdmin').val(data.group_admin);
                $('#groupEmail').val(data.group_email);
                $('#expirationDate').val(data.expiration_date);
                $('#groupInstitutionAddress').val(data.group_institution_address);
                $('#groupPassword').val(data.group_pass_clear);
                $('#groupStatus').val(data.group_status);
                modal.style.display = "block";
            } catch (error) {
                console.error("Error parsing JSON:", error);
            }
        });
    });

    span.onclick = function() {
        modal.style.display = "none";
    }

    $('.close').on('click', function() {
        modal.style.display = "none";
    });

    window.onclick = function(event) {
        if (event.target == modal) {
            modal.style.display = "none";
        }
    }

$('#editGroupForm').on('submit', function(e) {
    e.preventDefault();
    var formData = $(this).serializeArray();
	console.log(formData);
    
    $.ajax({
        url: 'inc/update-group.php',
        method: 'POST',
        data: formData,
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                // Update the form fields
                $('#groupName').text(response.data.group_name);
                $('#groupAdmin').val(response.data.group_admin);
                $('#groupEmail').val(response.data.group_email);
                $('#expirationDate').val(response.data.expiration_date);
                $('#groupStatus').val(response.data.group_status);
                $('#groupInstitutionAddress').val(response.data.group_institution_address);
                $('#groupPassword').val(response.data.group_pass_clear);
                
                // Update the table row
                var $row = $('a.edit-group[data-id="' + $('#groupId').val() + '"]').closest('tr');
                var userType = '<?php echo $_SESSION['user_type']; ?>';
				if (userType === 'super') {
					$row.find('td:eq(0)').text(response.data.id);
					$row.find('td:eq(1)').text(response.data.group_name);
					$row.find('td:eq(2)').text(response.data.group_admin);
					$row.find('td:eq(3)').text(response.data.group_email);
					$row.find('td:eq(4)').text(response.data.group_pass_clear);
					$row.find('td:eq(5)').text(response.data.expiration_date);
					$row.find('td:eq(6)').html(response.data.group_institution_address.replace(/\n/g, '<br>'));
				} else {
					$row.find('td:eq(0)').text(response.data.group_name);
					$row.find('td:eq(1)').text(response.data.group_admin);
					$row.find('td:eq(2)').text(response.data.group_email);
					$row.find('td:eq(3)').text(response.data.group_pass_clear);
					$row.find('td:eq(4)').text(formatDate(response.data.expiration_date));
				}
                
                // Close the modal
                $('#editGroupModal').hide();
                $('body').removeClass('modal-open');
                $('.modal-backdrop').remove();
            } else {
                console.error('Error updating group:', response.error || 'Unknown error');
            }
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.error('AJAX error:', textStatus, errorThrown);
        }
    });
});
});

function updateCell($cell, value) {
    if (value === null || value === undefined || value === "") {
        $cell.empty();
    } else {
        $cell.text(value);
    }
}

function formatExpirationDate(date) {
    if (!date || date === '0000-00-00') {
        return 'Unknown';
    } else if (date === '9999-12-31') {
        return 'Never';
    } else {
        var d = new Date(date);
        if (isSuper) {
            return date; // Keep the original format for super admin
        } else {
            return d.toLocaleString('default', { month: 'long' }) + ' ' + d.getDate() + ', ' + d.getFullYear();
        }
    }
}

function nl2br(str) {
    return str ? (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1<br>$2') : '';
}

function confirmDeleteGeneric() {
    return confirm("Are You Sure You Want To Delete? There is no undo!");
}
</script>

<?php include($_SERVER['DOCUMENT_ROOT'] . '/admin/footer.php'); ?>

</body>
</html>