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

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

// Check if user_id is provided
if (!isset($_GET['user_id'])) {
    header('Location: user_manage.php');
    exit;
}

$user_id = $_GET['user_id'];

// Fetch user details
$query = "SELECT id, first_name, last_name, email, designation FROM users WHERE id = ? AND role = 'staff' AND is_deleted = 0";
$stmt = mysqli_prepare($conn, $query);
mysqli_stmt_bind_param($stmt, 's', $user_id);
mysqli_stmt_execute($stmt);
$user = mysqli_fetch_assoc(mysqli_stmt_get_result($stmt));

if (!$user) {
    header('Location: user_manage.php');
    exit;
}

// Fetch current role
$query = "SELECT role_id FROM user_roles WHERE user_id = ?";
$stmt = mysqli_prepare($conn, $query);
mysqli_stmt_bind_param($stmt, 's', $user_id);
mysqli_stmt_execute($stmt);
$current_role = mysqli_fetch_assoc(mysqli_stmt_get_result($stmt));

// Set default if no role exists
$has_role = !is_null($current_role);
$current_role_id = $has_role ? $current_role['role_id'] : '';

// Fetch available roles
$roles_query = "SELECT role_id, role_name FROM roles ORDER BY role_name";
$roles_result = mysqli_query($conn, $roles_query);
$roles = mysqli_fetch_all($roles_result, MYSQLI_ASSOC);

// Check if roles are empty
if (empty($roles)) {
    $error = "No roles available. Please add roles in the management section.";
}

$error = '';
$success = '';
$warning = $has_role ? '' : 'No role assigned to this staff member. Please select one.';

if ($_SERVER['REQUEST_METHOD'] == 'POST' && empty($error)) {
    $first_name = trim($_POST['first_name']);
    $last_name = trim($_POST['last_name']);
    $email = trim($_POST['email']);
    $designation = $_POST['designation'];
    $role_id = $_POST['role_id'];

    // Validate inputs
    if (empty($first_name) || empty($last_name) || empty($email) || empty($designation) || empty($role_id)) {
        $error = "All fields are required.";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = "Invalid email format.";
    } elseif (!in_array($designation, ['Teaching Staff', 'Non-Teaching Staff'])) {
        $error = "Invalid designation selected.";
    } elseif (!array_key_exists($role_id, array_column($roles, 'role_id', 'role_id'))) {
        $error = "Invalid role selected.";
    } else {
        // Check if email is taken by another user
        $query = "SELECT id FROM users WHERE email = ? AND id != ?";
        $stmt = mysqli_prepare($conn, $query);
        mysqli_stmt_bind_param($stmt, 'ss', $email, $user_id);
        mysqli_stmt_execute($stmt);
        if (mysqli_stmt_get_result($stmt)->num_rows > 0) {
            $error = "Email already in use by another user.";
        } else {
            // Update user details
            $query = "UPDATE users SET first_name = ?, last_name = ?, email = ?, designation = ? WHERE id = ?";
            $stmt = mysqli_prepare($conn, $query);
            mysqli_stmt_bind_param($stmt, 'sssss', $first_name, $last_name, $email, $designation, $user_id);
            if (mysqli_stmt_execute($stmt)) {
                // Update role assignment
                $query = "REPLACE INTO user_roles (user_id, role_id) VALUES (?, ?)";
                $stmt = mysqli_prepare($conn, $query);
                mysqli_stmt_bind_param($stmt, 'si', $user_id, $role_id);
                if (mysqli_stmt_execute($stmt)) {
                    $success = "Staff details updated successfully.";
                } else {
                    $error = "Failed to update role: " . mysqli_error($conn);
                }
            } else {
                $error = "Failed to update user: " . mysqli_error($conn);
            }
        }
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Edit Staff</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 Staff</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 ($warning): ?>
            <div class="alert alert-warning"><?php echo htmlspecialchars($warning); ?></div>
        <?php endif; ?>

        <form method="POST">
            <div class="form-group mb-3">
                <label>ID</label>
                <input type="text" class="form-control" value="<?php echo htmlspecialchars($user['id']); ?>" disabled>
            </div>
            <div class="form-group mb-3">
                <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 mb-3">
                <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 mb-3">
                <label>Email</label>
                <input type="email" name="email" class="form-control" value="<?php echo htmlspecialchars($user['email']); ?>" required>
            </div>
            <div class="form-group mb-3">
                <label>Designation</label>
                <select name="designation" class="form-control" required>
                    <option value="">Select Designation</option>
                    <option value="Teaching Staff" <?php echo $user['designation'] == 'Teaching Staff' ? 'selected' : ''; ?>>Teaching Staff</option>
                    <option value="Non-Teaching Staff" <?php echo $user['designation'] == 'Non-Teaching Staff' ? 'selected' : ''; ?>>Non-Teaching Staff</option>
                </select>
            </div>
            <div class="form-group mb-3">
                <label>Role</label>
                <select name="role_id" class="form-control" required>
                    <option value="">Select Role</option>
                    <?php foreach ($roles as $role): ?>
                        <option value="<?php echo $role['role_id']; ?>" <?php echo $current_role_id == $role['role_id'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($role['role_name']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <button type="submit" class="btn btn-primary">Update</button>
            <a href="user_manage.php" class="btn btn-secondary">Back to Manage Users</a>
        </form>
    </div>
</body>
</html>