<?php
// Include configuration file
require_once 'config.php';

// Require user to be logged in
require_login();

// Set the current page for navigation
$current_page = 'users';

// Initialize connection
$conn = connect_db();

// Determine the action (list, add, edit, delete)
$action = isset($_GET['action']) ? sanitize_input($_GET['action']) : 'list';

// Initialize variables
$user = [
    'id' => '',
    'username' => '',
    'password' => '',
    'email' => '',
    'fullname' => '',
    'role' => 'editor',
    'status' => 'active'
];

$error = '';
$success = '';

// Handle actions
switch ($action) {
    case 'add':
        // Display add form, actual addition handled in the 'save' case
        break;

    case 'edit':
        if (isset($_GET['id'])) {
            $id = (int)$_GET['id'];
            $stmt = $conn->prepare("SELECT id, username, email, fullname, role, status FROM users WHERE id = ?");
            $stmt->bind_param("i", $id);
            $stmt->execute();
            $result = $stmt->get_result();
            if ($result->num_rows > 0) {
                $user = $result->fetch_assoc();
            } else {
                $error = "User not found.";
                $action = 'list';
            }
            $stmt->close();
        } else {
            $error = "No user ID specified.";
            $action = 'list';
        }
        break;

    case 'save':
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            // Sanitize inputs
            $user['username'] = sanitize_input($_POST['username']);
            $user['email'] = sanitize_input($_POST['email']);
            $user['fullname'] = sanitize_input($_POST['fullname']);
            $user['role'] = sanitize_input($_POST['role']);
            $user['status'] = sanitize_input($_POST['status']);
            
            // Password is only required for new users or if changing password
            $password = $_POST['password'] ?? '';
            $password_confirm = $_POST['password_confirm'] ?? '';
            
            // Validate inputs
            if (empty($user['username'])) {
                $error = "Username is required.";
            } elseif (empty($user['email'])) {
                $error = "Email is required.";
            } elseif (!filter_var($user['email'], FILTER_VALIDATE_EMAIL)) {
                $error = "Invalid email format.";
            } elseif (!in_array($user['role'], ['admin', 'editor'])) {
                $error = "Invalid role.";
            } elseif (!in_array($user['status'], ['active', 'inactive'])) {
                $error = "Invalid status.";
            } else {
                // Check if username is already taken
                $check_username = $conn->prepare("SELECT id FROM users WHERE username = ? AND id != ?");
                $id_param = isset($_POST['id']) ? (int)$_POST['id'] : 0;
                $check_username->bind_param("si", $user['username'], $id_param);
                $check_username->execute();
                $check_result = $check_username->get_result();
                
                if ($check_result->num_rows > 0) {
                    $error = "Username already exists. Please choose a different one.";
                }
                $check_username->close();
                
                // Check if email is already taken
                if (empty($error)) {
                    $check_email = $conn->prepare("SELECT id FROM users WHERE email = ? AND id != ?");
                    $check_email->bind_param("si", $user['email'], $id_param);
                    $check_email->execute();
                    $check_result = $check_email->get_result();
                    
                    if ($check_result->num_rows > 0) {
                        $error = "Email already exists. Please use a different one.";
                    }
                    $check_email->close();
                }
                
                // Check password for new users or if password is being changed
                if (empty($error) && ((empty($_POST['id']) || !empty($password)))) {
                    if (strlen($password) < 8) {
                        $error = "Password must be at least 8 characters long.";
                    } elseif ($password !== $password_confirm) {
                        $error = "Passwords do not match.";
                    }
                }
            }

            // Database operation (insert or update)
            if (empty($error)) {
                if (isset($_POST['id']) && !empty($_POST['id'])) {
                    // Update existing user
                    $user['id'] = (int)$_POST['id'];
                    
                    // Determine if we're updating the password too
                    if (!empty($password)) {
                        $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                        $stmt = $conn->prepare("UPDATE users SET username = ?, email = ?, fullname = ?, role = ?, status = ?, password = ? WHERE id = ?");
                        $stmt->bind_param("ssssssi", $user['username'], $user['email'], $user['fullname'], $user['role'], $user['status'], $hashed_password, $user['id']);
                    } else {
                        $stmt = $conn->prepare("UPDATE users SET username = ?, email = ?, fullname = ?, role = ?, status = ? WHERE id = ?");
                        $stmt->bind_param("sssssi", $user['username'], $user['email'], $user['fullname'], $user['role'], $user['status'], $user['id']);
                    }
                    
                    if ($stmt->execute()) {
                        $success = "User updated successfully.";
                        log_action("Updated user", "ID: " . $user['id']);
                    } else {
                        $error = "Error updating user: " . $conn->error;
                    }
                    $stmt->close();
                } else {
                    // Insert new user
                    $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                    $stmt = $conn->prepare("INSERT INTO users (username, email, fullname, password, role, status) VALUES (?, ?, ?, ?, ?, ?)");
                    $stmt->bind_param("ssssss", $user['username'], $user['email'], $user['fullname'], $hashed_password, $user['role'], $user['status']);
                    
                    if ($stmt->execute()) {
                        $user['id'] = $conn->insert_id;
                        $success = "User added successfully.";
                        log_action("Added new user", "ID: " . $user['id']);
                    } else {
                        $error = "Error adding user: " . $conn->error;
                    }
                    $stmt->close();
                }
            }
            
            if (empty($error)) {
                // Redirect back to list view after successful operation
                header("Location: users.php?success=" . urlencode($success));
                exit;
            } else {
                // Stay on form in case of error
                $action = isset($_POST['id']) && !empty($_POST['id']) ? 'edit' : 'add';
            }
        }
        break;

    case 'delete':
        if (isset($_GET['id'])) {
            $id = (int)$_GET['id'];
            
            // Check if this is the current user (prevent self-deletion)
            if ($id === ($_SESSION['user_id'] ?? 0)) {
                $error = "You cannot delete your own account.";
                header("Location: users.php?error=" . urlencode($error));
                exit;
            }
            
            // Check if this is the last admin
            $stmt = $conn->prepare("SELECT COUNT(*) as count FROM users WHERE role = 'admin' AND id != ?");
            $stmt->bind_param("i", $id);
            $stmt->execute();
            $result = $stmt->get_result();
            $row = $result->fetch_assoc();
            $admin_count = $row['count'];
            $stmt->close();
            
            // Get the role of the user to be deleted
            $stmt = $conn->prepare("SELECT role FROM users WHERE id = ?");
            $stmt->bind_param("i", $id);
            $stmt->execute();
            $result = $stmt->get_result();
            $row = $result->fetch_assoc();
            $user_role = $row['role'] ?? '';
            $stmt->close();
            
            // Prevent deleting the last admin
            if ($user_role === 'admin' && $admin_count === 0) {
                $error = "Cannot delete the last admin user.";
                header("Location: users.php?error=" . urlencode($error));
                exit;
            }
            
            // If checks pass, proceed with deletion
            $stmt = $conn->prepare("DELETE FROM users WHERE id = ?");
            $stmt->bind_param("i", $id);
            
            if ($stmt->execute()) {
                $success = "User deleted successfully.";
                log_action("Deleted user", "ID: " . $id);
            } else {
                $error = "Error deleting user: " . $conn->error;
            }
            $stmt->close();
            
            header("Location: users.php?success=" . urlencode($success));
            exit;
        } else {
            $error = "No user ID specified.";
        }
        break;

    default:
        // 'list' action is the default view
        break;
}

