<?php
session_start();
require_once('../config.php');

if (!isset($_SESSION['user_id']) || $_SESSION['role'] != 'admin') {
    header("Location: dashboard.php");
    exit();
}

include('../header/header.php');

// Handle user deletion
if (isset($_GET['delete_user'])) {
    $user_id = $_GET['delete_user'];
    $stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    $success = "User deleted successfully.";
}

// Handle adding new user (Admin/Lecturer)
if (isset($_POST['add_user'])) {
    $username = $_POST['username'];
    $email = $_POST['email'];
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
    $role = $_POST['role'];
    $status = 'accepted'; // Admin-added users are accepted by default

    try {
        $stmt = $pdo->prepare("INSERT INTO users (username, email, password, role, status) VALUES (?, ?, ?, ?, ?)");
        $stmt->execute([$username, $email, $password, $role, $status]);
        $success = "New " . ucfirst($role) . " added successfully.";
    } catch (PDOException $e) {
        $error = "Error adding user: " . $e->getMessage();
    }
}

// Handle role and status update
if (isset($_POST['update_user'])) {
    $user_id = $_POST['user_id'];
    $new_role = $_POST['role'];
    $new_status = $_POST['status'];
    $stmt = $pdo->prepare("UPDATE users SET role = ?, status = ? WHERE id = ?");
    $stmt->execute([$new_role, $new_status, $user_id]);
    $success = "User details updated successfully.";
}

// Fetch all users
$stmt = $pdo->query("SELECT * FROM users ORDER BY created_at DESC");
$users = $stmt->fetchAll();
?>

