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

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

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

// Get user for editing
$user = null;
if (isset($_GET['id']) && !empty($_GET['id'])) {
    $query = "SELECT * FROM users WHERE id = ? AND is_deleted = 0";
    $stmt = mysqli_prepare($conn, $query);
    mysqli_stmt_bind_param($stmt, 's', $_GET['id']);
    mysqli_stmt_execute($stmt);
    $user = mysqli_fetch_assoc(mysqli_stmt_get_result($stmt));
    if (!$user) {
        $error = "User not found or has been deleted.";
    }
} else {
    header('Location: user_manage.php');
    exit;
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $new_id = trim($_POST['id']);
    $first_name = trim($_POST['first_name']);
    $last_name = trim($_POST['last_name']);
    $email = trim($_POST['email']);
    $role = $_POST['role'];
    $old_id = $_POST['old_id'];

    if (empty($new_id) || empty($first_name) || empty($last_name) || empty($email) || empty($role)) {
        $error = "All fields are required.";
    } else {
        // Check if new ID is unique (if changed)
        if ($new_id !== $old_id) {
            $query = "SELECT id FROM users WHERE id = ? AND is_deleted = 0";
            $stmt = mysqli_prepare($conn, $query);
            mysqli_stmt_bind_param($stmt, 's', $new_id);
            mysqli_stmt_execute($stmt);
            if (mysqli_stmt_get_result($stmt)->num_rows > 0) {
                $error = "The new ID is already in use.";
            }
        }

        if (!$error) {
            $query = "UPDATE users SET id = ?, first_name = ?, last_name = ?, email = ?, role = ? WHERE id = ?";
            $stmt = mysqli_prepare($conn, $query);
            mysqli_stmt_bind_param($stmt, 'ssssss', $new_id, $first_name, $last_name, $email, $role, $old_id);
            if (mysqli_stmt_execute($stmt)) {
                $success = "User updated successfully!";
                // Refresh user data
                $query = "SELECT * FROM users WHERE id = ? AND is_deleted = 0";
                $stmt = mysqli_prepare($conn, $query);
                mysqli_stmt_bind_param($stmt, 's', $new_id);
                mysqli_stmt_execute($stmt);
                $user = mysqli_fetch_assoc(mysqli_stmt_get_result($stmt));
            } else {
                $error = "Failed to update user: " . mysqli_error($conn);
            }
        }
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Edit User</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="../css/style.css" rel="stylesheet">
</head>
<body>
    <div class="container">
        <h2>Edit User</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; ?>

        <?php if ($user): ?>
            <form method="POST">
                <input type="hidden" name="old_id" value="<?php echo htmlspecialchars($user['id']); ?>">
                <div class="form-group">
                    <label>User ID</label>
                    <input type="text" name="id" class="form-control" value="<?php echo htmlspecialchars($user['id']); ?>" required>
                </div>
                <div class="form-group">
                    <label>First Name</label>
                    <input type="text" name="first_name" class="form-control" value="<?php echo htmlspecialchars($user['first_name']); ?>" required>
                </div>
                <div class="form-group">
                    <label>Last Name</label>
                    <input type="text" name="last_name" class="form-control" value="<?php echo htmlspecialchars($user['last_name']); ?>" required>
                </div>
                <div class="form-group">
                    <label>Email</label>
                    <input type="email" name="email" class="form-control" value="<?php echo htmlspecialchars($user['email']); ?>" required>
                </div>
                <div class="form-group">
                    <label>Role</label>
                    <select name="role" class="form-control" required>
                        <option value="admin" <?php if ($user['role'] == 'admin') echo 'selected'; ?>>Admin</option>
                        <option value="staff" <?php if ($user['role'] == 'staff') echo 'selected'; ?>>Staff</option>
                        <option value="student" <?php if ($user['role'] == 'student') echo 'selected'; ?>>Student</option>
                    </select>
                </div>
                <button type="submit" class="btn btn-primary">Update User</button>
                <a href="user_manage.php" class="btn btn-secondary">Cancel</a>
            </form>
        <?php else: ?>
            <p>User not found.</p>
            <a href="user_manage.php" class="btn btn-secondary">Back to Manage Users</a>
        <?php endif; ?>
    </div>
</body>
</html>