// Pagination setup for list view
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 10;
$offset = ($page - 1) * $limit;

// Count total records for pagination
$total_records = 0;
$result = $conn->query("SELECT COUNT(*) as count FROM users");
if ($result && $row = $result->fetch_assoc()) {
    $total_records = $row['count'];
}
$total_pages = ceil($total_records / $limit);

// Get users for list view
$users = [];
$query = "SELECT id, username, email, fullname, role, status FROM users ORDER BY username LIMIT ? OFFSET ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("ii", $limit, $offset);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    $users[] = $row;
}
$stmt->close();

// Close connection
$conn->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User Management - <?php echo $config['app_name']; ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
    <style>
        :root {
            --primary-color: #1f3889;
            --secondary-color: #ad9237;
            --primary-dark: #152a6a;
            --secondary-dark: #967d2f;
            --sidebar-width: 250px;
        }
        
        body {
            min-height: 100vh;
            background-color: #f8f9fa;
        }
        
        /* Sidebar */
        .sidebar {
            width: var(--sidebar-width);
            position: fixed;
            top: 0;
            left: 0;
            height: 100%;
            z-index: 1000;
            background: linear-gradient(135deg, var(--primary-color), var(--primary-dark));
            color: white;
            padding-top: 20px;
            transition: all 0.3s;
        }
        
        .sidebar-header {
            padding: 10px 20px;
            text-align: center;
            margin-bottom: 20px;
        }
        
        .sidebar-header img {
            max-width: 120px;
            margin-bottom: 10px;
        }
        
        .sidebar-menu {
            list-style: none;
            padding: 0;
            margin: 0;
        }
        
        .sidebar-menu li {
            margin-bottom: 5px;
        }
        
        .sidebar-menu a {
            color: rgba(255, 255, 255, 0.8);
            text-decoration: none;
            padding: 12px 20px;
            display: block;
            transition: all 0.3s;
            border-left: 4px solid transparent;
        }
        
        .sidebar-menu a:hover, .sidebar-menu a.active {
            color: white;
            background-color: rgba(255, 255, 255, 0.1);
            border-left-color: var(--secondary-color);
        }
        
        .sidebar-menu i {
            margin-right: 10px;
            width: 20px;
            text-align: center;
        }
        
        /* Main content */
        .main-content {
            margin-left: var(--sidebar-width);
            padding: 20px;
            transition: all 0.3s;
        }
        
        /* Header */
        .main-header {
            background-color: white;
            padding: 15px 20px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
            border-radius: 5px;
        }
        
        .main-header h1 {
            color: var(--primary-color);
            font-size: 1.5rem;
            margin-bottom: 0;
        }
        
        /* Cards */
        .content-card {
            background-color: white;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
            margin-bottom: 20px;
        }
        
        .content-card .card-header {
            padding: 15px 20px;
            border-bottom: 1px solid #eee;
        }
        
        .content-card .card-body {
            padding: 20px;
        }
        
        /* Tables */
        .data-table th {
            background-color: #f8f9fa;
        }
        
        /* Buttons */
        .btn-primary {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
        }
        
        .btn-primary:hover, .btn-primary:focus {
            background-color: var(--primary-dark);
            border-color: var(--primary-dark);
        }
        
        .btn-secondary {
            background-color: var(--secondary-color);
            border-color: var(--secondary-color);
        }
        
        .btn-secondary:hover, .btn-secondary:focus {
            background-color: var(--secondary-dark);
            border-color: var(--secondary-dark);
        }
        
        /* Footer */
        .footer {
            margin-left: var(--sidebar-width);
            padding: 15px 20px;
            text-align: center;
            color: #6c757d;
            font-size: 0.9rem;
            border-top: 1px solid #eee;
        }
        
        /* Responsive */
        @media (max-width: 768px) {
            .sidebar {
                width: 0;
                padding-top: 60px;
            }
            
            .sidebar.active {
                width: var(--sidebar-width);
            }
            
            .main-content, .footer {
                margin-left: 0;
            }
            
            .main-content.sidebar-active, .footer.sidebar-active {
                margin-left: var(--sidebar-width);
            }
            
            .sidebar-toggle {
                display: block;
            }
        }
        
        .sidebar-toggle {
            display: none;
            position: fixed;
            top: 15px;
            left: 15px;
            z-index: 1050;
            background-color: var(--primary-color);
            border: none;
            color: white;
            width: 40px;
            height: 40px;
            border-radius: 3px;
        }
        
        .badge.bg-admin {
            background-color: var(--primary-color) !important;
        }
        
        .badge.bg-editor {
            background-color: var(--secondary-color) !important;
        }
        
        .badge.bg-active {
            background-color: #28a745 !important;
        }
        
        .badge.bg-inactive {
            background-color: #6c757d !important;
        }
    </style>
