<?php
include "include/db.php"; // Include database connection
include "include/header.php";

// Initialize variables
$errors = [];
$success = '';
$user = null;

// Fetch user data
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    $errors[] = "Invalid user ID.";
} else {
    $stmt = $conn->prepare("SELECT id, name, phone, role, profile_pic, bio, status FROM users WHERE id = ?");
    $stmt->bind_param("i", $_GET['id']);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows === 0) {
        $errors[] = "User not found.";
    } else {
        $user = $result->fetch_assoc();
    }
    $stmt->close();
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $user) {
    $name = trim($_POST['name'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $password = trim($_POST['password'] ?? '');
    $confirm_password = trim($_POST['confirm_password'] ?? '');
    $role = trim($_POST['role'] ?? '');
    $bio = trim($_POST['bio'] ?? '');
    $status = trim($_POST['status'] ?? '');
    $profile_pic = $user['profile_pic']; // Retain existing picture if not updated

    // Validation
    if (empty($name)) $errors[] = "Name is required.";
    if (empty($phone) || !preg_match('/^[0-9]{10,15}$/', $phone)) $errors[] = "Phone must be a valid number (10-15 digits).";
    if ($password && ($password !== $confirm_password)) $errors[] = "Passwords do not match.";
    if (empty($role)) $errors[] = "Role is required.";
    if (empty($status)) $errors[] = "Status is required.";

    // Handle profile picture upload
    if (isset($_FILES['profile_pic']) && $_FILES['profile_pic']['error'] !== UPLOAD_ERR_NO_FILE) {
        $allowed_types = ['image/jpeg', 'image/png', 'image/gif'];
        $max_size = 2 * 1024 * 1024; // 2MB
        if (!in_array($_FILES['profile_pic']['type'], $allowed_types)) {
            $errors[] = "Profile picture must be JPEG, PNG, or GIF.";
        } elseif ($_FILES['profile_pic']['size'] > $max_size) {
            $errors[] = "Profile picture must be less than 2MB.";
        } else {
            $upload_dir = 'uploads/';
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0755, true);
            }
            $ext = pathinfo($_FILES['profile_pic']['name'], PATHINFO_EXTENSION);
            $filename = 'profile_' . $user['id'] . '_' . time() . '.' . $ext;
            $upload_path = $upload_dir . $filename;
            if (move_uploaded_file($_FILES['profile_pic']['tmp_name'], $upload_path)) {
                $profile_pic = $upload_path;
                // Delete old profile picture if it exists
                if ($user['profile_pic'] && file_exists($user['profile_pic'])) {
                    unlink($user['profile_pic']);
                }
            } else {
                $errors[] = "Failed to upload profile picture.";
            }
        }
    }

    // If no errors, update the user
    if (empty($errors)) {
        $query = "UPDATE users SET name = ?, phone = ?, role = ?, profile_pic = ?, bio = ?, status = ?";
        $params = [$name, $phone, $role, $profile_pic, $bio, $status];
        $types = "ssssss";
        if ($password) {
            $hashed_password = password_hash($password, PASSWORD_DEFAULT);
            $query .= ", password = ?";
            $params[] = $hashed_password;
            $types .= "s";
        }
        $query .= " WHERE id = ?";
        $params[] = $user['id'];
        $types .= "i";

        $stmt = $conn->prepare($query);
        $stmt->bind_param($types, ...$params);
        if ($stmt->execute()) {
            $success = "User updated successfully!";
            // Refresh user data
            $stmt = $conn->prepare("SELECT id, name, phone, role, profile_pic, bio, status FROM users WHERE id = ?");
            $stmt->bind_param("i", $user['id']);
            $stmt->execute();
            $user = $stmt->get_result()->fetch_assoc();
            $_POST = []; // Reset form fields
        } else {
            $errors[] = "Failed to update user: " . $conn->error;
        }
        $stmt->close();
    }
}
?>

