<?php
require_once 'auth_rbac.php';
requirePermission('users', 'view');

$pageTitle = 'User Management';
$currentPage = 'users';

// Handle form submissions
$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $currentUser = getCurrentUser();
    
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'create_user':
                if (hasPermission('users', 'create')) {
                    $username = trim($_POST['username']);
                    $password = $_POST['password'];
                    $fullName = trim($_POST['full_name']);
                    $email = trim($_POST['email']);
                    $role = $_POST['role'];
                    
                    if (strlen($password) < 8) {
                        $message = 'Password must be at least 8 characters long.';
                        $messageType = 'error';
                    } else {
                        try {
                            $db = getDBConnection();
                            $stmt = $db->prepare("INSERT INTO admin_users (username, password_hash, full_name, email, role, created_by) VALUES (?, ?, ?, ?, ?, ?)");
                            $passwordHash = password_hash($password, PASSWORD_DEFAULT);
                            
                            if ($stmt->execute([$username, $passwordHash, $fullName, $email, $role, $currentUser['id']])) {
                                $message = 'User created successfully.';
                                $messageType = 'success';
                                logActivity('create_user', 'admin_users', $db->lastInsertId(), "Created user: $username");
                            } else {
                                $message = 'Failed to create user.';
                                $messageType = 'error';
                            }
                        } catch (Exception $e) {
                            if (strpos($e->getMessage(), 'Duplicate entry') !== false) {
                                $message = 'Username already exists.';
                            } else {
                                $message = 'Error creating user: ' . $e->getMessage();
                            }
                            $messageType = 'error';
                        }
                    }
                }
                break;
                
            case 'edit_user':
                if (hasPermission('users', 'edit')) {
                    $userId = $_POST['user_id'];
                    $fullName = trim($_POST['full_name']);
                    $email = trim($_POST['email']);
                    $role = $_POST['role'];
                    $isActive = isset($_POST['is_active']) ? 1 : 0;
                    
                    try {
                        $db = getDBConnection();
                        $stmt = $db->prepare("UPDATE admin_users SET full_name = ?, email = ?, role = ?, is_active = ? WHERE id = ?");
                        
                        if ($stmt->execute([$fullName, $email, $role, $isActive, $userId])) {
                            $message = 'User updated successfully.';
                            $messageType = 'success';
                            logActivity('edit_user', 'admin_users', $userId, "Updated user details");
                        } else {
                            $message = 'Failed to update user.';
                            $messageType = 'error';
                        }
                    } catch (Exception $e) {
                        $message = 'Error updating user: ' . $e->getMessage();
                        $messageType = 'error';
                    }
                }
                break;
                
            case 'reset_password':
                if (hasPermission('users', 'edit')) {
                    $userId = $_POST['user_id'];
                    $newPassword = $_POST['new_password'];
                    
                    if (strlen($newPassword) < 8) {
                        $message = 'Password must be at least 8 characters long.';
                        $messageType = 'error';
                    } else {
                        try {
                            $db = getDBConnection();
                            $stmt = $db->prepare("UPDATE admin_users SET password_hash = ? WHERE id = ?");
                            $passwordHash = password_hash($newPassword, PASSWORD_DEFAULT);
                            
                            if ($stmt->execute([$passwordHash, $userId])) {
                                $message = 'Password reset successfully.';
                                $messageType = 'success';
                                logActivity('reset_password', 'admin_users', $userId, "Password reset");
                            } else {
                                $message = 'Failed to reset password.';
                                $messageType = 'error';
                            }
                        } catch (Exception $e) {
                            $message = 'Error resetting password: ' . $e->getMessage();
                            $messageType = 'error';
                        }
                    }
                }
                break;
        }
    }
}

