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

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

$student_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", $student_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'])) {
    requireCSRFToken();
    $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, $student_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'])) {
    requireCSRFToken();
    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'];
        $tmp_name = $_FILES['profile_picture']['tmp_name'];

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

        // Validate file extension
        if (!in_array($ext, $allowed)) {
            $error_message = "Only JPG, JPEG, PNG & GIF files are allowed!";
        }
        // Validate file size
        elseif ($filesize > 5 * 1024 * 1024) { // 5MB limit
            $error_message = "File size must be less than 5MB!";
        }
        // Validate actual file type using getimagesize()
        elseif (!getimagesize($tmp_name)) {
            $error_message = "Invalid image file! File content does not match image format.";
        }
        // Validate MIME type
        elseif (!in_array($filetype, ['image/jpeg', 'image/png', 'image/gif'])) {
            $error_message = "Invalid file type! Only JPEG, PNG & GIF images are allowed.";
        }
        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_' . $student_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, $student_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'])) {
    requireCSRFToken();
    $id_number = trim($_POST['id_number']);
    $full_name = trim($_POST['full_name']);
    $email = trim($_POST['email']);
    $year_level = trim($_POST['year_level']);
    $section = trim($_POST['section']);

    $update_query = "UPDATE users SET id_number = ?, full_name = ?, email = ?, year_level = ?, section = ? WHERE id = ?";
    $stmt = $conn->prepare($update_query);
    $stmt->bind_param("sssssi", $id_number, $full_name, $email, $year_level, $section, $student_id);

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

// Check if violation tracking columns exist
$check_columns = $conn->query("SHOW COLUMNS FROM submissions LIKE 'violation_count'");
$has_violation_tracking = $check_columns->num_rows > 0;

// Get violation statistics
$total_violations = 0;
$activities_with_violations = 0;
$auto_submitted_count = 0;

if ($has_violation_tracking) {
    $violation_query = "SELECT
                        COUNT(*) as activities_with_violations,
                        SUM(violation_count) as total_violations,
                        SUM(CASE WHEN is_auto_submitted = 1 THEN 1 ELSE 0 END) as auto_submitted_count
                        FROM submissions
                        WHERE student_id = ? AND violation_count > 0";
    $v_stmt = $conn->prepare($violation_query);
    $v_stmt->bind_param("i", $student_id);
    $v_stmt->execute();
    $v_result = $v_stmt->get_result();
    $v_data = $v_result->fetch_assoc();
    $v_stmt->close();

    $total_violations = $v_data['total_violations'] ?? 0;
    $activities_with_violations = $v_data['activities_with_violations'] ?? 0;
    $auto_submitted_count = $v_data['auto_submitted_count'] ?? 0;
}

// Get enrolled subjects
$subjects_query = "SELECT s.*, u.full_name as instructor_name
                   FROM subjects s
                   JOIN enrollments e ON s.id = e.subject_id
                   LEFT JOIN users u ON s.instructor_id = u.id
                   WHERE e.student_id = ?";
$stmt = $conn->prepare($subjects_query);
$stmt->bind_param("i", $student_id);
$stmt->execute();
$subjects_result = $stmt->get_result();
$enrolled_subjects = [];
while ($row = $subjects_result->fetch_assoc()) {
    $enrolled_subjects[] = $row;
}
$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", $student_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></script>
    <script src="../assets/js/interactive-pet.js" defer></script>
    <script src="../assets/js/push-notifications.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="grades.php" class="nav-link">Grades</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>

    <!-- 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>

    <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; ?>

        <!-- Code Points Section -->
        <div class="dashboard-section" style="max-width: 800px; margin: 0 auto 30px;">
            <div class="code-points-showcase" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 40px; border-radius: 16px; text-align: center; color: white; position: relative; overflow: hidden;">
                <div style="position: relative; z-index: 2;">
                    <h2 style="margin: 0 0 10px 0; font-size: 1.2em; opacity: 0.95;">🏆 Your Code Points</h2>
                    <div style="font-size: 5em; font-weight: bold; margin: 20px 0; text-shadow: 0 4px 8px rgba(0,0,0,0.2);">
                        <?php echo isset($user['code_points']) ? $user['code_points'] : 0; ?>
                    </div>
                    <p style="margin: 0; font-size: 1.1em; opacity: 0.9;">
                        Earned from completing Code Challenges
                    </p>
                    <a href="code_challenges.php" class="btn" style="margin-top: 25px; background: rgba(255,255,255,0.2); color: white; border: 2px solid white; padding: 12px 30px; font-size: 1.1em; transition: all 0.3s;">
                        🎮 Play Code Challenges
                    </a>
                </div>
                <div style="position: absolute; top: -50px; right: -50px; width: 200px; height: 200px; background: rgba(255,255,255,0.1); border-radius: 50%; z-index: 1;"></div>
                <div style="position: absolute; bottom: -30px; left: -30px; width: 150px; height: 150px; background: rgba(255,255,255,0.1); border-radius: 50%; z-index: 1;"></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">
                        <?php echo csrfField(); ?>
                        <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">
                    <?php echo csrfField(); ?>
                    <div class="form-group">
                        <label>ID Number</label>
                        <input type="text" name="id_number" value="<?php echo htmlspecialchars($user['id_number'] ?? ''); ?>" required>
                    </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>Year Level</label>
                        <select name="year_level" required>
                            <option value="">Select Year Level</option>
                            <option value="1st Year" <?php echo ($user['year_level'] ?? '') == '1st Year' ? 'selected' : ''; ?>>1st Year</option>
                            <option value="2nd Year" <?php echo ($user['year_level'] ?? '') == '2nd Year' ? 'selected' : ''; ?>>2nd Year</option>
                            <option value="3rd Year" <?php echo ($user['year_level'] ?? '') == '3rd Year' ? 'selected' : ''; ?>>3rd Year</option>
                            <option value="4th Year" <?php echo ($user['year_level'] ?? '') == '4th Year' ? 'selected' : ''; ?>>4th Year</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Section</label>
                        <input type="text" name="section" value="<?php echo htmlspecialchars($user['section'] ?? ''); ?>" placeholder="e.g., A, B, C, IT-301" 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>

            <!-- Violation Statistics -->
            <div class="dashboard-section">
                <div class="section-header">
                    <h2>⚠️ Anti-Cheat Record</h2>
                </div>
                <?php if ($total_violations > 0): ?>
                    <div style="background: rgba(220, 53, 69, 0.1); padding: 20px; border-radius: 10px; border-left: 4px solid #dc3545;">
                        <div style="margin-bottom: 15px;">
                            <strong style="color: #dc3545; font-size: 1.1em; display: block; margin-bottom: 10px;">
                                🚨 Violation Summary
                            </strong>
                        </div>
                        <div style="display: grid; gap: 12px;">
                            <div style="display: flex; justify-content: space-between; align-items: center; padding: 10px; background: rgba(255,255,255,0.5); border-radius: 6px;">
                                <span style="color: #333;">Total Violations:</span>
                                <strong style="color: #dc3545; font-size: 1.3em;"><?php echo $total_violations; ?></strong>
                            </div>
                            <div style="display: flex; justify-content: space-between; align-items: center; padding: 10px; background: rgba(255,255,255,0.5); border-radius: 6px;">
                                <span style="color: #333;">Activities with Violations:</span>
                                <strong style="color: #dc3545; font-size: 1.3em;"><?php echo $activities_with_violations; ?></strong>
                            </div>
                            <div style="display: flex; justify-content: space-between; align-items: center; padding: 10px; background: rgba(255,255,255,0.5); border-radius: 6px;">
                                <span style="color: #333;">Auto-Submitted Activities:</span>
                                <strong style="color: #dc3545; font-size: 1.3em;"><?php echo $auto_submitted_count; ?></strong>
                            </div>
                        </div>
                        <div style="margin-top: 15px; padding-top: 15px; border-top: 1px solid rgba(220, 53, 69, 0.3);">
                            <small style="color: #666; display: block; line-height: 1.6;">
                                ⚠️ Violations are recorded when you:
                                <ul style="margin: 8px 0; padding-left: 20px;">
                                    <li>Switch tabs or windows</li>
                                    <li>Minimize the browser</li>
                                    <li>Try to open developer tools</li>
                                </ul>
                                Multiple violations may result in auto-submission.
                            </small>
                        </div>
                    </div>
                <?php else: ?>
                    <div style="background: rgba(40, 167, 69, 0.1); padding: 20px; border-radius: 10px; border-left: 4px solid #28a745; text-align: center;">
                        <div style="font-size: 3em; margin-bottom: 10px;">✓</div>
                        <strong style="color: #28a745; font-size: 1.2em; display: block; margin-bottom: 8px;">
                            Clean Record!
                        </strong>
                        <p style="color: #666; margin: 0;">
                            You have no anti-cheat violations. Keep up the honest work!
                        </p>
                    </div>
                <?php endif; ?>
            </div>

            <!-- Change Password -->
            <div class="dashboard-section">
                <div class="section-header">
                    <h2>🔒 Change Password</h2>
                </div>
                <form method="POST" id="password-form">
                    <?php echo csrfField(); ?>
                    <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>

        <!-- Enrolled Subjects -->
        <div class="dashboard-section full-width">
            <div class="section-header">
                <h2>📚 Enrolled Subjects</h2>
                <a href="enroll.php" class="btn btn-small btn-primary">Enroll in More Subjects</a>
            </div>
            <?php if (!empty($enrolled_subjects)): ?>
                <div class="subjects-grid">
                    <?php foreach ($enrolled_subjects as $subject): ?>
                        <div class="subject-card">
                            <div class="subject-header">
                                <h3><?php echo htmlspecialchars($subject['subject_name']); ?></h3>
                                <span class="subject-code"><?php echo htmlspecialchars($subject['subject_code']); ?></span>
                            </div>
                            <p class="subject-description"><?php echo htmlspecialchars($subject['description']); ?></p>
                            <div class="subject-footer">
                                <span class="instructor">
                                    👤 <?php echo htmlspecialchars($subject['instructor_name']); ?>
                                </span>
                                <a href="activities.php?subject=<?php echo $subject['id']; ?>" class="btn btn-small">
                                    View Activities
                                </a>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <p class="empty-message">
                    📚 You haven't enrolled in any subjects yet. <a href="enroll.php">Enroll now</a>
                </p>
            <?php endif; ?>
        </div>
    </div>

    <script>
        function toggleMenu() {
            const navMenu = document.getElementById('nav-menu');
            navMenu.classList.toggle('active');
        }

        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>${notif.message}</p>
                                    <span class="notif-time">${notif.created_at}</span>
                                    ${notif.activity_id ? `<a href="take_activity.php?id=${notif.activity_id}" class="notif-link">View Activity →</a>` : ''}
                                </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');
            }
        });

        // Password validation
        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!');
            }
        });

        // 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_student');
                window.location.href = 'dashboard.php';
            }
        }
    </script>
</body>
</html>
