<?php
include '../config.php';

if (!isAdmin()) {
    redirect('../login.php');
}

// Get user ID from URL
if (!isset($_GET['id']) || empty($_GET['id'])) {
    $_SESSION['error'] = "User ID tidak valid!";
    header("Location: manage_users.php");
    exit();
}

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

// Get user data
$user_result = $conn->query("SELECT * FROM lms_users WHERE id = $user_id");
if ($user_result->num_rows == 0) {
    $_SESSION['error'] = "User tidak ditemukan!";
    header("Location: manage_users.php");
    exit();
}

$user = $user_result->fetch_assoc();

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $username = $conn->real_escape_string($_POST['username']);
    $nama_lengkap = $conn->real_escape_string($_POST['nama_lengkap']);
    $email = $conn->real_escape_string($_POST['email']);
    $role = $conn->real_escape_string($_POST['role']);
    $phone = $conn->real_escape_string($_POST['phone']);
    $bio = $conn->real_escape_string($_POST['bio']);
    $status = $conn->real_escape_string($_POST['status']);
    
    // Check if username or email already exists (excluding current user)
    $check_user = $conn->query("SELECT id FROM lms_users WHERE (username = '$username' OR email = '$email') AND id != $user_id");
    
    if ($check_user->num_rows > 0) {
        $_SESSION['error'] = "Username atau email sudah digunakan!";
    } else {
        // Update user
        $sql = "UPDATE lms_users SET 
                username = '$username',
                nama_lengkap = '$nama_lengkap',
                email = '$email',
                role = '$role',
                phone = '$phone',
                bio = '$bio',
                status = '$status'
                WHERE id = $user_id";
        
        if ($conn->query($sql)) {
            $_SESSION['success'] = "User berhasil diperbarui!";
            header("Location: manage_users.php");
            exit();
        } else {
            $_SESSION['error'] = "Error: " . $conn->error;
        }
    }
    
    // Refresh user data after update
    $user_result = $conn->query("SELECT * FROM lms_users WHERE id = $user_id");
    $user = $user_result->fetch_assoc();
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit User - SMANSAB LMS</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
</head>
<body>
    <!-- Navbar Admin -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container">
            <a class="navbar-brand fw-bold" href="dashboard.php">SMANSAB LMS - Admin</a>
            <div class="navbar-nav ms-auto">
                <a class="nav-link" href="manage_users.php">Kelola User</a>
                <a class="nav-link" href="manage_courses.php">Kelola Kursus</a>
                <a class="nav-link" href="../logout.php">Logout</a>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h4 class="mb-0">Edit User</h4>
                        <a href="manage_users.php" class="btn btn-secondary btn-sm">
                            <i class="bi bi-arrow-left"></i> Kembali
                        </a>
                    </div>
                    <div class="card-body">
                        <!-- Alert Messages -->
                        <?php if (isset($_SESSION['error'])): ?>
                            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                <?php echo $_SESSION['error']; unset($_SESSION['error']); ?>
                                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                            </div>
                        <?php endif; ?>

                        <form method="POST" action="">
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <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="col-md-6">
                                    <label for="email" class="form-label">Email *</label>
                                    <input type="email" class="form-control" id="email" name="email" 
                                           value="<?php echo htmlspecialchars($user['email']); ?>" required>
                                </div>
                                
                                <div class="col-12">
                                    <label for="nama_lengkap" class="form-label">Nama Lengkap *</label>
                                    <input type="text" class="form-control" id="nama_lengkap" name="nama_lengkap" 
                                           value="<?php echo htmlspecialchars($user['nama_lengkap']); ?>" required>
                                </div>
                                
                                <div class="col-md-6">
                                    <label for="role" class="form-label">Role *</label>
                                    <select class="form-select" id="role" name="role" required>
                                        <option value="">Pilih Role</option>
                                        <option value="admin" <?php echo $user['role'] == 'admin' ? 'selected' : ''; ?>>Admin</option>
                                        <option value="guru" <?php echo $user['role'] == 'guru' ? 'selected' : ''; ?>>Guru</option>
                                        <option value="siswa" <?php echo $user['role'] == 'siswa' ? 'selected' : ''; ?>>Siswa</option>
                                    </select>
                                </div>
                                
                                <div class="col-md-6">
                                    <label for="status" class="form-label">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>
                                
                                <div class="col-md-6">
                                    <label for="phone" class="form-label">Nomor Telepon</label>
                                    <input type="text" class="form-control" id="phone" name="phone" 
                                           value="<?php echo htmlspecialchars($user['phone'] ?? ''); ?>">
                                </div>
                                
                                <div class="col-md-6">
                                    <label class="form-label">Tanggal Daftar</label>
                                    <input type="text" class="form-control" value="<?php echo date('d/m/Y H:i', strtotime($user['tanggal_daftar'])); ?>" readonly>
                                </div>
                                
                                <div class="col-12">
                                    <label for="bio" class="form-label">Bio</label>
                                    <textarea class="form-control" id="bio" name="bio" rows="3"><?php echo htmlspecialchars($user['bio'] ?? ''); ?></textarea>
                                </div>
                                
                                <div class="col-12">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <div>
                                            <button type="submit" class="btn btn-primary">
                                                <i class="bi bi-check-circle"></i> Update User
                                            </button>
                                            <a href="manage_users.php" class="btn btn-secondary">Batal</a>
                                        </div>
                                        <a href="?action=reset_password&id=<?php echo $user_id; ?>" 
                                           class="btn btn-outline-info btn-sm"
                                           onclick="return confirm('Yakin ingin mereset password user ini menjadi \\'123\\'?')">
                                            <i class="bi bi-key"></i> Reset Password
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>