// Fetch all users
try {
    $db = getDBConnection();
    $stmt = $db->prepare("
        SELECT u.*, creator.username as created_by_username 
        FROM admin_users u 
        LEFT JOIN admin_users creator ON u.created_by = creator.id 
        ORDER BY u.created_at DESC
    ");
    $stmt->execute();
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $users = [];
    $message = 'Error fetching users: ' . $e->getMessage();
    $messageType = 'error';
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $pageTitle; ?> - XChange Admin</title>
    <?php include '../includes/favicon.php'; ?>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700;800;900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="../styles.css">
    <link rel="stylesheet" href="admin.css">
</head>
<body>
    <?php include 'includes/admin_nav.php'; ?>
    
    <div class="admin-content">
        <div class="page-header">
            <h1 class="page-title">
                <i class="fas fa-user-cog"></i> User Management
            </h1>
            <?php if (hasPermission('users', 'create')): ?>
            <button onclick="openCreateModal()" class="btn btn-primary">
                <i class="fas fa-plus"></i> Add New User
            </button>
            <?php endif; ?>
        </div>

        <?php if ($message): ?>
        <div class="alert alert-<?php echo $messageType; ?>">
            <?php echo htmlspecialchars($message); ?>
        </div>
        <?php endif; ?>

        <!-- Users Table -->
        <div class="data-table">
            <h2>Admin Users (<?php echo count($users); ?> total)</h2>
            <div class="table-container">
                <table class="table">
                        <thead>
                            <tr>
                                <th>Username</th>
                                <th>Full Name</th>
                                <th>Email</th>
                                <th>Role</th>
                                <th>Status</th>
                                <th>Last Login</th>
                                <th>Created</th>
                                <?php if (hasPermission('users', 'edit')): ?>
                                <th>Actions</th>
                                <?php endif; ?>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($users as $user): ?>
                            <tr>
                                <td>
                                    <strong><?php echo htmlspecialchars($user['username']); ?></strong>
                                    <?php if ($user['id'] == getCurrentUser()['id']): ?>
                                    <span class="badge badge-secondary">You</span>
                                    <?php endif; ?>
                                </td>
                                <td><?php echo htmlspecialchars($user['full_name']); ?></td>
                                <td><?php echo htmlspecialchars($user['email']); ?></td>
                                <td>
                                    <?php
                                    $roleClass = '';
                                    switch($user['role']) {
                                        case 'super_admin': $roleClass = 'badge-danger'; break;
                                        case 'manager': $roleClass = 'badge-warning'; break;
                                        case 'viewer': $roleClass = 'badge-secondary'; break;
                                    }
                                    ?>
                                    <span class="badge <?php echo $roleClass; ?>">
                                        <?php echo AdminAuth::getRoleDisplayName($user['role']); ?>
                                    </span>
                                </td>
                                <td>
                                    <span class="badge <?php echo $user['is_active'] ? 'badge-success' : 'badge-danger'; ?>">
                                        <?php echo $user['is_active'] ? 'Active' : 'Inactive'; ?>
                                    </span>
                                </td>
                                <td>
                                    <?php echo $user['last_login'] ? date('M j, Y g:i A', strtotime($user['last_login'])) : 'Never'; ?>
                                </td>
                                <td>
                                    <?php echo date('M j, Y', strtotime($user['created_at'])); ?>
                                    <?php if ($user['created_by_username']): ?>
                                    <br><small>by <?php echo htmlspecialchars($user['created_by_username']); ?></small>
                                    <?php endif; ?>
                                </td>
                                <?php if (hasPermission('users', 'edit')): ?>
                                <td>
                                    <button onclick="openEditModal(<?php echo htmlspecialchars(json_encode($user)); ?>)" 
                                            class="btn btn-secondary btn-compact" title="Edit User">
                                        Edit
                                    </button>
                                    <button onclick="openPasswordModal(<?php echo $user['id']; ?>, '<?php echo htmlspecialchars($user['username']); ?>')" 
                                            class="btn btn-secondary btn-compact" title="Reset Password" style="margin-left: 8px;">
                                        Reset
                                    </button>
                                </td>
                                <?php endif; ?>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- Create User Modal -->
    <div id="createModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">Create New User</h3>
                <button type="button" class="close" onclick="closeModal('createModal')">&times;</button>
            </div>
            <form method="POST">
                <input type="hidden" name="action" value="create_user">
                
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">Username</label>
                        <input type="text" name="username" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Password</label>
                        <input type="password" name="password" class="form-control" required minlength="8">
                    </div>
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">Full Name</label>
                        <input type="text" name="full_name" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Email</label>
                        <input type="email" name="email" class="form-control" required>
                    </div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Role</label>
                    <select name="role" class="form-control" required>
                        <?php foreach (AdminAuth::getAllRoles() as $roleKey => $roleLabel): ?>
                        <option value="<?php echo $roleKey; ?>"><?php echo $roleLabel; ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="form-actions">
                    <button type="button" onclick="closeModal('createModal')" class="btn btn-secondary">Cancel</button>
                    <button type="submit" class="btn btn-success">Create User</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Edit User Modal -->
    <div id="editModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">Edit User</h3>
                <button type="button" class="close" onclick="closeModal('editModal')">&times;</button>
            </div>
            <form method="POST">
                <input type="hidden" name="action" value="edit_user">
                <input type="hidden" name="user_id" id="edit_user_id">
                
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">Username</label>
                        <input type="text" id="edit_username" class="form-control" readonly>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Full Name</label>
                        <input type="text" name="full_name" id="edit_full_name" class="form-control" required>
                    </div>
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">Email</label>
                        <input type="email" name="email" id="edit_email" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Role</label>
                        <select name="role" id="edit_role" class="form-control" required>
                            <?php foreach (AdminAuth::getAllRoles() as $roleKey => $roleLabel): ?>
                            <option value="<?php echo $roleKey; ?>"><?php echo $roleLabel; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                
                <div class="form-group">
                    <div class="checkbox-group">
                        <input type="checkbox" name="is_active" id="edit_is_active" value="1">
            			<label for="edit_is_active" class="form-label">Active User</label>
                    </div>
                </div>
                
                <div style="display: flex; gap: 1rem; justify-content: flex-end; margin-top: 2rem;">
                    <button type="button" onclick="closeModal('editModal')" class="btn btn-secondary">Cancel</button>
                    <button type="submit" class="btn btn-success">Update User</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Reset Password Modal -->
    <div id="passwordModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">Reset Password</h3>
                <button type="button" class="close" onclick="closeModal('passwordModal')">&times;</button>
            </div>
            <form method="POST">
                <input type="hidden" name="action" value="reset_password">
                <input type="hidden" name="user_id" id="password_user_id">
                
                <div class="form-group">
                    <label class="form-label">Username</label>
                    <input type="text" id="password_username" class="form-control readonly-input" readonly>
                </div>
                
                <div class="form-group">
                    <label class="form-label">New Password</label>
                    <input type="password" name="new_password" class="form-control" required minlength="8">
                    <small class="muted">Minimum 8 characters</small>
                </div>
                
                <div class="form-actions">
                    <button type="button" onclick="closeModal('passwordModal')" class="btn btn-secondary">Cancel</button>
                    <button type="submit" class="btn btn-warning">Reset Password</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        function openCreateModal() {
            document.getElementById('createModal').style.display = 'block';
        }

        function openEditModal(user) {
            document.getElementById('edit_user_id').value = user.id;
            document.getElementById('edit_username').value = user.username;
            document.getElementById('edit_full_name').value = user.full_name;
            document.getElementById('edit_email').value = user.email;
            document.getElementById('edit_role').value = user.role;
            document.getElementById('edit_is_active').checked = user.is_active == 1;
            document.getElementById('editModal').style.display = 'block';
        }

        function openPasswordModal(userId, username) {
            document.getElementById('password_user_id').value = userId;
            document.getElementById('password_username').value = username;
            document.getElementById('passwordModal').style.display = 'block';
        }

        function closeModal(modalId) {
            document.getElementById(modalId).style.display = 'none';
        }

        // Close modal when clicking outside
        window.onclick = function(event) {
            const modals = document.querySelectorAll('.modal');
            modals.forEach(modal => {
                if (event.target === modal) {
                    modal.style.display = 'none';
                }
            });
        }
    </script>

<?php include 'includes/footer.php'; ?>
