<?php
// pages/admin/edit_user.php
// Handles the editing of a user's details.

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Ensure user is logged in and has admin role.
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true || $_SESSION['user_role'] !== 'admin') {
    header("Location: index.php?page=login");
    exit();
}

require_once 'config/database.php';

$user_id = isset($_GET['user_id']) ? (int)$_GET['user_id'] : 0;
$user = null;
$message = '';
$is_error = false;

// Handle form submission for updating the user
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_user'])) {
    $user_id = filter_input(INPUT_POST, 'user_id', FILTER_VALIDATE_INT);
    $full_name = filter_input(INPUT_POST, 'full_name', FILTER_SANITIZE_STRING);
    $username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
    $email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);

    // Basic validation
    if (!$user_id || !$full_name || !$username || !$email) {
        $message = "All fields must be filled and valid.";
        $is_error = true;
    } else {
        try {
            // Check for duplicate username (excluding the current user)
            $stmt_username = $pdo->prepare("SELECT COUNT(*) FROM users WHERE username = ? AND id != ?");
            $stmt_username->execute([$username, $user_id]);
            if ($stmt_username->fetchColumn() > 0) {
                $message = "Username is already taken by another user.";
                $is_error = true;
            }

            // Check for duplicate email (excluding the current user)
            $stmt_email = $pdo->prepare("SELECT COUNT(*) FROM users WHERE email = ? AND id != ?");
            $stmt_email->execute([$email, $user_id]);
            if ($stmt_email->fetchColumn() > 0) {
                $message = "Email is already in use by another user.";
                $is_error = true;
            }

            if (!$is_error) {
                $sql = "UPDATE users SET full_name = ?, username = ?, email = ? WHERE id = ?";
                $stmt = $pdo->prepare($sql);
                $stmt->execute([$full_name, $username, $email, $user_id]);

                $_SESSION['message'] = "User details updated successfully!";
                $_SESSION['is_error'] = false;
                header("Location: index.php?page=manage_users");
                exit();
            }

        } catch (PDOException $e) {
            $message = "Database error: " . $e->getMessage();
            $is_error = true;
            error_log("User Update Error: " . $e->getMessage());
        }
    }
}

// Fetch existing user data to pre-fill the form
if ($user_id > 0) {
    try {
        $sql = "SELECT id, full_name, username, email, role FROM users WHERE id = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$user_id]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$user) {
            $message = "User not found.";
            $is_error = true;
        }
    } catch (PDOException $e) {
        $message = "Database error: " . $e->getMessage();
        $is_error = true;
    }
} else {
    $message = "Invalid user ID.";
    $is_error = true;
}

?>

<div class="w-full max-w-2xl mx-auto p-6 bg-white rounded-lg shadow-xl">
    <h1 class="text-3xl font-bold text-gray-900 mb-6">Edit User</h1>

    <?php if (!empty($message)): ?>
        <div class="mb-4 p-4 rounded-md text-sm <?php echo $is_error ? 'bg-red-100 text-red-700' : 'bg-green-100 text-green-700'; ?>">
            <?php echo htmlspecialchars($message); ?>
        </div>
    <?php endif; ?>

    <?php if ($user): ?>
    <form action="index.php?page=edit_user" method="POST" class="space-y-6">
        <input type="hidden" name="user_id" value="<?php echo htmlspecialchars($user['id']); ?>">
        
        <div>
            <label for="full_name" class="block text-sm font-medium text-gray-700">Full Name</label>
            <input type="text" name="full_name" id="full_name" required value="<?php echo htmlspecialchars($user['full_name']); ?>" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm">
        </div>

        <div>
            <label for="username" class="block text-sm font-medium text-gray-700">Username</label>
            <input type="text" name="username" id="username" required value="<?php echo htmlspecialchars($user['username']); ?>" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm">
        </div>

        <div>
            <label for="email" class="block text-sm font-medium text-gray-700">Email</label>
            <input type="email" name="email" id="email" required value="<?php echo htmlspecialchars($user['email']); ?>" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm">
        </div>

        <div class="flex justify-end space-x-3">
            <a href="index.php?page=manage_users" class="inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                Cancel
            </a>
            <button type="submit" name="update_user" class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                Save Changes
            </button>
        </div>
    </form>
    <?php endif; ?>
</div>