<?php
// Permission checking is handled by the permission system in auto-prepend.php

require_once('/docker/whp/web/libs/delegated_user_manager.php');
$delegatedUserManager = new DelegatedUserManager();

$message = '';
$message_type = '';

// Get current user info
$current_user = $_SESSION['user'];
$is_root = ($current_user === 'root');
$is_delegated_user = isset($_SESSION['user_type']) && $_SESSION['user_type'] === 'delegated';
$delegated_username = $_SESSION['delegated_user'] ?? null;

// Handle form submissions (only for non-delegated users)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !$is_delegated_user) {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'create_delegated_user':
                $data = [
                    'username' => $_POST['username'] ?? '',
                    'password' => $_POST['password'] ?? '',
                    'parent_username' => $_POST['parent_username'] ?? $current_user,
                    'display_name' => $_POST['display_name'] ?? '',
                    'email' => $_POST['email'] ?? '',
                    'can_manage_domains' => isset($_POST['can_manage_domains']),
                    'can_manage_sites' => isset($_POST['can_manage_sites']),
                    'can_manage_databases' => isset($_POST['can_manage_databases']),
                    'can_manage_email' => isset($_POST['can_manage_email']),
                    'can_manage_files' => isset($_POST['can_manage_files']),
                    'can_manage_backups' => isset($_POST['can_manage_backups']),
                    'can_view_terminal' => isset($_POST['can_view_terminal']),
                    'can_manage_wordpress' => isset($_POST['can_manage_wordpress']),
                ];
                
                
                $result = $delegatedUserManager->createDelegatedUser($data, $current_user);
                
                if ($result['success']) {
                    $message = 'Delegated user created successfully: ' . htmlspecialchars($_POST['username']);
                    $message_type = 'success';
                } else {
                    $message = 'Error creating delegated user: ' . htmlspecialchars($result['message']);
                    $message_type = 'danger';
                }
                break;
                
            case 'update_delegated_user':
                $user_id = intval($_POST['user_id']);
                $data = [
                    'display_name' => $_POST['display_name'] ?? '',
                    'email' => $_POST['email'] ?? '',
                    'can_manage_domains' => isset($_POST['can_manage_domains']),
                    'can_manage_sites' => isset($_POST['can_manage_sites']),
                    'can_manage_databases' => isset($_POST['can_manage_databases']),
                    'can_manage_email' => isset($_POST['can_manage_email']),
                    'can_manage_files' => isset($_POST['can_manage_files']),
                    'can_manage_backups' => isset($_POST['can_manage_backups']),
                    'can_view_terminal' => isset($_POST['can_view_terminal']),
                    'can_manage_wordpress' => isset($_POST['can_manage_wordpress']),
                    'is_active' => isset($_POST['is_active']),
                ];
                
                
                $result = $delegatedUserManager->updateDelegatedUser($user_id, $data, $current_user);
                
                if ($result['success']) {
                    $message = 'Delegated user updated successfully';
                    $message_type = 'success';
                } else {
                    $message = 'Error updating delegated user: ' . htmlspecialchars($result['message']);
                    $message_type = 'danger';
                }
                break;
                
            case 'delete_delegated_user':
                $user_id = intval($_POST['user_id']);
                $result = $delegatedUserManager->deleteDelegatedUser($user_id, $current_user);
                
                if ($result['success']) {
                    $message = 'Delegated user deleted successfully';
                    $message_type = 'success';
                } else {
                    $message = 'Error deleting delegated user: ' . htmlspecialchars($result['message']);
                    $message_type = 'danger';
                }
                break;
        }
    }
}

// Get delegated users for the current user
if ($is_delegated_user) {
    // If delegated user, only show their own info
    $parent_username = $current_user;
    $all_delegated_users = $delegatedUserManager->getDelegatedUsers($parent_username, true);
    $delegated_users = array_filter($all_delegated_users, function($user) use ($delegated_username) {
        return $user['username'] === $delegated_username;
    });
} else {
    $parent_username = $is_root && !empty($_GET['parent_user']) ? $_GET['parent_user'] : $current_user;
    
    if ($is_root && (empty($_GET['parent_user']) || $_GET['parent_user'] === '')) {
        // Root user with "All Users" selected - show all delegated users across all parents
        $delegated_users = $delegatedUserManager->getAllDelegatedUsers(true);
    } else {
        // Specific parent user selected or regular user viewing their own
        $delegated_users = $delegatedUserManager->getDelegatedUsers($parent_username, true);
    }
}

