<?php
session_start();
require_once '../config/database.php';

if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] != 'instructor') {
    header('Location: ../index.php');
    exit();
}

$instructor_id = $_SESSION['user_id'];
$conn = getDBConnection();

// Get user details
$user_query = "SELECT * FROM users WHERE id = ?";
$stmt = $conn->prepare($user_query);
$stmt->bind_param("i", $instructor_id);
$stmt->execute();
$user_result = $stmt->get_result();
$user = $user_result->fetch_assoc();
$stmt->close();

// Handle password update
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_password'])) {
    $current_password = $_POST['current_password'];
    $new_password = $_POST['new_password'];
    $confirm_password = $_POST['confirm_password'];

    if (password_verify($current_password, $user['password'])) {
        if ($new_password === $confirm_password) {
            $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
            $update_query = "UPDATE users SET password = ? WHERE id = ?";
            $stmt = $conn->prepare($update_query);
            $stmt->bind_param("si", $hashed_password, $instructor_id);
            $stmt->execute();
            $stmt->close();
            $success_message = "Password updated successfully!";
        } else {
            $error_message = "New passwords do not match!";
        }
    } else {
        $error_message = "Current password is incorrect!";
    }
}

// Handle profile picture upload
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['upload_picture'])) {
    if (isset($_FILES['profile_picture']) && $_FILES['profile_picture']['error'] == 0) {
        $allowed = ['jpg', 'jpeg', 'png', 'gif'];
        $filename = $_FILES['profile_picture']['name'];
        $filetype = $_FILES['profile_picture']['type'];
        $filesize = $_FILES['profile_picture']['size'];

        $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));

        if (!in_array($ext, $allowed)) {
            $error_message = "Only JPG, JPEG, PNG & GIF files are allowed!";
        } elseif ($filesize > 5 * 1024 * 1024) { // 5MB limit
            $error_message = "File size must be less than 5MB!";
        } else {
            // Delete old profile picture if exists
            if (isset($user['profile_picture']) && $user['profile_picture'] && file_exists('../' . $user['profile_picture'])) {
                unlink('../' . $user['profile_picture']);
            }

            // Generate unique filename
            $new_filename = 'profile_' . $instructor_id . '_' . time() . '.' . $ext;
            $upload_path = '../uploads/profile_pictures/' . $new_filename;

            if (move_uploaded_file($_FILES['profile_picture']['tmp_name'], $upload_path)) {
                $db_path = 'uploads/profile_pictures/' . $new_filename;
                $update_query = "UPDATE users SET profile_picture = ? WHERE id = ?";
                $stmt = $conn->prepare($update_query);
                $stmt->bind_param("si", $db_path, $instructor_id);
                $stmt->execute();
                $stmt->close();
                $user['profile_picture'] = $db_path;
                $success_message = "Profile picture updated successfully!";
            } else {
                $error_message = "Failed to upload profile picture!";
            }
        }
    } else {
        $error_message = "Please select an image file!";
    }
}

// Handle profile update
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_profile'])) {
    $full_name = trim($_POST['full_name']);
    $email = trim($_POST['email']);

    $update_query = "UPDATE users SET full_name = ?, email = ? WHERE id = ?";
    $stmt = $conn->prepare($update_query);
    $stmt->bind_param("ssi", $full_name, $email, $instructor_id);

    if ($stmt->execute()) {
        $_SESSION['full_name'] = $full_name;
        $_SESSION['email'] = $email;
        $user['full_name'] = $full_name;
        $user['email'] = $email;
        $success_message = "Profile updated successfully!";
    } else {
        $error_message = "Failed to update profile!";
    }
    $stmt->close();
}

// Get statistics
$subjects_count_query = "SELECT COUNT(*) as count FROM subjects WHERE instructor_id = ?";
$stmt = $conn->prepare($subjects_count_query);
$stmt->bind_param("i", $instructor_id);
$stmt->execute();
$subjects_count = $stmt->get_result()->fetch_assoc()['count'];
$stmt->close();

$activities_count_query = "SELECT COUNT(*) as count FROM activities WHERE created_by = ?";
$stmt = $conn->prepare($activities_count_query);
$stmt->bind_param("i", $instructor_id);
$stmt->execute();
$activities_count = $stmt->get_result()->fetch_assoc()['count'];
$stmt->close();

$students_count_query = "SELECT COUNT(DISTINCT e.student_id) as count FROM enrollments e JOIN subjects s ON e.subject_id = s.id WHERE s.instructor_id = ?";
$stmt = $conn->prepare($students_count_query);
$stmt->bind_param("i", $instructor_id);
$stmt->execute();
$students_count = $stmt->get_result()->fetch_assoc()['count'];
$stmt->close();

// Get unread notifications count
$notif_count_query = "SELECT COUNT(*) as count FROM notifications WHERE user_id = ? AND is_read = FALSE";
$stmt = $conn->prepare($notif_count_query);
$stmt->bind_param("i", $instructor_id);
$stmt->execute();
$notif_result = $stmt->get_result();
$notif_count = $notif_result->fetch_assoc()['count'];
$stmt->close();

