<?php
/**
 * Users Management
 * Manage system users and their roles
 * Kenyan Pension & Life Insurance Management System
 */

require_once 'layouts/main.php';
require_once 'includes/auth.php';

requireLogin();
requirePermission('manage_users');

$action = $_GET['action'] ?? 'list';
$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($action === 'create') {
        $password_hash = password_hash($_POST['password'], PASSWORD_DEFAULT);
        $profile = json_encode([
            'first_name' => $_POST['first_name'] ?? '',
            'last_name' => $_POST['last_name'] ?? ''
        ]);
        
        $sql = "INSERT INTO users (username, email, phone, password_hash, role_id, profile, is_active)
                VALUES (?, ?, ?, ?, ?, ?, 1)";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("ssssis",
            $_POST['username'],
            $_POST['email'],
            $_POST['phone'] ?? null,
            $password_hash,
            $_POST['role_id'],
            $profile
        );
        if ($stmt->execute()) {
            $message = 'User created successfully';
            $messageType = 'success';
            $action = 'list';
        } else {
            $message = 'Failed to create user';
            $messageType = 'danger';
        }
    }
}

// Get users
$users = $conn->query("SELECT u.*, r.role_name FROM users u INNER JOIN roles r ON u.role_id = r.role_id WHERE u.deleted_at IS NULL ORDER BY u.created_at DESC")->fetch_all(MYSQLI_ASSOC);
$roles = $conn->query("SELECT role_id, role_name FROM roles WHERE is_active = 1")->fetch_all(MYSQLI_ASSOC);

$pageTitle = 'Users Management';
include 'layouts/topbar.php';
?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Users Management')); ?>
    <link rel="stylesheet" href="assets/css/pension-dashboard.css">
    <?php include 'layouts/head-css.php'; ?>
</head>

<body data-sidebar="dark">
    <div id="layout-wrapper">
        <?php include 'layouts/sidebar.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Header -->
                    <div class="welcome-header" style="background: linear-gradient(135deg, #6366f1 0%, #4f46e5 100%); margin-bottom: 2rem;">
                        <div class="welcome-content">
                            <div class="welcome-text">
                                <h2>Users Management</h2>
                                <p>Manage system users and their roles</p>
                            </div>
                        </div>
                    </div>

                    <?php if ($message): ?>
                    <div class="alert alert-<?php echo $messageType; ?> alert-dismissible fade show">
                        <?php echo htmlspecialchars($message); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <?php endif; ?>

                    <div class="row mb-3">
                        <div class="col-12">
                            <a href="users.php?action=create" class="btn btn-primary">
                                <i class="ri-user-add-line me-2"></i>Add User
                            </a>
                        </div>
                    </div>

                    <?php if ($action === 'create'): ?>
                        <div class="row">
                            <div class="col-12">
                                <div class="page-card">
                                    <div class="page-card-header">
                                        <h4 class="page-card-title">Add New User</h4>
                                    </div>
                                    <div class="page-card-body">
                                        <form method="POST">
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Username <span class="text-danger">*</span></label>
                                                    <input type="text" name="username" class="form-control" required>
                                                </div>
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Email <span class="text-danger">*</span></label>
                                                    <input type="email" name="email" class="form-control" required>
                                                </div>
                                            </div>
                                            <div class="row">
                                                <div class="col-md-4 mb-3">
                                                    <label class="form-label">First Name</label>
                                                    <input type="text" name="first_name" class="form-control">
                                                </div>
                                                <div class="col-md-4 mb-3">
                                                    <label class="form-label">Last Name</label>
                                                    <input type="text" name="last_name" class="form-control">
                                                </div>
                                                <div class="col-md-4 mb-3">
                                                    <label class="form-label">Phone</label>
                                                    <input type="text" name="phone" class="form-control">
                                                </div>
                                            </div>
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Role <span class="text-danger">*</span></label>
                                                    <select name="role_id" class="form-select" required>
                                                        <option value="">Select Role</option>
                                                        <?php foreach ($roles as $role): ?>
                                                            <option value="<?php echo $role['role_id']; ?>">
                                                                <?php echo htmlspecialchars($role['role_name']); ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Password <span class="text-danger">*</span></label>
                                                    <input type="password" name="password" class="form-control" required minlength="8">
                                                    <small class="text-muted">Minimum 8 characters</small>
                                                </div>
                                            </div>
                                            <button type="submit" class="btn btn-primary">Save User</button>
                                            <a href="users.php" class="btn btn-secondary">Cancel</a>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php else: ?>
                        <div class="row">
                            <div class="col-12">
                                <div class="page-card">
                                    <div class="page-card-header">
                                        <h4 class="page-card-title">Users List</h4>
                                    </div>
                                    <div class="page-card-body">
                                        <div class="table-responsive">
                                            <table class="data-table">
                                                <thead>
                                                    <tr>
                                                        <th>Username</th>
                                                        <th>Name</th>
                                                        <th>Email</th>
                                                        <th>Phone</th>
                                                        <th>Role</th>
                                                        <th>Status</th>
                                                        <th>Last Login</th>
                                                        <th>Actions</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php if (empty($users)): ?>
                                                        <tr><td colspan="8" class="text-center">No users found</td></tr>
                                                    <?php else: ?>
                                                        <?php foreach ($users as $user): 
                                                            $profile = json_decode($user['profile'], true);
                                                            $full_name = isset($profile['first_name']) && isset($profile['last_name']) 
                                                                ? $profile['first_name'] . ' ' . $profile['last_name'] 
                                                                : 'N/A';
                                                        ?>
                                                            <tr>
                                                                <td><?php echo htmlspecialchars($user['username']); ?></td>
                                                                <td><?php echo htmlspecialchars($full_name); ?></td>
                                                                <td><?php echo htmlspecialchars($user['email']); ?></td>
                                                                <td><?php echo htmlspecialchars($user['phone'] ?? 'N/A'); ?></td>
                                                                <td><span class="badge bg-info"><?php echo htmlspecialchars($user['role_name']); ?></span></td>
                                                                <td>
                                                                    <span class="status-badge status-<?php echo $user['is_active'] ? 'active' : 'pending'; ?>">
                                                                        <?php echo $user['is_active'] ? 'Active' : 'Inactive'; ?>
                                                                    </span>
                                                                </td>
                                                                <td><?php echo $user['last_login'] ? date('d M Y', strtotime($user['last_login'])) : 'Never'; ?></td>
                                                                <td>
                                                                    <a href="user_details.php?id=<?php echo $user['user_id']; ?>" class="btn btn-sm btn-info">
                                                                        <i class="ri-eye-line"></i>
                                                                    </a>
                                                                    <a href="users.php?action=edit&id=<?php echo $user['user_id']; ?>" class="btn btn-sm btn-primary">
                                                                        <i class="ri-edit-line"></i>
                                                                    </a>
                                                                </td>
                                                            </tr>
                                                        <?php endforeach; ?>
                                                    <?php endif; ?>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <?php include 'layouts/vendor-scripts.php'; ?>
</body>
</html>
