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

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

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

// Get user data including profile picture
$user_query = "SELECT profile_picture FROM users WHERE id = ?";
$stmt = $conn->prepare($user_query);
$stmt->bind_param("i", $admin_id);
$stmt->execute();
$user_result = $stmt->get_result();
$user = $user_result->fetch_assoc();
$stmt->close();

// Handle delete subject
if (isset($_GET['delete'])) {
    $subject_id = intval($_GET['delete']);
    $delete_query = "DELETE FROM subjects WHERE id = ?";
    $stmt = $conn->prepare($delete_query);
    $stmt->bind_param("i", $subject_id);
    $stmt->execute();
    $stmt->close();
    header('Location: subjects.php?success=deleted');
    exit();
}

// Get all subjects with instructor info
$subjects_query = "SELECT s.*, u.full_name as instructor_name,
                   (SELECT COUNT(*) FROM enrollments e WHERE e.subject_id = s.id) as student_count,
                   (SELECT COUNT(*) FROM activities a WHERE a.subject_id = s.id) as activity_count
                   FROM subjects s
                   LEFT JOIN users u ON s.instructor_id = u.id
                   ORDER BY s.created_at DESC";
$subjects_result = $conn->query($subjects_query);
$subjects = [];
while ($row = $subjects_result->fetch_assoc()) {
    $subjects[] = $row;
}

$conn->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Subjects - CODELAB</title>
    <link rel="stylesheet" href="../assets/css/style.css">
    <script src="../assets/js/dark-mode.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">👨‍💼</div>
                <?php endif; ?>
                <h2>CODELAB ADMIN</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="users.php" class="nav-link">Manage Users</a>
                <a href="subjects.php" class="nav-link active">Manage Subjects</a>
                <a href="activities.php" class="nav-link">Manage Activities</a>
                <a href="profile.php" class="nav-link">Profile</a>
                <a href="../auth/logout.php" class="nav-link logout">Logout</a>
            </div>
        </div>
    </nav>

    <div class="main-content">
        <div class="dashboard-header">
            <h1>📚 Manage Subjects</h1>
        </div>

        <?php if (isset($_GET['success'])): ?>
            <div class="alert alert-success">
                <?php if ($_GET['success'] == 'deleted') echo 'Subject deleted successfully!'; ?>
            </div>
        <?php endif; ?>

        <!-- Subjects Grid -->
        <div class="dashboard-section full-width">
            <?php if (!empty($subjects)): ?>
                <div class="subjects-grid">
                    <?php foreach ($subjects as $subject): ?>
                        <div class="subject-card" style="cursor: pointer;" onclick="window.location.href='subject_details.php?id=<?php echo $subject['id']; ?>'">
                            <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">
                                <div>
                                    <span class="instructor">
                                        👨‍🏫 <?php echo htmlspecialchars($subject['instructor_name'] ?? 'No Instructor'); ?>
                                    </span>
                                    <br>
                                    <small style="color: rgba(255,255,255,0.8);">
                                        👥 <?php echo $subject['student_count']; ?> Students |
                                        📝 <?php echo $subject['activity_count']; ?> Activities
                                    </small>
                                </div>
                                <a href="?delete=<?php echo $subject['id']; ?>"
                                   class="btn btn-small btn-danger"
                                   onclick="event.stopPropagation(); return confirm('Are you sure you want to delete this subject? This will also delete all related activities and enrollments.')">
                                    Delete
                                </a>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <p class="empty-message">📚 No subjects found.</p>
            <?php endif; ?>
        </div>
    </div>

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