$conn->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Profile - CODELAB</title>
    <link rel="stylesheet" href="../assets/css/style.css">
    <script src="../assets/js/dark-mode.js" defer>
        // HTML escape function to prevent XSS
        function escapeHtml(text) {
            if (!text) return '';
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
</script>
    <script src="../assets/js/burger-menu.js" defer></script>
    <script src="../assets/js/push-notifications.js" defer></script>
    <script src="../assets/js/interactive-pet.js" defer></script>
</head>
<body>
    <nav class="navbar">
        <div class="nav-container">
            <div class="nav-brand">
                <?php if (isset($user['profile_picture']) && $user['profile_picture']): ?>
                    <img src="../<?php echo htmlspecialchars($user['profile_picture']); ?>" alt="Profile" class="nav-profile-pic">
                <?php else: ?>
                    <div class="nav-avatar"><?php echo strtoupper(substr($_SESSION['full_name'], 0, 1)); ?></div>
                <?php endif; ?>
                <h2>CODELAB</h2>
            </div>
            <button class="burger-menu" onclick="toggleMenu()">
                <span></span>
                <span></span>
                <span></span>
            </button>
            <div class="nav-menu" id="nav-menu">
                <a href="dashboard.php" class="nav-link">Dashboard</a>
                <a href="subjects.php" class="nav-link">My Subjects</a>
                <a href="activities.php" class="nav-link">Activities</a>
                <a href="submissions.php" class="nav-link">Submissions</a>
                <a href="profile.php" class="nav-link active">Profile</a>
                <a href="#" class="nav-link notification-bell" onclick="toggleNotifications()">
                    🔔 Notifications
                    <?php if ($notif_count > 0): ?>
                        <span class="badge"><?php echo $notif_count; ?></span>
                    <?php endif; ?>
                </a>
                <a href="../auth/logout.php" class="nav-link logout">Logout</a>
            </div>
        </div>
    </nav>

    <div class="main-content">
        <div class="dashboard-header">
            <h1>👤 My Profile</h1>
            <p>Manage your account information</p>
        </div>

        <?php if (isset($success_message)): ?>
            <div class="alert alert-success"><?php echo $success_message; ?></div>
        <?php endif; ?>

        <?php if (isset($error_message)): ?>
            <div class="alert alert-error"><?php echo $error_message; ?></div>
        <?php endif; ?>

        <!-- Stats Cards -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-icon">📚</div>
                <div class="stat-info">
                    <h3>My Subjects</h3>
                    <p class="stat-value"><?php echo $subjects_count; ?></p>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon">📝</div>
                <div class="stat-info">
                    <h3>Activities Created</h3>
                    <p class="stat-value"><?php echo $activities_count; ?></p>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon">👥</div>
                <div class="stat-info">
                    <h3>Total Students</h3>
                    <p class="stat-value"><?php echo $students_count; ?></p>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon">📅</div>
                <div class="stat-info">
                    <h3>Member Since</h3>
                    <p class="stat-value" style="font-size: 1.2em;"><?php echo date('Y', strtotime($user['created_at'])); ?></p>
                </div>
            </div>
        </div>

        <div class="dashboard-grid">
            <!-- Profile Picture -->
            <div class="dashboard-section">
                <div class="section-header">
                    <h2>📸 Profile Picture</h2>
                </div>
                <div style="text-align: center;">
                    <?php if (isset($user['profile_picture']) && $user['profile_picture']): ?>
                        <img src="../<?php echo htmlspecialchars($user['profile_picture']); ?>" alt="Profile Picture" style="width: 150px; height: 150px; border-radius: 50%; object-fit: cover; margin-bottom: 20px; border: 4px solid #667eea;">
                    <?php else: ?>
                        <div style="width: 150px; height: 150px; border-radius: 50%; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); margin: 0 auto 20px; display: flex; align-items: center; justify-content: center; font-size: 60px; color: white;">
                            <?php echo strtoupper(substr($user['full_name'], 0, 1)); ?>
                        </div>
                    <?php endif; ?>
                    <form method="POST" enctype="multipart/form-data">
                        <div class="form-group">
                            <input type="file" name="profile_picture" accept="image/*" required style="margin-bottom: 10px;">
                            <small style="color: #666; display: block; margin-bottom: 10px;">Max size: 5MB. Allowed: JPG, PNG, GIF</small>
                        </div>
                        <button type="submit" name="upload_picture" class="btn btn-primary">Upload Picture</button>
                    </form>
                </div>
            </div>

            <!-- Profile Information -->
            <div class="dashboard-section">
                <div class="section-header">
                    <h2>📝 Profile Information</h2>
                </div>
                <form method="POST">
                    <div class="form-group">
                        <label>ID Number</label>
                        <input type="text" value="<?php echo htmlspecialchars($user['id_number'] ?? 'N/A'); ?>" disabled style="background: #f0f0f0;">
                        <small style="color: #666;">ID number cannot be changed</small>
                    </div>
                    <div class="form-group">
                        <label>Username</label>
                        <input type="text" value="<?php echo htmlspecialchars($user['username']); ?>" disabled style="background: #f0f0f0;">
                        <small style="color: #666;">Username cannot be changed</small>
                    </div>
                    <div class="form-group">
                        <label>Full Name</label>
                        <input type="text" name="full_name" value="<?php echo htmlspecialchars($user['full_name']); ?>" required>
                    </div>
                    <div class="form-group">
                        <label>Email</label>
                        <input type="email" name="email" value="<?php echo htmlspecialchars($user['email']); ?>" required>
                    </div>
                    <div class="form-group">
                        <label>User Type</label>
                        <input type="text" value="<?php echo ucfirst($user['user_type']); ?>" disabled style="background: #f0f0f0;">
                    </div>
                    <div class="form-group">
                        <label>Member Since</label>
                        <input type="text" value="<?php echo date('M d, Y', strtotime($user['created_at'])); ?>" disabled style="background: #f0f0f0;">
                    </div>
                    <button type="submit" name="update_profile" class="btn btn-primary">Update Profile</button>
                </form>
            </div>

            <!-- Change Password -->
            <div class="dashboard-section">
                <div class="section-header">
                    <h2>🔒 Change Password</h2>
                </div>
                <form method="POST" id="password-form">
                    <div class="form-group">
                        <label>Current Password</label>
                        <input type="password" name="current_password" required>
                    </div>
                    <div class="form-group">
                        <label>New Password</label>
                        <input type="password" name="new_password" id="new_password" minlength="6" required>
                    </div>
                    <div class="form-group">
                        <label>Confirm New Password</label>
                        <input type="password" name="confirm_password" id="confirm_password" minlength="6" required>
                    </div>
                    <button type="submit" name="update_password" class="btn btn-primary">Change Password</button>
                </form>
            </div>

            <!-- Tutorial Settings -->
            <div class="dashboard-section">
                <div class="section-header">
                    <h2>🎓 Tutorial</h2>
                </div>
                <p style="margin-bottom: 15px; color: #666;">
                    Need a refresher? Restart the interactive tutorial to learn about CODELAB features again.
                </p>
                <button onclick="restartTutorial()" class="btn btn-secondary">
                    🔄 Restart Tutorial
                </button>
            </div>
        </div>
    </div>

    <script>
        document.getElementById('password-form').addEventListener('submit', function(e) {
            const newPassword = document.getElementById('new_password').value;
            const confirmPassword = document.getElementById('confirm_password').value;

            if (newPassword !== confirmPassword) {
                e.preventDefault();
                alert('New passwords do not match!');
            }
        });

        function toggleNotifications() {
            const panel = document.getElementById('notifications-panel');
            const isOpen = panel.classList.contains('open');

            if (isOpen) {
                panel.classList.remove('open');
            } else {
                panel.classList.add('open');
                loadNotifications();
            }
        }

        function loadNotifications() {
            const content = document.getElementById('notifications-content');

            fetch('get_notifications.php')
                .then(response => response.json())
                .then(data => {
                    if (data.length === 0) {
                        content.innerHTML = '<p class="empty-message">No notifications yet.</p>';
                    } else {
                        let html = '';
                        data.forEach(notif => {
                            html += `
                                <div class="notification-item ${notif.is_read ? '' : 'unread'}">
                                    <p>${escapeHtml(notif.message)}</p>
                                    <span class="notif-time">${escapeHtml(notif.created_at)}</span>
                                </div>
                            `;
                        });
                        content.innerHTML = html;

                        fetch('mark_notifications_read.php');
                    }
                })
                .catch(error => {
                    content.innerHTML = '<p class="error-message">Failed to load notifications.</p>';
                });
        }

        document.addEventListener('click', function(event) {
            const panel = document.getElementById('notifications-panel');
            const target = event.target;

            if (!panel.contains(target) && !target.closest('.nav-link')) {
                panel.classList.remove('open');
            }
        });

        // Restart tutorial function
        function restartTutorial() {
            if (confirm('This will restart the interactive tutorial. You will be redirected to the dashboard. Continue?')) {
                localStorage.removeItem('tutorial_completed_instructor');
                window.location.href = 'dashboard.php';
            }
        }
    </script>

    <!-- Notifications Panel -->
    <div id="notifications-panel" class="notifications-panel">
        <div class="notifications-header">
            <h3>📬 Notifications</h3>
            <button onclick="toggleNotifications()" class="close-btn">×</button>
        </div>
        <div class="notifications-content" id="notifications-content">
            <p class="loading">Loading notifications...</p>
        </div>
    </div>
</body>
</html>
