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

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

$guru_id = $_SESSION['user_id'];

// Get guru data
$sql_guru = "SELECT * FROM lms_users WHERE id = ?";
$stmt_guru = $conn->prepare($sql_guru);
$stmt_guru->bind_param('i', $guru_id);
$stmt_guru->execute();
$guru = $stmt_guru->get_result()->fetch_assoc();

// Get guru statistics
$sql_stats = "SELECT 
    COUNT(DISTINCT c.id) as total_lms_courses,
    COUNT(DISTINCT e.id_siswa) as total_students,
    AVG(c.rating) as avg_rating,
    SUM(c.total_siswa) as total_lms_enrollments
    FROM lms_courses c
    LEFT JOIN lms_enrollments e ON c.id = e.id_course
    WHERE c.id_guru = ?";
$stmt_stats = $conn->prepare($sql_stats);
$stmt_stats->bind_param('i', $guru_id);
$stmt_stats->execute();
$stats = $stmt_stats->get_result()->fetch_assoc();

// Handle profile update
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = isset($_POST['action']) ? sanitize($_POST['action']) : '';
    
    if ($action === 'update_profile') {
        $nama_lengkap = isset($_POST['nama_lengkap']) ? sanitize($_POST['nama_lengkap']) : '';
        $email = isset($_POST['email']) ? sanitize($_POST['email']) : '';
        $bio = isset($_POST['bio']) ? sanitize($_POST['bio']) : '';
        $phone = isset($_POST['phone']) ? sanitize($_POST['phone']) : '';
        
        $errors = [];
        
        if (empty($nama_lengkap)) {
            $errors[] = "Nama lengkap harus diisi";
        }
        
        if (empty($email)) {
            $errors[] = "Email harus diisi";
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $errors[] = "Format email tidak valid";
        }
        
        // Check if email already exists (excluding current user)
        $check_email_sql = "SELECT id FROM lms_users WHERE email = ? AND id != ?";
        $check_email_stmt = $conn->prepare($check_email_sql);
        $check_email_stmt->bind_param('si', $email, $guru_id);
        $check_email_stmt->execute();
        $email_exists = $check_email_stmt->get_result()->num_rows > 0;
        $check_email_stmt->close();
        
        if ($email_exists) {
            $errors[] = "Email sudah digunakan oleh pengguna lain";
        }
        
        // Handle profile picture upload
        $foto_profil = $guru['foto_profil']; // Keep existing if no new upload
        
        if (isset($_FILES['foto_profil']) && $_FILES['foto_profil']['error'] === 0) {
            $allowed_types = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'];
            $max_size = 2 * 1024 * 1024; // 2MB
            
            if (in_array($_FILES['foto_profil']['type'], $allowed_types)) {
                if ($_FILES['foto_profil']['size'] <= $max_size) {
                    $upload_dir = '../uploads/profiles/';
                    if (!is_dir($upload_dir)) {
                        mkdir($upload_dir, 0755, true);
                    }
                    
                    $file_extension = pathinfo($_FILES['foto_profil']['name'], PATHINFO_EXTENSION);
                    $new_filename = 'profile_' . $guru_id . '_' . time() . '.' . $file_extension;
                    $upload_path = $upload_dir . $new_filename;
                    
                    if (move_uploaded_file($_FILES['foto_profil']['tmp_name'], $upload_path)) {
                        // Delete old profile picture if exists
                        if (!empty($guru['foto_profil']) && file_exists('../uploads/' . $guru['foto_profil'])) {
                            unlink('../uploads/' . $guru['foto_profil']);
                        }
                        $foto_profil = 'profiles/' . $new_filename;
                    } else {
                        $errors[] = "Gagal mengupload foto profil";
                    }
                } else {
                    $errors[] = "Ukuran file terlalu besar. Maksimal 2MB";
                }
            } else {
                $errors[] = "Format file tidak didukung. Gunakan JPG, PNG, atau GIF";
            }
        }
        
        if (empty($errors)) {
            $update_sql = "UPDATE lms_users SET 
                          nama_lengkap = ?, email = ?, bio = ?, phone = ?, foto_profil = ?
                          WHERE id = ?";
            
            $update_stmt = $conn->prepare($update_sql);
            $update_stmt->bind_param('sssssi', $nama_lengkap, $email, $bio, $phone, $foto_profil, $guru_id);
            
            if ($update_stmt->execute()) {
                $_SESSION['success'] = "Profil berhasil diperbarui!";
                $_SESSION['nama_lengkap'] = $nama_lengkap; // Update session
                
                // Refresh guru data
                $stmt_guru->execute();
                $guru = $stmt_guru->get_result()->fetch_assoc();
            } else {
                $_SESSION['error'] = "Gagal memperbarui profil: " . $conn->error;
            }
            $update_stmt->close();
        } else {
            $_SESSION['error'] = implode("<br>", $errors);
        }
    }
    elseif ($action === 'change_password') {
        $current_password = isset($_POST['current_password']) ? $_POST['current_password'] : '';
        $new_password = isset($_POST['new_password']) ? $_POST['new_password'] : '';
        $confirm_password = isset($_POST['confirm_password']) ? $_POST['confirm_password'] : '';
        
        $errors = [];
        
        if (empty($current_password)) {
            $errors[] = "Password saat ini harus diisi";
        }
        
        if (empty($new_password)) {
            $errors[] = "Password baru harus diisi";
        } elseif (strlen($new_password) < 6) {
            $errors[] = "Password baru minimal 6 karakter";
        }
        
        if ($new_password !== $confirm_password) {
            $errors[] = "Konfirmasi password tidak sesuai";
        }
        
        // Verify current password
        if (empty($errors)) {
            $verify_sql = "SELECT password FROM lms_users WHERE id = ?";
            $verify_stmt = $conn->prepare($verify_sql);
            $verify_stmt->bind_param('i', $guru_id);
            $verify_stmt->execute();
            $verify_result = $verify_stmt->get_result()->fetch_assoc();
            $verify_stmt->close();
            
            if (!password_verify($current_password, $verify_result['password'])) {
                $errors[] = "Password saat ini salah";
            }
        }
        
        if (empty($errors)) {
            $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
            
            $update_sql = "UPDATE lms_users SET password = ? WHERE id = ?";
            $update_stmt = $conn->prepare($update_sql);
            $update_stmt->bind_param('si', $hashed_password, $guru_id);
            
            if ($update_stmt->execute()) {
                $_SESSION['success'] = "Password berhasil diubah!";
            } else {
                $_SESSION['error'] = "Gagal mengubah password: " . $conn->error;
            }
            $update_stmt->close();
        } else {
            $_SESSION['error'] = implode("<br>", $errors);
        }
    }
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Profil Saya - 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">
    <style>
        :root {
            --primary-color: #3f51b5;
            --secondary-color: #f5f5f5;
        }
        
        .sidebar {
            background: var(--primary-color);
            color: white;
            min-height: 100vh;
            padding: 0;
        }
        
        .sidebar-sticky {
            position: sticky;
            top: 0;
            height: 100vh;
            padding-top: 20px;
            overflow-y: auto;
        }
        
        .sidebar .nav-link {
            color: rgba(255, 255, 255, 0.8);
            padding: 12px 20px;
            margin: 2px 0;
            border-radius: 0;
            transition: all 0.3s;
        }
        
        .sidebar .nav-link:hover {
            color: white;
            background: rgba(255, 255, 255, 0.1);
        }
        
        .sidebar .nav-link.active {
            color: white;
            background: rgba(255, 255, 255, 0.2);
            border-left: 4px solid #fff;
        }
        
        .sidebar .nav-link i {
            width: 20px;
            margin-right: 10px;
        }
        
        .main-content {
            background: #f8f9fa;
            min-height: 100vh;
        }
        
        .navbar-custom {
            background: white;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .profile-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 60px 0;
            margin-bottom: 40px;
        }
        
        .profile-container {
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            margin-bottom: 30px;
        }
        
        .stats-card {
            background: white;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
            border: none;
        }
        
        .profile-avatar {
            width: 150px;
            height: 150px;
            border-radius: 50%;
            object-fit: cover;
            border: 5px solid white;
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
        }
        
        .avatar-placeholder {
            width: 150px;
            height: 150px;
            border-radius: 50%;
            background: var(--primary-color);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 3rem;
            border: 5px solid white;
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
        }
        
        .nav-tabs-custom .nav-link {
            border: none;
            padding: 15px 25px;
            font-weight: 500;
            color: #6c757d;
            border-bottom: 3px solid transparent;
        }
        
        .nav-tabs-custom .nav-link.active {
            color: var(--primary-color);
            border-bottom: 3px solid var(--primary-color);
            background: transparent;
        }
        
        .tab-content {
            background: white;
            border-radius: 0 0 15px 15px;
            padding: 30px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .form-container {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 25px;
            margin-bottom: 20px;
        }
        
        .profile-info-item {
            display: flex;
            justify-content: between;
            align-items: center;
            padding: 10px 0;
            border-bottom: 1px solid #e9ecef;
        }
        
        .profile-info-item:last-child {
            border-bottom: none;
        }
        
        .info-label {
            font-weight: 600;
            color: #495057;
            min-width: 150px;
        }
        
        .info-value {
            color: #6c757d;
        }
        
        .upload-btn {
            position: relative;
            overflow: hidden;
            display: inline-block;
        }
        
        .upload-btn input[type=file] {
            position: absolute;
            left: 0;
            top: 0;
            opacity: 0;
            width: 100%;
            height: 100%;
            cursor: pointer;
        }
        
        .progress-course {
            height: 8px;
            border-radius: 4px;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <div class="col-md-3 col-lg-2 sidebar">
                <div class="sidebar-sticky">
                    <div class="text-center mb-4">
                        <h4 class="fw-bold">
                            <i class="bi bi-book-half"></i><br>
                            SMANSAB LMS
                        </h4>
                        <small class="text-white-50">Guru Dashboard</small>
                    </div>
                    
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link" href="dashboard.php">
                                <i class="bi bi-speedometer2"></i> Dashboard
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="my_courses.php">
                                <i class="bi bi-journal-bookmark"></i> Kursus Saya
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="manage_lessons.php">
                                <i class="bi bi-collection-play"></i> Kelola Materi
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="manage_quizzes.php">
                                <i class="bi bi-pencil-square"></i> Kelola Kuis
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="students_progress.php">
                                <i class="bi bi-graph-up"></i> Progress Siswa
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active" href="profile.php">
                                <i class="bi bi-person"></i> Profil Saya
                            </a>
                        </li>
                        <li class="nav-item mt-4">
                            <a class="nav-link" href="../logout.php">
                                <i class="bi bi-box-arrow-right"></i> Logout
                            </a>
                        </li>
                    </ul>
                    
                    <div class="mt-5 px-3">
                        <small class="text-white-50">
                            <i class="bi bi-info-circle"></i> Butuh bantuan?
                            <a href="#" class="text-white">Hubungi Admin</a>
                        </small>
                    </div>
                </div>
            </div>

            <!-- Main Content -->
            <div class="col-md-9 col-lg-10 main-content">
                <!-- Top Navbar -->
                <nav class="navbar navbar-custom">
                    <div class="container-fluid">
                        <div class="d-flex align-items-center">
                            <button class="btn btn-outline-primary me-3 d-md-none" type="button">
                                <i class="bi bi-list"></i>
                            </button>
                            <h5 class="mb-0">Profil Saya</h5>
                        </div>
                        <div class="d-flex align-items-center">
                            <div class="dropdown">
                                <button class="btn btn-outline-primary dropdown-toggle" type="button" 
                                        data-bs-toggle="dropdown">
                                    <i class="bi bi-person-circle me-2"></i>
                                    <?php echo $_SESSION['nama_lengkap']; ?>
                                </button>
                                <ul class="dropdown-menu">
                                    <li><a class="dropdown-item" href="profile.php">
                                        <i class="bi bi-person me-2"></i>Profil
                                    </a></li>
                                    <li><a class="dropdown-item" href="my_courses.php">
                                        <i class="bi bi-journal-bookmark me-2"></i>Kursus Saya
                                    </a></li>
                                    <li><hr class="dropdown-divider"></li>
                                    <li><a class="dropdown-item" href="../logout.php">
                                        <i class="bi bi-box-arrow-right me-2"></i>Logout
                                    </a></li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </nav>

                <div class="container-fluid">
                    <!-- Profile Header -->
                    <div class="profile-header">
                        <div class="container">
                            <div class="row align-items-center">
                                <div class="col-md-3 text-center">
                                    <?php if (!empty($guru['foto_profil'])): ?>
                                        <img src="../uploads/<?php echo $guru['foto_profil']; ?>" 
                                             alt="<?php echo htmlspecialchars($guru['nama_lengkap']); ?>" 
                                             class="profile-avatar">
                                    <?php else: ?>
                                        <div class="avatar-placeholder mx-auto">
                                            <i class="bi bi-person-fill"></i>
                                        </div>
                                    <?php endif; ?>
                                </div>
                                <div class="col-md-9">
                                    <h1 class="display-5 fw-bold mb-2"><?php echo htmlspecialchars($guru['nama_lengkap']); ?></h1>
                                    <p class="lead mb-3 opacity-75">
                                        <i class="bi bi-award me-2"></i>Guru Profesional - SMANSAB LMS
                                    </p>
                                    <p class="mb-4 opacity-75">
                                        <?php echo !empty($guru['bio']) ? htmlspecialchars($guru['bio']) : 'Guru yang berdedikasi dalam membagikan pengetahuan dan pengalaman.'; ?>
                                    </p>
                                    
                                    <div class="row text-center">
                                        <div class="col-md-3 col-6 mb-3">
                                            <div class="text-white">
                                                <i class="bi bi-journal-bookmark display-6 mb-2"></i>
                                                <h4 class="fw-bold"><?php echo $stats['total_lms_courses'] ?? 0; ?></h4>
                                                <small>Total Kursus</small>
                                            </div>
                                        </div>
                                        <div class="col-md-3 col-6 mb-3">
                                            <div class="text-white">
                                                <i class="bi bi-people display-6 mb-2"></i>
                                                <h4 class="fw-bold"><?php echo $stats['total_students'] ?? 0; ?></h4>
                                                <small>Total Siswa</small>
                                            </div>
                                        </div>
                                        <div class="col-md-3 col-6 mb-3">
                                            <div class="text-white">
                                                <i class="bi bi-star display-6 mb-2"></i>
                                                <h4 class="fw-bold"><?php echo number_format($stats['avg_rating'] ?? 0, 1); ?></h4>
                                                <small>Rating Rata-rata</small>
                                            </div>
                                        </div>
                                        <div class="col-md-3 col-6 mb-3">
                                            <div class="text-white">
                                                <i class="bi bi-bookmark-check display-6 mb-2"></i>
                                                <h4 class="fw-bold"><?php echo $stats['total_lms_enrollments'] ?? 0; ?></h4>
                                                <small>Total Pendaftaran</small>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="container">
                        <!-- Tabs Navigation -->
                        <ul class="nav nav-tabs nav-tabs-custom" id="profileTabs" role="tablist">
                            <li class="nav-item" role="presentation">
                                <button class="nav-link active" id="overview-tab" data-bs-toggle="tab" data-bs-target="#overview" type="button" role="tab">
                                    <i class="bi bi-person me-2"></i>Overview Profil
                                </button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link" id="edit-tab" data-bs-toggle="tab" data-bs-target="#edit" type="button" role="tab">
                                    <i class="bi bi-pencil me-2"></i>Edit Profil
                                </button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link" id="security-tab" data-bs-toggle="tab" data-bs-target="#security" type="button" role="tab">
                                    <i class="bi bi-shield-lock me-2"></i>Keamanan
                                </button>
                            </li>
                        </ul>

                        <!-- Tabs Content -->
                        <div class="tab-content" id="profileTabsContent">
                            <!-- Tab 1: Overview Profil -->
                            <div class="tab-pane fade show active" id="overview" role="tabpanel">
                                <div class="row">
                                    <div class="col-lg-8">
                                        <!-- Informasi Pribadi -->
                                        <div class="profile-container">
                                            <h4 class="fw-bold mb-4">
                                                <i class="bi bi-info-circle me-2"></i>Informasi Pribadi
                                            </h4>
                                            
                                            <div class="profile-info-list">
                                                <div class="profile-info-item">
                                                    <span class="info-label">Nama Lengkap</span>
                                                    <span class="info-value"><?php echo htmlspecialchars($guru['nama_lengkap']); ?></span>
                                                </div>
                                                <div class="profile-info-item">
                                                    <span class="info-label">Email</span>
                                                    <span class="info-value"><?php echo htmlspecialchars($guru['email']); ?></span>
                                                </div>
                                                <div class="profile-info-item">
                                                    <span class="info-label">Username</span>
                                                    <span class="info-value"><?php echo htmlspecialchars($guru['username']); ?></span>
                                                </div>
                                                <div class="profile-info-item">
                                                    <span class="info-label">Nomor Telepon</span>
                                                    <span class="info-value"><?php echo !empty($guru['phone']) ? htmlspecialchars($guru['phone']) : '-'; ?></span>
                                                </div>
                                                <div class="profile-info-item">
                                                    <span class="info-label">Bergabung Sejak</span>
                                                    <span class="info-value"><?php echo date('d F Y', strtotime($guru['tanggal_daftar'])); ?></span>
                                                </div>
                                                <div class="profile-info-item">
                                                    <span class="info-label">Status</span>
                                                    <span class="info-value">
                                                        <span class="badge bg-success">Aktif</span>
                                                    </span>
                                                </div>
                                            </div>
                                            
                                            <?php if (!empty($guru['bio'])): ?>
                                                <div class="mt-4">
                                                    <h6 class="fw-bold mb-3">Tentang Saya</h6>
                                                    <p class="text-muted"><?php echo nl2br(htmlspecialchars($guru['bio'])); ?></p>
                                                </div>
                                            <?php endif; ?>
                                        </div>

                                        <!-- Aktivitas Terbaru -->
                                        <div class="profile-container">
                                            <h4 class="fw-bold mb-4">
                                                <i class="bi bi-clock-history me-2"></i>Aktivitas Terbaru
                                            </h4>
                                            
                                            <div class="activity-list">
                                                <div class="alert alert-light d-flex align-items-center mb-3">
                                                    <i class="bi bi-plus-circle text-success me-3 fs-4"></i>
                                                    <div>
                                                        <div class="fw-semibold">Membuat kursus baru</div>
                                                        <small class="text-muted">Hari ini - "Web Development Dasar"</small>
                                                    </div>
                                                </div>
                                                
                                                <div class="alert alert-light d-flex align-items-center mb-3">
                                                    <i class="bi bi-pencil-square text-primary me-3 fs-4"></i>
                                                    <div>
                                                        <div class="fw-semibold">Memperbarui materi</div>
                                                        <small class="text-muted">Kemarin - "Pemrograman PHP Lanjutan"</small>
                                                    </div>
                                                </div>
                                                
                                                <div class="alert alert-light d-flex align-items-center mb-3">
                                                    <i class="bi bi-graph-up text-warning me-3 fs-4"></i>
                                                    <div>
                                                        <div class="fw-semibold">Melihat progress siswa</div>
                                                        <small class="text-muted">2 hari yang lalu - 15 siswa aktif</small>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="col-lg-4">
                                        <!-- Statistik Cepat -->
                                        <div class="stats-card">
                                            <h5 class="fw-bold mb-4">
                                                <i class="bi bi-graph-up me-2"></i>Statistik Mengajar
                                            </h5>
                                            
                                            <div class="mb-4">
                                                <div class="d-flex justify-content-between mb-2">
                                                    <small class="text-muted">Kursus Aktif</small>
                                                    <small class="fw-semibold"><?php echo $stats['total_lms_courses'] ?? 0; ?> kursus</small>
                                                </div>
                                                <div class="progress progress-course">
                                                    <div class="progress-bar bg-primary" 
                                                         style="width: <?php echo min(($stats['total_lms_courses'] ?? 0) * 10, 100); ?>%">
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <div class="mb-4">
                                                <div class="d-flex justify-content-between mb-2">
                                                    <small class="text-muted">Siswa Terdaftar</small>
                                                    <small class="fw-semibold"><?php echo $stats['total_students'] ?? 0; ?> siswa</small>
                                                </div>
                                                <div class="progress progress-course">
                                                    <div class="progress-bar bg-success" 
                                                         style="width: <?php echo min(($stats['total_students'] ?? 0) * 2, 100); ?>%">
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <div class="mb-4">
                                                <div class="d-flex justify-content-between mb-2">
                                                    <small class="text-muted">Rating Rata-rata</small>
                                                    <small class="fw-semibold"><?php echo number_format($stats['avg_rating'] ?? 0, 1); ?>/5</small>
                                                </div>
                                                <div class="progress progress-course">
                                                    <div class="progress-bar bg-warning" 
                                                         style="width: <?php echo (($stats['avg_rating'] ?? 0) / 5) * 100; ?>%">
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Pencapaian -->
                                        <div class="stats-card">
                                            <h5 class="fw-bold mb-4">
                                                <i class="bi bi-trophy me-2"></i>Pencapaian
                                            </h5>
                                            
                                            <div class="achievement-list">
                                                <div class="d-flex align-items-center mb-3">
                                                    <div class="bg-primary rounded-circle p-2 me-3">
                                                        <i class="bi bi-journal-text text-white"></i>
                                                    </div>
                                                    <div>
                                                        <div class="fw-semibold">Guru Baru</div>
                                                        <small class="text-muted">Membuat kursus pertama</small>
                                                    </div>
                                                </div>
                                                
                                                <div class="d-flex align-items-center mb-3">
                                                    <div class="bg-success rounded-circle p-2 me-3">
                                                        <i class="bi bi-people text-white"></i>
                                                    </div>
                                                    <div>
                                                        <div class="fw-semibold">Populer</div>
                                                        <small class="text-muted">50+ siswa terdaftar</small>
                                                    </div>
                                                </div>
                                                
                                                <div class="d-flex align-items-center mb-3">
                                                    <div class="bg-warning rounded-circle p-2 me-3">
                                                        <i class="bi bi-star text-white"></i>
                                                    </div>
                                                    <div>
                                                        <div class="fw-semibold">Berkualitas</div>
                                                        <small class="text-muted">Rating 4.5+</small>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Tab 2: Edit Profil -->
                            <div class="tab-pane fade" id="edit" role="tabpanel">
                                <div class="row">
                                    <div class="col-lg-8">
                                        <div class="profile-container">
                                            <h4 class="fw-bold mb-4">
                                                <i class="bi bi-pencil-square me-2"></i>Edit Informasi Profil
                                            </h4>
                                            
                                            <form method="POST" enctype="multipart/form-data">
                                                <input type="hidden" name="action" value="update_profile">
                                                
                                                <div class="form-container">
                                                    <h6 class="fw-bold mb-3">Foto Profil</h6>
                                                    <div class="row align-items-center">
                                                        <div class="col-md-3 text-center mb-3">
                                                            <?php if (!empty($guru['foto_profil'])): ?>
                                                                <img src="../uploads/<?php echo $guru['foto_profil']; ?>" 
                                                                     alt="Current Profile" 
                                                                     class="rounded-circle" 
                                                                     width="100" height="100">
                                                            <?php else: ?>
                                                                <div class="rounded-circle bg-primary d-inline-flex align-items-center justify-content-center" 
                                                                     style="width: 100px; height: 100px;">
                                                                    <i class="bi bi-person text-white fs-2"></i>
                                                                </div>
                                                            <?php endif; ?>
                                                        </div>
                                                        <div class="col-md-9">
                                                            <div class="mb-3">
                                                                <label class="form-label">Ubah Foto Profil</label>
                                                                <div class="upload-btn">
                                                                    <button type="button" class="btn btn-outline-primary">
                                                                        <i class="bi bi-upload me-2"></i>Pilih File
                                                                    </button>
                                                                    <input type="file" name="foto_profil" accept="image/*">
                                                                </div>
                                                                <div class="form-text">
                                                                    Format: JPG, PNG, GIF. Maksimal 2MB
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                                
                                                <div class="form-container">
                                                    <h6 class="fw-bold mb-3">Informasi Pribadi</h6>
                                                    
                                                    <div class="row">
                                                        <div class="col-md-6">
                                                            <div class="mb-3">
                                                                <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($guru['nama_lengkap']); ?>" required>
                                                            </div>
                                                        </div>
                                                        <div class="col-md-6">
                                                            <div class="mb-3">
                                                                <label for="email" class="form-label">Email</label>
                                                                <input type="email" class="form-control" id="email" name="email" 
                                                                       value="<?php echo htmlspecialchars($guru['email']); ?>" required>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    
                                                    <div class="row">
                                                        <div class="col-md-6">
                                                            <div class="mb-3">
                                                                <label for="phone" class="form-label">Nomor Telepon</label>
                                                                <input type="tel" class="form-control" id="phone" name="phone" 
                                                                       value="<?php echo htmlspecialchars($guru['phone'] ?? ''); ?>">
                                                            </div>
                                                        </div>
                                                    </div>
                                                    
                                                    <div class="mb-3">
                                                        <label for="bio" class="form-label">Bio / Deskripsi Diri</label>
                                                        <textarea class="form-control" id="bio" name="bio" rows="4" 
                                                                  placeholder="Ceritakan sedikit tentang diri dan pengalaman mengajar Anda..."><?php echo htmlspecialchars($guru['bio'] ?? ''); ?></textarea>
                                                        <div class="form-text">Maksimal 500 karakter</div>
                                                    </div>
                                                </div>
                                                
                                                <div class="d-flex justify-content-between">
                                                    <button type="button" class="btn btn-outline-secondary" data-bs-toggle="tab" data-bs-target="#overview">
                                                        <i class="bi bi-arrow-left me-2"></i>Kembali
                                                    </button>
                                                    <button type="submit" class="btn btn-primary">
                                                        <i class="bi bi-check-circle me-2"></i>Simpan Perubahan
                                                    </button>
                                                </div>
                                            </form>
                                        </div>
                                    </div>
                                    
                                    <div class="col-lg-4">
                                        <div class="stats-card">
                                            <h5 class="fw-bold mb-4">
                                                <i class="bi bi-lightbulb me-2"></i>Tips Profil
                                            </h5>
                                            
                                            <div class="small">
                                                <div class="mb-3">
                                                    <strong>Foto Profil yang Baik:</strong>
                                                    <ul class="mt-2 mb-0">
                                                        <li>Gunakan foto wajah yang jelas</li>
                                                        <li>Background yang professional</li>
                                                        <li>Ekspresi yang ramah dan percaya diri</li>
                                                    </ul>
                                                </div>
                                                
                                                <div class="mb-3">
                                                    <strong>Bio yang Menarik:</strong>
                                                    <ul class="mt-2 mb-0">
                                                        <li>Sebutkan keahlian utama</li>
                                                        <li>Pengalaman mengajar</li>
                                                        <li>Prestasi atau sertifikasi</li>
                                                    </ul>
                                                </div>
                                                
                                                <div class="mb-0">
                                                    <strong>Informasi Kontak:</strong>
                                                    <ul class="mt-2 mb-0">
                                                        <li>Pastikan email aktif</li>
                                                        <li>Nomor telepon untuk urgent</li>
                                                        <li>Update informasi secara berkala</li>
                                                    </ul>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Tab 3: Keamanan -->
                            <div class="tab-pane fade" id="security" role="tabpanel">
                                <div class="row">
                                    <div class="col-lg-8">
                                        <div class="profile-container">
                                            <h4 class="fw-bold mb-4">
                                                <i class="bi bi-shield-lock me-2"></i>Pengaturan Keamanan
                                            </h4>
                                            
                                            <!-- Ubah Password -->
                                            <div class="form-container">
                                                <h6 class="fw-bold mb-3">Ubah Password</h6>
                                                
                                                <form method="POST" id="changePasswordForm">
                                                    <input type="hidden" name="action" value="change_password">
                                                    
                                                    <div class="mb-3">
                                                        <label for="current_password" class="form-label">Password Saat Ini</label>
                                                        <input type="password" class="form-control" id="current_password" name="current_password" required>
                                                    </div>
                                                    
                                                    <div class="mb-3">
                                                        <label for="new_password" class="form-label">Password Baru</label>
                                                        <input type="password" class="form-control" id="new_password" name="new_password" required>
                                                        <div class="form-text">Minimal 6 karakter</div>
                                                    </div>
                                                    
                                                    <div class="mb-3">
                                                        <label for="confirm_password" class="form-label">Konfirmasi Password Baru</label>
                                                        <input type="password" class="form-control" id="confirm_password" name="confirm_password" required>
                                                    </div>
                                                    
                                                    <div class="d-flex justify-content-between">
                                                        <button type="button" class="btn btn-outline-secondary" data-bs-toggle="tab" data-bs-target="#overview">
                                                            <i class="bi bi-arrow-left me-2"></i>Kembali
                                                        </button>
                                                        <button type="submit" class="btn btn-primary">
                                                            <i class="bi bi-key me-2"></i>Ubah Password
                                                        </button>
                                                    </div>
                                                </form>
                                            </div>
                                            
                                            <!-- Sesi Aktif -->
                                            <div class="form-container">
                                                <h6 class="fw-bold mb-3">Sesi Aktif</h6>
                                                
                                                <div class="alert alert-info">
                                                    <div class="d-flex justify-content-between align-items-center">
                                                        <div>
                                                            <i class="bi bi-laptop me-2"></i>
                                                            <strong>Sesi Saat Ini</strong>
                                                            <div class="small text-muted">
                                                                Browser: <?php echo $_SERVER['HTTP_USER_AGENT']; ?>
                                                            </div>
                                                        </div>
                                                        <span class="badge bg-success">Aktif</span>
                                                    </div>
                                                </div>
                                                
                                                <div class="alert alert-light">
                                                    <div class="d-flex justify-content-between align-items-center">
                                                        <div>
                                                            <i class="bi bi-phone me-2"></i>
                                                            <strong>Mobile Device</strong>
                                                            <div class="small text-muted">
                                                                Login: 2 hari yang lalu
                                                            </div>
                                                        </div>
                                                        <button class="btn btn-sm btn-outline-danger">
                                                            <i class="bi bi-box-arrow-right"></i> Logout
                                                        </button>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="col-lg-4">
                                        <div class="stats-card">
                                            <h5 class="fw-bold mb-4">
                                                <i class="bi bi-shield-check me-2"></i>Tips Keamanan
                                            </h5>
                                            
                                            <div class="small">
                                                <div class="mb-3">
                                                    <strong>Password yang Kuat:</strong>
                                                    <ul class="mt-2 mb-0">
                                                        <li>Gunakan kombinasi huruf dan angka</li>
                                                        <li>Minimal 8 karakter</li>
                                                        <li>Hindari informasi personal</li>
                                                    </ul>
                                                </div>
                                                
                                                <div class="mb-3">
                                                    <strong>Keamanan Akun:</strong>
                                                    <ul class="mt-2 mb-0">
                                                        <li>Jangan bagikan password</li>
                                                        <li>Logout dari perangkat bersama</li>
                                                        <li>Periksa sesi aktif secara berkala</li>
                                                    </ul>
                                                </div>
                                                
                                                <div class="mb-0">
                                                    <strong>Jika Curiga:</strong>
                                                    <ul class="mt-2 mb-0">
                                                        <li>Segera ubah password</li>
                                                        <li>Logout dari semua perangkat</li>
                                                        <li>Hubungi admin jika perlu</li>
                                                    </ul>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Notifikasi
            <?php if (isset($_SESSION['success'])): ?>
                setTimeout(() => {
                    const alert = document.createElement('div');
                    alert.className = 'alert alert-success alert-dismissible fade show position-fixed top-0 end-0 m-3';
                    alert.style.zIndex = '9999';
                    alert.innerHTML = `
                        <?php echo $_SESSION['success']; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    `;
                    document.body.appendChild(alert);
                }, 500);
            <?php unset($_SESSION['success']); endif; ?>

            <?php if (isset($_SESSION['error'])): ?>
                setTimeout(() => {
                    const alert = document.createElement('div');
                    alert.className = 'alert alert-danger alert-dismissible fade show position-fixed top-0 end-0 m-3';
                    alert.style.zIndex = '9999';
                    alert.innerHTML = `
                        <?php echo $_SESSION['error']; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    `;
                    document.body.appendChild(alert);
                }, 500);
            <?php unset($_SESSION['error']); endif; ?>

            // Preview image before upload
            const fileInput = document.querySelector('input[type="file"]');
            if (fileInput) {
                fileInput.addEventListener('change', function(e) {
                    const file = e.target.files[0];
                    if (file) {
                        const reader = new FileReader();
                        reader.onload = function(e) {
                            const img = document.createElement('img');
                            img.src = e.target.result;
                            img.className = 'rounded-circle';
                            img.width = 100;
                            img.height = 100;
                            
                            const previewContainer = fileInput.closest('.col-md-9').querySelector('.mb-3');
                            const existingImg = previewContainer.querySelector('img, .rounded-circle.bg-primary');
                            if (existingImg) {
                                existingImg.replaceWith(img);
                            }
                        }
                        reader.readAsDataURL(file);
                    }
                });
            }

            // Password validation
            const passwordForm = document.getElementById('changePasswordForm');
            if (passwordForm) {
                passwordForm.addEventListener('submit', function(e) {
                    const newPassword = document.getElementById('new_password').value;
                    const confirmPassword = document.getElementById('confirm_password').value;
                    
                    if (newPassword.length < 6) {
                        e.preventDefault();
                        alert('Password baru harus minimal 6 karakter');
                        return;
                    }
                    
                    if (newPassword !== confirmPassword) {
                        e.preventDefault();
                        alert('Konfirmasi password tidak sesuai');
                        return;
                    }
                });
            }

            // Character counter for bio
            const bioTextarea = document.getElementById('bio');
            if (bioTextarea) {
                const counter = document.createElement('div');
                counter.className = 'form-text text-end';
                counter.textContent = '0/500 karakter';
                
                bioTextarea.parentNode.appendChild(counter);
                
                bioTextarea.addEventListener('input', function() {
                    const length = this.value.length;
                    counter.textContent = `${length}/500 karakter`;
                    
                    if (length > 500) {
                        counter.classList.add('text-danger');
                    } else {
                        counter.classList.remove('text-danger');
                    }
                });
            }

            // Auto-save indicator
            const forms = document.querySelectorAll('form');
            forms.forEach(form => {
                let saveTimeout;
                
                form.addEventListener('input', function() {
                    clearTimeout(saveTimeout);
                    
                    const submitBtn = form.querySelector('button[type="submit"]');
                    const originalText = submitBtn.innerHTML;
                    
                    submitBtn.innerHTML = '<i class="bi bi-clock me-2"></i>Menyimpan...';
                    submitBtn.disabled = true;
                    
                    saveTimeout = setTimeout(() => {
                        submitBtn.innerHTML = originalText;
                        submitBtn.disabled = false;
                    }, 2000);
                });
            });
        });
    </script>
</body>
</html>
<?php
// Tutup koneksi database
if (isset($stmt_guru)) $stmt_guru->close();
if (isset($stmt_stats)) $stmt_stats->close();
$conn->close();
?>