<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
if (!isset($_SESSION['admin'])) {
    header('Location: login.php');
    exit();
}

include 'db.php';
if (!$conn) {
    die("Database connection failed: " . mysqli_connect_error());
}

// Validate user ID
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    echo "<div class='alert alert-danger'>Invalid user ID.</div>";
    exit();
}

$user_id = (int)$_GET['id'];

// Fetch user
$stmt = $conn->prepare("SELECT UserID, FullName, Email, PhoneNumber, Username, Status FROM users WHERE UserID = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();
$stmt->close();

if (!$user) {
    echo "<div class='alert alert-danger'>User not found.</div>";
    exit();
}

// Handle form submission
if (isset($_POST['update_profile'])) {
    $username = trim($_POST['username']);
    $full_name = trim($_POST['full_name']);
    $email = trim($_POST['email']);
    $phone_number = trim($_POST['phone_number']);
    $status = $_POST['status'];

    // Validate inputs
    if (empty($username) || empty($full_name) || empty($email) || !in_array($status, ['active', 'inactive'])) {
        echo "<div class='alert alert-danger'>Please fill all required fields and select a valid status.</div>";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo "<div class='alert alert-danger'>Invalid email format.</div>";
    } else {
        // Update user
        $stmt = $conn->prepare("UPDATE users SET Username = ?, FullName = ?, Email = ?, PhoneNumber = ?, Status = ? WHERE UserID = ?");
        $stmt->bind_param("sssssi", $username, $full_name, $email, $phone_number, $status, $user_id);
        if ($stmt->execute()) {
            $_SESSION['success_message'] = "Profile updated successfully!";
            header("Location: profile_management.php");
            exit;
        } else {
            echo "<div class='alert alert-danger'>Error: " . $stmt->error . "</div>";
        }
        $stmt->close();
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit User Profile</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f0f4f8;
        }
        .container {
            max-width: 600px;
            margin-top: 50px;
        }
    </style>
</head>
<body>
<div class="container">
    <h2>Edit User Profile</h2>

    <!-- Edit Profile Form -->
    <form method="post">
        <input type="hidden" name="user_id" value="<?php echo htmlspecialchars($user['UserID']); ?>">
        <div class="mb-3">
            <label for="username" class="form-label">Username</label>
            <input type="text" class="form-control" id="username" name="username" value="<?php echo htmlspecialchars($user['Username']); ?>" required>
        </div>
        <div class="mb-3">
            <label for="full_name" class="form-label">Full Name</label>
            <input type="text" class="form-control" id="full_name" name="full_name" value="<?php echo htmlspecialchars($user['FullName']); ?>" required>
        </div>
        <div class="mb-3">
            <label for="email" class="form-label">Email Address</label>
            <input type="email" class="form-control" id="email" name="email" value="<?php echo htmlspecialchars($user['Email']); ?>" required>
        </div>
        <div class="mb-3">
            <label for="phone_number" class="form-label">Phone Number</label>
            <input type="text" class="form-control" id="phone_number" name="phone_number" value="<?php echo htmlspecialchars($user['PhoneNumber']); ?>">
        </div>
        <div class="mb-3">
            <label for="status" class="form-label">Account Status</label>
            <select class="form-select" id="status" name="status" required>
                <option value="active" <?php echo $user['Status'] === 'active' ? 'selected' : ''; ?>>Active</option>
                <option value="inactive" <?php echo $user['Status'] === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
            </select>
        </div>
        <button type="submit" name="update_profile" class="btn btn-primary">Update Profile</button>
        <a href="profile_management.php" class="btn btn-secondary">Cancel</a>
    </form>
</div>
</body>
</html>