</head>
<body>
    <!-- Sidebar toggle button (mobile) -->
    <button class="sidebar-toggle d-md-none" id="sidebarToggle">
        <i class="fas fa-bars"></i>
    </button>
    
    <!-- Sidebar -->
    <div class="sidebar">
        <div class="sidebar-header">
            <img src="assets/nsa-logo.jpeg" alt="NSA Logo" class="img-fluid">
            <h5>NSA Admin</h5>
        </div>
        
        <ul class="sidebar-menu">
            <li><a href="index.php"><i class="fas fa-tachometer-alt"></i> Dashboard</a></li>
            <li><a href="reports.php"><i class="fas fa-file-alt"></i> Reports</a></li>
            <li><a href="report-categories.php"><i class="fas fa-tags"></i> Report Categories</a></li>
            <li><a href="indicators.php"><i class="fas fa-chart-line"></i> Indicators</a></li>
            <li><a href="indicator-themes.php"><i class="fas fa-palette"></i> Indicator Themes</a></li>
            <li><a href="users.php" class="active"><i class="fas fa-users"></i> Users</a></li>
            <li><a href="settings.php"><i class="fas fa-cog"></i> Settings</a></li>
            <li><a href="login.php?action=logout"><i class="fas fa-sign-out-alt"></i> Logout</a></li>
        </ul>
    </div>
    
    <!-- Main content -->
    <div class="main-content">
        <!-- Header -->
        <div class="main-header d-flex justify-content-between align-items-center">
            <h1><?php echo ($action === 'add' ? 'Add New User' : ($action === 'edit' ? 'Edit User' : 'User Management')); ?></h1>
            <div class="user-info">
                <span class="me-2"><?php echo $_SESSION['username'] ?? 'Admin User'; ?></span>
                <i class="fas fa-user-circle"></i>
            </div>
        </div>
        
        <?php if (isset($_GET['success'])): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <?php echo htmlspecialchars($_GET['success']); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>
        
        <?php if (isset($_GET['error'])): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <?php echo htmlspecialchars($_GET['error']); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>
        
        <?php if (!empty($error)): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <?php echo $error; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>
        
        <!-- Content based on action -->
        <?php if ($action === 'list'): ?>
            <div class="content-card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">All Users</h5>
                    <a href="users.php?action=add" class="btn btn-primary btn-sm">
                        <i class="fas fa-plus"></i> Add New User
                    </a>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover data-table">
                            <thead>
                                <tr>
                                    <th>Username</th>
                                    <th>Name</th>
                                    <th>Email</th>
                                    <th>Role</th>
                                    <th>Status</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($users)): ?>
                                    <tr>
                                        <td colspan="6" class="text-center">No users found.</td>
                                    </tr>
                                <?php else: ?>
                                    <?php foreach ($users as $item): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($item['username']); ?></td>
                                            <td><?php echo htmlspecialchars($item['fullname']); ?></td>
                                            <td><?php echo htmlspecialchars($item['email']); ?></td>
                                            <td>
                                                <span class="badge bg-<?php echo $item['role']; ?>">
                                                    <?php echo ucfirst(htmlspecialchars($item['role'])); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <span class="badge bg-<?php echo $item['status']; ?>">
                                                    <?php echo ucfirst(htmlspecialchars($item['status'])); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <a href="users.php?action=edit&id=<?php echo $item['id']; ?>" class="btn btn-sm btn-info">
                                                    <i class="fas fa-edit"></i>
                                                </a>
                                                <?php if ($item['id'] != ($_SESSION['user_id'] ?? 0)): ?>
                                                    <a href="#" class="btn btn-sm btn-danger" data-bs-toggle="modal" data-bs-target="#deleteModal<?php echo $item['id']; ?>">
                                                        <i class="fas fa-trash"></i>
                                                    </a>
                                                    
                                                    <!-- Delete Confirmation Modal -->
                                                    <div class="modal fade" id="deleteModal<?php echo $item['id']; ?>" tabindex="-1" aria-labelledby="deleteModalLabel<?php echo $item['id']; ?>" aria-hidden="true">
                                                        <div class="modal-dialog">
                                                            <div class="modal-content">
                                                                <div class="modal-header">
                                                                    <h5 class="modal-title" id="deleteModalLabel<?php echo $item['id']; ?>">Confirm Delete</h5>
                                                                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                                                </div>
                                                                <div class="modal-body">
                                                                    Are you sure you want to delete the user: <strong><?php echo htmlspecialchars($item['username']); ?></strong>?<br>
                                                                    This action cannot be undone.
                                                                </div>
                                                                <div class="modal-footer">
                                                                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                                                                    <a href="users.php?action=delete&id=<?php echo $item['id']; ?>" class="btn btn-danger">Delete</a>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                <?php else: ?>
                                                    <button class="btn btn-sm btn-danger" disabled title="Cannot delete your own account">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                    
                    <!-- Pagination -->
                    <?php if ($total_pages > 1): ?>
                        <?php echo get_pagination($total_pages, $page, 'users.php?action=list'); ?>
                    <?php endif; ?>
                </div>
            </div>
        <?php else: ?>
            <!-- Form for add/edit -->
            <div class="content-card">
                <div class="card-body">
                    <form action="users.php?action=save" method="post">
                        <?php if ($action === 'edit'): ?>
                            <input type="hidden" name="id" value="<?php echo $user['id']; ?>">
                        <?php endif; ?>
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="username" class="form-label">Username *</label>
                                <input type="text" class="form-control" id="username" name="username" value="<?php echo htmlspecialchars($user['username']); ?>" required>
                            </div>
                            
                            <div class="col-md-6">
                                <label for="email" class="form-label">Email *</label>
                                <input type="email" class="form-control" id="email" name="email" value="<?php echo htmlspecialchars($user['email']); ?>" required>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="fullname" class="form-label">Full Name</label>
                            <input type="text" class="form-control" id="fullname" name="fullname" value="<?php echo htmlspecialchars($user['fullname']); ?>">
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="password" class="form-label"><?php echo ($action === 'add') ? 'Password *' : 'New Password (leave blank to keep current)'; ?></label>
                                <input type="password" class="form-control" id="password" name="password" <?php echo ($action === 'add') ? 'required' : ''; ?>>
                                <?php if ($action === 'add'): ?>
                                    <small class="text-muted">Password must be at least 8 characters long</small>
                                <?php endif; ?>
                            </div>
                            
                            <div class="col-md-6">
                                <label for="password_confirm" class="form-label"><?php echo ($action === 'add') ? 'Confirm Password *' : 'Confirm New Password'; ?></label>
                                <input type="password" class="form-control" id="password_confirm" name="password_confirm" <?php echo ($action === 'add') ? 'required' : ''; ?>>
                            </div>
                        </div>
                        
                        <div class="row mb-4">
                            <div class="col-md-6">
                                <label for="role" class="form-label">Role *</label>
                                <select class="form-select" id="role" name="role" required>
                                    <option value="admin" <?php echo ($user['role'] === 'admin') ? 'selected' : ''; ?>>Administrator</option>
                                    <option value="editor" <?php echo ($user['role'] === 'editor') ? 'selected' : ''; ?>>Editor</option>
                                </select>
                                <small class="text-muted">Administrators have full access. Editors can manage content but not users.</small>
                            </div>
                            
                            <div class="col-md-6">
                                <label for="status" class="form-label">Status *</label>
                                <select class="form-select" id="status" name="status" required>
                                    <option value="active" <?php echo ($user['status'] === 'active') ? 'selected' : ''; ?>>Active</option>
                                    <option value="inactive" <?php echo ($user['status'] === 'inactive') ? 'selected' : ''; ?>>Inactive</option>
                                </select>
                                <small class="text-muted">Inactive users cannot log in to the system.</small>
                            </div>
                        </div>
                        
                        <div class="d-flex justify-content-between">
                            <a href="users.php" class="btn btn-secondary">Cancel</a>
                            <button type="submit" class="btn btn-primary"><?php echo ($action === 'edit') ? 'Update User' : 'Add User'; ?></button>
                        </div>
                    </form>
                </div>
            </div>
        <?php endif; ?>
    </div>
    
    <!-- Footer -->
    <div class="footer">
        <p><?php echo $config['app_name']; ?> &copy; <?php echo date('Y'); ?> Namibia Statistics Agency</p>
    </div>
    
    <!-- Scripts -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Mobile sidebar toggle
        document.getElementById('sidebarToggle')?.addEventListener('click', function() {
            document.querySelector('.sidebar').classList.toggle('active');
            document.querySelector('.main-content').classList.toggle('sidebar-active');
            document.querySelector('.footer').classList.toggle('sidebar-active');
        });
        
        // Password match validation
        document.querySelector('form')?.addEventListener('submit', function(e) {
            const password = document.getElementById('password');
            const passwordConfirm = document.getElementById('password_confirm');
            
            if (password.value !== '' && password.value !== passwordConfirm.value) {
                e.preventDefault();
                alert('Passwords do not match!');
            }
        });
    </script>
</body>
</html>