<!-- Content -->
<div id="content" class="content ml-64 p-6 min-h-screen">
    <style>
        /* Tailwind CSS CDN (embedded for top-class design) */
        @import url('https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css');

        /* Custom styles for enhanced design */
        body { overflow-x: hidden; font-family: 'Inter', sans-serif; }
        .content { transition: margin-left 0.3s ease; }
        .form-section { transition: transform 0.2s ease, box-shadow 0.2s ease; }
        .form-section:hover { transform: translateY(-5px); box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15); }
        .top-nav { background: linear-gradient(90deg, #1F2937, #374151); }
        input, textarea, select { transition: all 0.2s ease; }
        input:focus, textarea:focus, select:focus { ring: 2px solid #F59E0B; }
        .error { color: #DC2626; }
        .success { color: #10B981; font-size: 1.25rem; font-weight: bold; }
        .profile-pic-preview { max-width: 100px; max-height: 100px; object-fit: cover; }
        @media (max-width: 768px) {
            .content { margin-left: 0; }
            .content.open { margin-left: 0; }
            .search { display: none; }
        }
        @media (min-width: 769px) {
            .content { margin-left: 250px; }
        }
    </style>

    <!-- Top Nav -->
    <nav class="top-nav sticky top-0 text-white p-4 flex justify-between items-center shadow-lg z-40">
        <div class="logo text-2xl font-bold">CourseLMS Admin</div>
        <div class="search flex-1 max-w-xs mx-4">
            <input type="text" placeholder="Search students..." class="w-full p-2 border border-gray-300 rounded-md bg-white text-gray-900 focus:outline-none focus:ring-2 focus:ring-yellow-500">
        </div>
        <div class="right-nav flex items-center gap-4">
            <i class="fas fa-bell text-xl p-2 rounded-full hover:bg-yellow-500 cursor-pointer" title="Notifications"></i>
            <i class="fas fa-envelope text-xl p-2 rounded-full hover:bg-yellow-500 cursor-pointer" title="Messages"></i>
            <div class="profile flex items-center gap-2">
                <img src="https://via.placeholder.com/40" alt="Profile" class="w-10 h-10 rounded-full">
                <span class="text-white">Admin</span>
            </div>
            <i id="toggle" class="fas fa-bars text-xl p-2 rounded-full hover:bg-yellow-500 cursor-pointer" title="Toggle Menu"></i>
        </div>
    </nav>

    <!-- Edit Student Form -->
    <div class="form-section bg-white p-6 rounded-lg shadow-md w-full max-w-2xl mx-auto my-6">
        <h2 class="text-xl font-semibold text-gray-900 mb-4">Edit Student</h2>
        
        <!-- Success/Error Messages -->
        <?php if ($success): ?>
            <p class="success text-center mb-4"><?php echo htmlspecialchars($success); ?></p>
        <?php endif; ?>
        <?php if (!empty($errors)): ?>
            <ul class="error mb-4">
                <?php foreach ($errors as $error): ?>
                    <li><?php echo htmlspecialchars($error); ?></li>
                <?php endforeach; ?>
            </ul>
        <?php endif; ?>

        <?php if ($user): ?>
            <!-- Edit Form -->
            <form method="POST" enctype="multipart/form-data" class="space-y-4">
                <div>
                    <label for="name" class="block text-sm font-medium text-gray-700">Name</label>
                    <input type="text" id="name" name="name" value="<?php echo isset($_POST['name']) ? htmlspecialchars($_POST['name']) : htmlspecialchars($user['name']); ?>" class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-yellow-500" required>
                </div>
                <div>
                    <label for="phone" class="block text-sm font-medium text-gray-700">Phone</label>
                    <input type="text" id="phone" name="phone" value="<?php echo isset($_POST['phone']) ? htmlspecialchars($_POST['phone']) : htmlspecialchars($user['phone']); ?>" class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-yellow-500" required>
                </div>
                <div>
                    <label for="password" class="block text-sm font-medium text-gray-700">New Password (leave blank to keep current)</label>
                    <input type="password" id="password" name="password" class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-yellow-500">
                </div>
                <div>
                    <label for="confirm_password" class="block text-sm font-medium text-gray-700">Confirm New Password</label>
                    <input type="password" id="confirm_password" name="confirm_password" class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-yellow-500">
                </div>
                <div>
                    <label for="role" class="block text-sm font-medium text-gray-700">Role</label>
                    <select id="role" name="role" class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-yellow-500" required>
                        <option value="">Select role</option>
                        <option value="student" <?php echo (isset($_POST['role']) && $_POST['role'] === 'student') || (!isset($_POST['role']) && $user['role'] === 'student') ? 'selected' : ''; ?>>Student</option>
                        <option value="admin" <?php echo (isset($_POST['role']) && $_POST['role'] === 'admin') || (!isset($_POST['role']) && $user['role'] === 'admin') ? 'selected' : ''; ?>>Admin</option>
                    </select>
                </div>
                <div>
                    <label for="profile_pic" class="block text-sm font-medium text-gray-700">Profile Picture (JPEG, PNG, GIF, max 2MB)</label>
                    <input type="file" id="profile_pic" name="profile_pic" accept="image/jpeg,image/png,image/gif" class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-yellow-500">
                    <?php if ($user['profile_pic']): ?>
                        <img src="<?php echo htmlspecialchars($user['profile_pic']); ?>" alt="Current Profile Pic" class="profile-pic-preview mt-2 rounded-md">
                    <?php else: ?>
                        <img src="https://via.placeholder.com/100" alt="No Profile Pic" class="profile-pic-preview mt-2 rounded-md">
                    <?php endif; ?>
                </div>
                <div>
                    <label for="bio" class="block text-sm font-medium text-gray-700">Bio</label>
                    <textarea id="bio" name="bio" rows="4" class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-yellow-500"><?php echo isset($_POST['bio']) ? htmlspecialchars($_POST['bio']) : htmlspecialchars($user['bio'] ?? ''); ?></textarea>
                </div>
                <div>
                    <label for="status" class="block text-sm font-medium text-gray-700">Status</label>
                    <select id="status" name="status" class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-yellow-500" required>
                        <option value="">Select status</option>
                        <option value="active" <?php echo (isset($_POST['status']) && $_POST['status'] === 'active') || (!isset($_POST['status']) && $user['status'] === 'active') ? 'selected' : ''; ?>>Active</option>
                        <option value="inactive" <?php echo (isset($_POST['status']) && $_POST['status'] === 'inactive') || (!isset($_POST['status']) && $user['status'] === 'inactive') ? 'selected' : ''; ?>>Inactive</option>
                    </select>
                </div>
                <div class="flex gap-4">
                    <button type="submit" class="flex-1 bg-yellow-500 text-white p-2 rounded-md hover:bg-yellow-600 transition-colors">Update Student</button>
                    <a href="student_list.php" class="flex-1 bg-gray-500 text-white p-2 rounded-md hover:bg-gray-600 transition-colors text-center">Cancel</a>
                </div>
            </form>
        <?php else: ?>
            <p class="text-center text-gray-700">No user found to edit.</p>
        <?php endif; ?>
    </div>
</div>

<?php
include "include/footer.php";
$conn->close(); // Close database connection
?>