// Get list of available parent users (only for root)
$available_parents = [];
if ($is_root) {
    require_once('/docker/whp/web/libs/usermgmt.php');
    $UserMgmt = new usermgmt();
    $all_users = $UserMgmt->list_users();
    $available_parents = array_filter($all_users, function($user) {
        return $user['uid'] >= 1000 && !$user['protected'];
    });
}
?>

<style>
.permission-checkbox-group {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 15px;
    margin: 15px 0;
}

.permission-checkbox {
    display: flex;
    align-items: center;
    padding: 12px;
    border: 1px solid #dee2e6;
    border-radius: 6px;
    background: var(--whp-card-bg);
    box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.permission-checkbox input[type="checkbox"] {
    margin-right: 10px;
    transform: scale(1.1);
}

.permission-checkbox label {
    color: var(--whp-content-text);
    font-weight: 500;
    margin-bottom: 0;
    cursor: pointer;
}

.delegated-user-card {
    border-left: 4px solid #007bff;
}

.inactive-user-card {
    border-left: 4px solid #dc3545;
    opacity: 0.7;
}

.user-permissions {
    display: flex;
    flex-wrap: wrap;
    gap: 5px;
    margin-top: 10px;
}

.permission-badge {
    background: #e3f2fd;
    color: #1976d2;
    padding: 3px 8px;
    border-radius: 12px;
}

.form-text {
    color: #ffffff !important;
    opacity: 0.9;
    font-size: 0.75rem;
}
</style>

<?php if (!empty($message)): ?>
<div class="row">
    <div class="col-sm-12">
        <div class="alert alert-<?php echo $message_type; ?> alert-dismissible" role="alert">
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            <?php echo $message; ?>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- Header -->
<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="fa fa-users"></i> Delegated Users Management
                    <?php if ($is_root && $parent_username !== 'root'): ?>
                        - Managing for: <?php echo htmlspecialchars($parent_username); ?>
                    <?php endif; ?>
                </h5>
            </div>
            <div class="card-body">
                <?php if ($is_delegated_user): ?>
                <p class="card-text">
                    You are logged in as a delegated user: <strong><?php echo htmlspecialchars($delegated_username); ?></strong><br>
                    Parent account: <strong><?php echo htmlspecialchars($current_user); ?></strong><br>
                    This page shows your account information and permissions.
                </p>
                <?php else: ?>
                <p class="card-text">
                    Delegated users are team members who can access specific features within your account.
                    Grant role-based permissions to collaborators without sharing your main account credentials.
                    Team members work with your existing resources based on their assigned permissions.
                </p>
                <?php endif; ?>
                
                <?php if ($is_root): ?>
                <div class="mb-3">
                    <label for="parent_user_filter" class="form-label">View delegated users for:</label>
                    <select class="form-select" id="parent_user_filter" onchange="filterByParent()">
                        <option value="">All Users</option>
                        <?php foreach ($available_parents as $user): ?>
                            <option value="<?php echo htmlspecialchars($user['username']); ?>" 
                                    <?php echo ($parent_username === $user['username']) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($user['username']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<?php if (!$is_delegated_user): ?>
<!-- Create Delegated User Form -->
<div class="row mt-4">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">Add Team Member</h5>
            </div>
            <div class="card-body">
                <form method="POST" action="">
                    <input type="hidden" name="action" value="create_delegated_user">
                    <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="username" class="form-label">Username *</label>
                                <input type="text" class="form-control" id="username" name="username" 
                                       pattern="[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9]" 
                                       minlength="3" maxlength="32" required>
                                <div class="form-text">3-32 characters, letters, numbers, dots, underscores, hyphens</div>
                            </div>
                            
                            <div class="mb-3">
                                <label for="password" class="form-label">Password *</label>
                                <input type="password" class="form-control" id="password" name="password" 
                                       minlength="8" required>
                                <div class="form-text">Minimum 8 characters</div>
                            </div>
                            
                            <?php if ($is_root): ?>
                            <div class="mb-3">
                                <label for="parent_username" class="form-label">Parent User *</label>
                                <select class="form-select" id="parent_username" name="parent_username" required>
                                    <?php foreach ($available_parents as $user): ?>
                                        <option value="<?php echo htmlspecialchars($user['username']); ?>"
                                                <?php echo ($parent_username === $user['username']) ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($user['username']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <?php else: ?>
                            <input type="hidden" name="parent_username" value="<?php echo htmlspecialchars($current_user); ?>">
                            <?php endif; ?>
                            
                            <div class="mb-3">
                                <label for="display_name" class="form-label">Display Name</label>
                                <input type="text" class="form-control" id="display_name" name="display_name" maxlength="100">
                            </div>
                            
                            <div class="mb-3">
                                <label for="email" class="form-label">Email</label>
                                <input type="email" class="form-control" id="email" name="email" maxlength="255">
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Permissions</label>
                                <div class="permission-checkbox-group">
                                    <div class="permission-checkbox">
                                        <input type="checkbox" id="can_manage_domains" name="can_manage_domains" class="form-check-input">
                                        <label for="can_manage_domains" class="form-check-label">Manage Domains</label>
                                    </div>
                                    <div class="permission-checkbox">
                                        <input type="checkbox" id="can_manage_sites" name="can_manage_sites" class="form-check-input">
                                        <label for="can_manage_sites" class="form-check-label">Manage Sites</label>
                                    </div>
                                    <div class="permission-checkbox">
                                        <input type="checkbox" id="can_manage_databases" name="can_manage_databases" class="form-check-input">
                                        <label for="can_manage_databases" class="form-check-label">Manage Databases</label>
                                    </div>
                                    <div class="permission-checkbox">
                                        <input type="checkbox" id="can_manage_email" name="can_manage_email" class="form-check-input">
                                        <label for="can_manage_email" class="form-check-label">Manage Email</label>
                                    </div>
                                    <div class="permission-checkbox">
                                        <input type="checkbox" id="can_manage_files" name="can_manage_files" class="form-check-input">
                                        <label for="can_manage_files" class="form-check-label">Manage Files</label>
                                    </div>
                                    <div class="permission-checkbox">
                                        <input type="checkbox" id="can_manage_backups" name="can_manage_backups" class="form-check-input">
                                        <label for="can_manage_backups" class="form-check-label">Manage Backups</label>
                                    </div>
                                    <div class="permission-checkbox">
                                        <input type="checkbox" id="can_view_terminal" name="can_view_terminal" class="form-check-input">
                                        <label for="can_view_terminal" class="form-check-label">Access Terminal</label>
                                    </div>
                                    <div class="permission-checkbox">
                                        <input type="checkbox" id="can_manage_wordpress" name="can_manage_wordpress" class="form-check-input">
                                        <label for="can_manage_wordpress" class="form-check-label">Manage WordPress</label>
                                    </div>
                                </div>
                            </div>
                            
                        </div>
                    </div>
                    
                    <button type="submit" class="btn btn-primary">Add Team Member</button>
                </form>
            </div>
        </div>
    </div>
</div>
<?php endif; // End if not delegated user ?>

<!-- Delegated Users List -->
<div class="row mt-4">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <?php if ($is_delegated_user): ?>
                        Your Account Information
                    <?php else: ?>
                        Existing Delegated Users
                    <?php endif; ?>
                </h5>
            </div>
            <div class="card-body">
                <?php if (empty($delegated_users)): ?>
                    <div class="text-center text-muted py-4">
                        <i class="fa fa-users fa-3x mb-3"></i>
                        <p>No delegated users found for this account.</p>
                    </div>
                <?php else: ?>
                    <div class="row">
                        <?php foreach ($delegated_users as $user): ?>
                            <div class="col-md-6 col-lg-4 mb-3">
                                <div class="card <?php echo $user['is_active'] ? 'delegated-user-card' : 'inactive-user-card'; ?>">
                                    <div class="card-body">
                                        <div class="d-flex justify-content-between align-items-start mb-2">
                                            <h6 class="card-title mb-0">
                                                <?php echo htmlspecialchars($user['username']); ?>
                                                <?php if (!$user['is_active']): ?>
                                                    <span class="badge bg-danger ms-2">Inactive</span>
                                                <?php endif; ?>
                                            </h6>
                                            <?php if (!$is_delegated_user): ?>
                                            <div class="dropdown">
                                                <button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown">
                                                    <i class="fa fa-cog"></i>
                                                </button>
                                                <ul class="dropdown-menu">
                                                    <li><a class="dropdown-item" href="#" onclick="editUser(<?php echo $user['id']; ?>)">
                                                        <i class="fa fa-edit"></i> Edit
                                                    </a></li>
                                                    <li><a class="dropdown-item text-danger" href="#" onclick="deleteUser(<?php echo $user['id']; ?>, '<?php echo htmlspecialchars($user['username']); ?>')">
                                                        <i class="fa fa-trash"></i> Delete
                                                    </a></li>
                                                </ul>
                                            </div>
                                            <?php endif; ?>
                                        </div>
                                        
                                        <?php if ($user['display_name']): ?>
                                            <p class="card-text small text-muted mb-1"><?php echo htmlspecialchars($user['display_name']); ?></p>
                                        <?php endif; ?>
                                        
                                        <?php if ($user['email']): ?>
                                            <p class="card-text small text-muted mb-2"><?php echo htmlspecialchars($user['email']); ?></p>
                                        <?php endif; ?>
                                        
                                        <div class="user-permissions">
                                            <?php
                                            $permissions = [];
                                            if ($user['can_manage_domains']) $permissions[] = 'Domains';
                                            if ($user['can_manage_sites']) $permissions[] = 'Sites';
                                            if ($user['can_manage_databases']) $permissions[] = 'Databases';
                                            if ($user['can_manage_email']) $permissions[] = 'Email';
                                            if ($user['can_manage_files']) $permissions[] = 'Files';
                                            if ($user['can_manage_backups']) $permissions[] = 'Backups';
                                            if ($user['can_view_terminal']) $permissions[] = 'Terminal';
                                            if ($user['can_manage_wordpress']) $permissions[] = 'WordPress';
                                            
                                            foreach ($permissions as $permission):
                                            ?>
                                                <span class="permission-badge"><?php echo $permission; ?></span>
                                            <?php endforeach; ?>
                                        </div>
                                        
                                        <div class="mt-2 small text-muted">
                                            Created: <?php echo whp_local_time($user['created_at'], 'M j, Y'); ?>
                                            <?php if ($user['last_login']): ?>
                                                <br>Last login: <?php echo whp_local_time($user['last_login'], 'M j, Y g:i A'); ?>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- Edit User Modal -->
<div class="modal fade" id="editUserModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Edit Delegated User</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" action="">
                <div class="modal-body">
                    <input type="hidden" name="action" value="update_delegated_user">
                    <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                    <input type="hidden" name="user_id" id="edit_user_id">
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="edit_display_name" class="form-label">Display Name</label>
                                <input type="text" class="form-control" id="edit_display_name" name="display_name" maxlength="100">
                            </div>
                            
                            <div class="mb-3">
                                <label for="edit_email" class="form-label">Email</label>
                                <input type="email" class="form-control" id="edit_email" name="email" maxlength="255">
                            </div>
                            
                            <div class="mb-3">
                                <div class="form-check">
                                    <input type="checkbox" class="form-check-input" id="edit_is_active" name="is_active">
                                    <label class="form-check-label" for="edit_is_active">Account Active</label>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Permissions</label>
                                <div class="permission-checkbox-group">
                                    <div class="permission-checkbox">
                                        <input type="checkbox" id="edit_can_manage_domains" name="can_manage_domains" class="form-check-input">
                                        <label for="edit_can_manage_domains" class="form-check-label">Manage Domains</label>
                                    </div>
                                    <div class="permission-checkbox">
                                        <input type="checkbox" id="edit_can_manage_sites" name="can_manage_sites" class="form-check-input">
                                        <label for="edit_can_manage_sites" class="form-check-label">Manage Sites</label>
                                    </div>
                                    <div class="permission-checkbox">
                                        <input type="checkbox" id="edit_can_manage_databases" name="can_manage_databases" class="form-check-input">
                                        <label for="edit_can_manage_databases" class="form-check-label">Manage Databases</label>
                                    </div>
                                    <div class="permission-checkbox">
                                        <input type="checkbox" id="edit_can_manage_email" name="can_manage_email" class="form-check-input">
                                        <label for="edit_can_manage_email" class="form-check-label">Manage Email</label>
                                    </div>
                                    <div class="permission-checkbox">
                                        <input type="checkbox" id="edit_can_manage_files" name="can_manage_files" class="form-check-input">
                                        <label for="edit_can_manage_files" class="form-check-label">Manage Files</label>
                                    </div>
                                    <div class="permission-checkbox">
                                        <input type="checkbox" id="edit_can_manage_backups" name="can_manage_backups" class="form-check-input">
                                        <label for="edit_can_manage_backups" class="form-check-label">Manage Backups</label>
                                    </div>
                                    <div class="permission-checkbox">
                                        <input type="checkbox" id="edit_can_view_terminal" name="can_view_terminal" class="form-check-input">
                                        <label for="edit_can_view_terminal" class="form-check-label">Access Terminal</label>
                                    </div>
                                    <div class="permission-checkbox">
                                        <input type="checkbox" id="edit_can_manage_wordpress" name="can_manage_wordpress" class="form-check-input">
                                        <label for="edit_can_manage_wordpress" class="form-check-label">Manage WordPress</label>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label for="edit_max_domains" class="form-label">Max Domains</label>
                                <input type="number" class="form-control" id="edit_max_domains" name="max_domains" min="0">
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label for="edit_max_databases" class="form-label">Max Databases</label>
                                <input type="number" class="form-control" id="edit_max_databases" name="max_databases" min="0">
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label for="edit_max_email_accounts" class="form-label">Max Email Accounts</label>
                                <input type="number" class="form-control" id="edit_max_email_accounts" name="max_email_accounts" min="0">
                            </div>
                        </div>
                    </div>
                    
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Update User</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteUserModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Confirm Deletion</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to delete the delegated user <strong id="delete_username"></strong>?</p>
                <p class="text-danger">This action cannot be undone.</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <form method="POST" action="" style="display: inline;">
                    <input type="hidden" name="action" value="delete_delegated_user">
                    <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                    <input type="hidden" name="user_id" id="delete_user_id">
                    <button type="submit" class="btn btn-danger">Delete User</button>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
// Store user data for editing
const userData = <?php echo json_encode($delegated_users); ?>;

function editUser(userId) {
    const user = userData.find(u => u.id == userId);
    if (!user) return;
    
    // Populate the form
    document.getElementById('edit_user_id').value = user.id;
    document.getElementById('edit_display_name').value = user.display_name || '';
    document.getElementById('edit_email').value = user.email || '';
    document.getElementById('edit_is_active').checked = user.is_active == 1;
    
    // Set permissions
    document.getElementById('edit_can_manage_domains').checked = user.can_manage_domains == 1;
    document.getElementById('edit_can_manage_sites').checked = user.can_manage_sites == 1;
    document.getElementById('edit_can_manage_databases').checked = user.can_manage_databases == 1;
    document.getElementById('edit_can_manage_email').checked = user.can_manage_email == 1;
    document.getElementById('edit_can_manage_files').checked = user.can_manage_files == 1;
    document.getElementById('edit_can_manage_backups').checked = user.can_manage_backups == 1;
    document.getElementById('edit_can_view_terminal').checked = user.can_view_terminal == 1;
    document.getElementById('edit_can_manage_wordpress').checked = user.can_manage_wordpress == 1;
    
    
    // Show modal
    new bootstrap.Modal(document.getElementById('editUserModal')).show();
}

function deleteUser(userId, username) {
    document.getElementById('delete_user_id').value = userId;
    document.getElementById('delete_username').textContent = username;
    new bootstrap.Modal(document.getElementById('deleteUserModal')).show();
}

function filterByParent() {
    const select = document.getElementById('parent_user_filter');
    const parentUser = select.value;
    const url = new URL(window.location);
    
    if (parentUser) {
        url.searchParams.set('parent_user', parentUser);
    } else {
        url.searchParams.delete('parent_user');
    }
    
    window.location.href = url.toString();
}

// Username validation
document.getElementById('username').addEventListener('input', function() {
    const username = this.value;
    if (username.length >= 3) {
        // Could add real-time username availability check here
    }
});
</script>