<?php
session_start();
require '../includes/config.php';

// Restrict to admins
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    header('Location: index.php');
    exit;
}

// Fetch users
$query = "SELECT id, first_name, last_name, email, role FROM users WHERE is_deleted = 0 ORDER BY role, first_name";
$result = mysqli_query($conn, $query);
$users = mysqli_fetch_all($result, MYSQLI_ASSOC);

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

// Handle delete user
if (isset($_GET['delete_user_id'])) {
    $delete_id = $_GET['delete_user_id'];
    
    // Prevent admin deletion
    $query = "SELECT role FROM users WHERE id = ? AND is_deleted = 0";
    $stmt = mysqli_prepare($conn, $query);
    mysqli_stmt_bind_param($stmt, 's', $delete_id);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    $user = mysqli_fetch_assoc($result);
    
    if ($user && $user['role'] === 'admin') {
        $error = "Cannot delete admin users.";
    } else {
        // Start transaction
        mysqli_begin_transaction($conn);
        try {
            // Delete from related tables based on role
            if ($user['role'] === 'student') {
                // Delete from class_program_students
                $query = "DELETE FROM class_program_students WHERE student_id = ?";
                $stmt = mysqli_prepare($conn, $query);
                mysqli_stmt_bind_param($stmt, 's', $delete_id);
                mysqli_stmt_execute($stmt);
                
                // Delete from responses_new where student_id
                $query = "DELETE FROM responses_new WHERE student_id = ?";
                $stmt = mysqli_prepare($conn, $query);
                mysqli_stmt_bind_param($stmt, 's', $delete_id);
                mysqli_stmt_execute($stmt);
            } elseif ($user['role'] === 'staff') {
                // Delete from user_roles
                $query = "DELETE FROM user_roles WHERE user_id = ?";
                $stmt = mysqli_prepare($conn, $query);
                mysqli_stmt_bind_param($stmt, 's', $delete_id);
                mysqli_stmt_execute($stmt);
                
                // Delete from class_program_staff
                $query = "DELETE FROM class_program_staff WHERE staff_id = ?";
                $stmt = mysqli_prepare($conn, $query);
                mysqli_stmt_bind_param($stmt, 's', $delete_id);
                mysqli_stmt_execute($stmt);
                
                // Delete from responses_new where staff_id
                $query = "DELETE FROM responses_new WHERE staff_id = ?";
                $stmt = mysqli_prepare($conn, $query);
                mysqli_stmt_bind_param($stmt, 's', $delete_id);
                mysqli_stmt_execute($stmt);
            }
            
            // Delete from users
            $query = "DELETE FROM users WHERE id = ?";
            $stmt = mysqli_prepare($conn, $query);
            mysqli_stmt_bind_param($stmt, 's', $delete_id);
            mysqli_stmt_execute($stmt);
            
            // Commit transaction
            mysqli_commit($conn);
            $success = "User and related data deleted successfully.";
            header('Location: user_manage.php');
            exit;
        } catch (mysqli_sql_exception $e) {
            // Rollback on error
            mysqli_rollback($conn);
            $error = "Failed to delete user: " . mysqli_error($conn);
        }
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Manage Users</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="../css/manage.css" rel="stylesheet">
</head>
<body>
    <div class="container">
        <h2>Manage Users</h2>
        <?php if ($success): ?>
            <div class="alert alert-success"><?php echo htmlspecialchars($success); ?></div>
        <?php endif; ?>
        <?php if ($error): ?>
            <div class="alert alert-danger"><?php echo htmlspecialchars($error); ?></div>
        <?php endif; ?>

        <table class="table table-bordered">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>First Name</th>
                    <th>Last Name</th>
                    <th>Email</th>
                    <th>Role</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($users)): ?>
                    <tr><td colspan="6">No users found.</td></tr>
                <?php else: ?>
                    <?php foreach ($users as $user): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($user['id']); ?></td>
                            <td><?php echo htmlspecialchars($user['first_name']); ?></td>
                            <td><?php echo htmlspecialchars($user['last_name']); ?></td>
                            <td><?php echo htmlspecialchars($user['email']); ?></td>
                            <td><?php echo htmlspecialchars($user['role']); ?></td>
                            <td>
                                <?php if ($user['role'] == 'student'): ?>
                                    <a href="edit_student.php?user_id=<?php echo $user['id']; ?>" class="btn btn-warning btn-sm">Edit</a>
                                <?php elseif ($user['role'] == 'staff'): ?>
                                    <a href="edit_staff.php?user_id=<?php echo $user['id']; ?>" class="btn btn-warning btn-sm">Edit</a>
                                <?php endif; ?>
                                <?php if ($user['role'] != 'admin'): ?>
                                    <a href="user_manage.php?delete_user_id=<?php echo $user['id']; ?>" class="btn btn-danger btn-sm" onclick="return confirm('Are you sure you want to delete this user and all related data?');">Delete</a>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
        <a href="dashboard.php" class="btn btn-secondary">Back to Dashboard</a>
    </div>
</body>
</html>