<div class="container-fluid py-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2 class="fw-bold">Manage Users</h2>
        <button class="btn btn-primary shadow-sm" data-bs-toggle="modal" data-bs-target="#addUserModal">
            <i class="fas fa-user-plus me-2"></i>Add Admin/Lecturer
        </button>
    </div>

    <!-- Stats Summary -->
    <div class="row g-4 mb-4">
        <div class="col-md-3">
            <div class="dash-card bg-white p-3 shadow-sm border-start border-4 border-primary">
                <div class="d-flex align-items-center">
                    <div class="icon-box bg-primary bg-opacity-10 text-primary me-3">
                        <i class="fas fa-users"></i>
                    </div>
                    <div>
                        <p class="text-muted small text-uppercase mb-0 fw-bold">Total Users</p>
                        <h4 class="fw-bold mb-0"><?php echo count($users); ?></h4>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <?php 
                $pending_count = count(array_filter($users, function($u) { return $u['status'] == 'pending'; }));
            ?>
            <div class="dash-card bg-white p-3 shadow-sm border-start border-4 border-warning">
                <div class="d-flex align-items-center">
                    <div class="icon-box bg-warning bg-opacity-10 text-warning me-3">
                        <i class="fas fa-user-clock"></i>
                    </div>
                    <div>
                        <p class="text-muted small text-uppercase mb-0 fw-bold">Pending Approval</p>
                        <h4 class="fw-bold mb-0"><?php echo $pending_count; ?></h4>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <?php 
                $lecturer_count = count(array_filter($users, function($u) { return $u['role'] == 'lecturer'; }));
            ?>
            <div class="dash-card bg-white p-3 shadow-sm border-start border-4 border-success">
                <div class="d-flex align-items-center">
                    <div class="icon-box bg-success bg-opacity-10 text-success me-3">
                        <i class="fas fa-chalkboard-teacher"></i>
                    </div>
                    <div>
                        <p class="text-muted small text-uppercase mb-0 fw-bold">Lecturers</p>
                        <h4 class="fw-bold mb-0"><?php echo $lecturer_count; ?></h4>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <?php 
                $student_count = count(array_filter($users, function($u) { return $u['role'] == 'student'; }));
            ?>
            <div class="dash-card bg-white p-3 shadow-sm border-start border-4 border-info">
                <div class="d-flex align-items-center">
                    <div class="icon-box bg-info bg-opacity-10 text-info me-3">
                        <i class="fas fa-user-graduate"></i>
                    </div>
                    <div>
                        <p class="text-muted small text-uppercase mb-0 fw-bold">Students</p>
                        <h4 class="fw-bold mb-0"><?php echo $student_count; ?></h4>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <?php if(isset($success)): ?>
        <div class="alert alert-success alert-dismissible fade show border-0 shadow-sm mb-4" role="alert">
            <i class="fas fa-check-circle me-2"></i> <?php echo $success; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <div class="card glass-card border-0 shadow-sm">
        <div class="card-header bg-white border-0 py-3">
            <h5 class="fw-bold mb-0">System Users Directory</h5>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover align-middle mb-0">
                    <thead class="bg-light">
                        <tr>
                            <th class="ps-4">User Details</th>
                            <th>Role</th>
                            <th>Status</th>
                            <th>Joined Date</th>
                            <th class="text-end pe-4">Manage Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach($users as $user): ?>
                            <tr>
                                <td class="ps-4">
                                    <div class="d-flex align-items-center">
                                        <div class="bg-yellowish text-primary rounded-circle d-flex align-items-center justify-content-center me-3 shadow-sm fw-bold" style="width: 45px; height: 45px;">
                                            <?php echo strtoupper(substr($user['username'], 0, 1)); ?>
                                        </div>
                                        <div>
                                            <div class="fw-bold text-dark"><?php echo htmlspecialchars($user['username']); ?></div>
                                            <small class="text-muted"><?php echo htmlspecialchars($user['email']); ?></small>
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    <span class="badge <?php 
                                        echo $user['role'] == 'admin' ? 'bg-danger' : ($user['role'] == 'lecturer' ? 'bg-success' : 'bg-info'); 
                                    ?> text-capitalize px-3 py-2 rounded-pill">
                                        <?php echo $user['role']; ?>
                                    </span>
                                </td>
                                <td>
                                    <span class="badge <?php 
                                        echo $user['status'] == 'accepted' ? 'bg-success' : ($user['status'] == 'rejected' ? 'bg-danger' : 'bg-warning text-dark'); 
                                    ?> text-capitalize px-3 py-2 rounded-pill">
                                        <?php echo $user['status']; ?>
                                    </span>
                                </td>
                                <td><i class="far fa-calendar-alt me-2 text-muted"></i><?php echo date('M d, Y', strtotime($user['created_at'])); ?></td>
                                <td class="text-end pe-4">
                                    <div class="d-flex justify-content-end align-items-center gap-2">
                                        <form method="POST" class="d-flex align-items-center gap-2">
                                            <input type="hidden" name="user_id" value="<?php echo $user['id']; ?>">
                                            <select name="role" class="form-select form-select-sm" style="min-width: 100px;">
                                                <option value="student" <?php echo $user['role'] == 'student' ? 'selected' : ''; ?>>Student</option>
                                                <option value="lecturer" <?php echo $user['role'] == 'lecturer' ? 'selected' : ''; ?>>Lecturer</option>
                                                <option value="admin" <?php echo $user['role'] == 'admin' ? 'selected' : ''; ?>>Admin</option>
                                            </select>
                                            <select name="status" class="form-select form-select-sm" style="min-width: 100px;">
                                                <option value="pending" <?php echo $user['status'] == 'pending' ? 'selected' : ''; ?>>Pending</option>
                                                <option value="accepted" <?php echo $user['status'] == 'accepted' ? 'selected' : ''; ?>>Accept</option>
                                                <option value="rejected" <?php echo $user['status'] == 'rejected' ? 'selected' : ''; ?>>Reject</option>
                                            </select>
                                            <button type="submit" name="update_user" class="btn btn-sm btn-primary">Save</button>
                                        </form>
                                        <a href="manage_users.php?delete_user=<?php echo $user['id']; ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('Are you sure you want to delete this user?')">
                                            <i class="fas fa-trash"></i>
                                        </a>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Add User Modal -->
<div class="modal fade" id="addUserModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content border-0 shadow">
            <div class="modal-header">
                <h5 class="modal-title fw-bold">Add Admin or Lecturer</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label small fw-bold">Username</label>
                        <input type="text" name="username" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label small fw-bold">Email Address</label>
                        <input type="email" name="email" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label small fw-bold">Temporary Password</label>
                        <input type="password" name="password" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label small fw-bold">System Role</label>
                        <select name="role" class="form-select" required>
                            <option value="lecturer">Lecturer</option>
                            <option value="admin">Administrator</option>
                        </select>
                    </div>
                    <div class="alert alert-info py-2 small">
                        <i class="fas fa-info-circle me-2"></i> Users added here are automatically <strong>Accepted</strong> and can log in immediately.
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" name="add_user" class="btn btn-primary px-4">Create Account</button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php include('../footer/footer.php'); ?>
