<?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'];
$subject_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if (!$subject_id) {
    header('Location: subjects.php');
    exit();
}

$conn = getDBConnection();

// Create allowed_students table if not exists
$conn->query("CREATE TABLE IF NOT EXISTS allowed_students (
    id INT AUTO_INCREMENT PRIMARY KEY,
    subject_id INT NOT NULL,
    student_name VARCHAR(255) NOT NULL,
    id_number VARCHAR(50),
    added_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (subject_id) REFERENCES subjects(id) ON DELETE CASCADE,
    UNIQUE KEY unique_student_subject (subject_id, student_name)
)");

// Get user data including profile picture
$user_query = "SELECT profile_picture 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();

// Get subject details
$subject_query = "SELECT * FROM subjects WHERE id = ? AND instructor_id = ?";
$stmt = $conn->prepare($subject_query);
$stmt->bind_param("ii", $subject_id, $instructor_id);
$stmt->execute();
$subject_result = $stmt->get_result();
$subject = $subject_result->fetch_assoc();
$stmt->close();

if (!$subject) {
    header('Location: subjects.php');
    exit();
}

// Handle CSV upload
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['student_list'])) {
    $file = $_FILES['student_list'];

    if ($file['error'] == UPLOAD_ERR_OK) {
        $allowed_types = ['text/csv', 'application/csv', 'text/plain'];
        $file_ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));

        if ($file_ext == 'csv' || in_array($file['type'], $allowed_types)) {
            $handle = fopen($file['tmp_name'], 'r');
            $added_count = 0;
            $skipped_count = 0;
            $row_number = 0;

            // Delete existing allowed students for this subject if replace option is checked
            if (isset($_POST['replace_list'])) {
                $delete_stmt = $conn->prepare("DELETE FROM allowed_students WHERE subject_id = ?");
                $delete_stmt->bind_param("i", $subject_id);
                $delete_stmt->execute();
                $delete_stmt->close();
            }

            while (($data = fgetcsv($handle)) !== FALSE) {
                $row_number++;

                // Skip header row
                if ($row_number == 1 && (strtolower($data[0]) == 'name' || strtolower($data[0]) == 'student name')) {
                    continue;
                }

                // Expecting: Name, ID Number (optional)
                $name = trim($data[0]);
                $id_number = isset($data[1]) ? trim($data[1]) : null;

                if (!empty($name)) {
                    $insert_stmt = $conn->prepare("INSERT IGNORE INTO allowed_students (subject_id, student_name, id_number) VALUES (?, ?, ?)");
                    $insert_stmt->bind_param("iss", $subject_id, $name, $id_number);

                    if ($insert_stmt->execute() && $insert_stmt->affected_rows > 0) {
                        $added_count++;
                    } else {
                        $skipped_count++;
                    }
                    $insert_stmt->close();
                }
            }

            fclose($handle);
            $success_message = "Successfully added $added_count students. $skipped_count duplicates skipped.";
        } else {
            $error_message = "Please upload a valid CSV file.";
        }
    } else {
        $error_message = "File upload error. Please try again.";
    }
}

// Handle manual add
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['add_student'])) {
    $name = trim($_POST['student_name']);
    $id_number = trim($_POST['student_id_number']);

    if (!empty($name)) {
        $insert_stmt = $conn->prepare("INSERT IGNORE INTO allowed_students (subject_id, student_name, id_number) VALUES (?, ?, ?)");
        $insert_stmt->bind_param("iss", $subject_id, $name, $id_number);

        if ($insert_stmt->execute() && $insert_stmt->affected_rows > 0) {
            $success_message = "Student added successfully!";
        } else {
            $error_message = "Student already exists in the list.";
        }
        $insert_stmt->close();
    }
}

// Handle delete
if (isset($_GET['delete'])) {
    $delete_id = intval($_GET['delete']);
    $delete_stmt = $conn->prepare("DELETE FROM allowed_students WHERE id = ? AND subject_id = ?");
    $delete_stmt->bind_param("ii", $delete_id, $subject_id);
    $delete_stmt->execute();
    $delete_stmt->close();
    header("Location: manage_allowed_students.php?id=$subject_id&success=deleted");
    exit();
}

// Get allowed students list
$allowed_query = "SELECT * FROM allowed_students WHERE subject_id = ? ORDER BY student_name";
$stmt = $conn->prepare($allowed_query);
$stmt->bind_param("i", $subject_id);
$stmt->execute();
$allowed_result = $stmt->get_result();
$allowed_students = [];
while ($row = $allowed_result->fetch_assoc()) {
    $allowed_students[] = $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", $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>Manage Allowed Students - 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/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 active">My Subjects</a>
                <a href="students.php" class="nav-link">My Students</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">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">
            <div>
                <a href="subject_details.php?id=<?php echo $subject_id; ?>" style="color: #667eea; text-decoration: none; display: inline-block; margin-bottom: 10px;">← Back to Subject</a>
                <h1>👥 Manage Allowed Students</h1>
                <p><?php echo htmlspecialchars($subject['subject_name']); ?> (<?php echo htmlspecialchars($subject['subject_code']); ?>)</p>
            </div>
        </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; ?>

        <?php if (isset($_GET['success']) && $_GET['success'] == 'deleted'): ?>
            <div class="alert alert-success">Student removed from allowed list.</div>
        <?php endif; ?>

        <!-- Upload CSV Section -->
        <div class="dashboard-section">
            <h2>📤 Upload Student List (CSV)</h2>
            <p style="color: #666; margin-bottom: 15px;">Upload a CSV file with student names. Format: Name, ID Number (optional)</p>

            <div class="csv-example">
                <strong>CSV Example:</strong>
                <pre>Student Name,ID Number
John Doe,22-11111
Jane Smith,22-11112
Mark Johnson,22-11113</pre>
                <a href="#" onclick="downloadTemplate(); return false;" class="btn btn-secondary" style="margin-top: 10px;">📥 Download Template</a>
            </div>

            <form method="POST" enctype="multipart/form-data" style="margin-top: 20px;">
                <div class="form-group">
                    <label>Select CSV File *</label>
                    <input type="file" name="student_list" accept=".csv" required>
                </div>
                <div class="form-group">
                    <label style="display: flex; align-items: center; gap: 10px;">
                        <input type="checkbox" name="replace_list" value="1">
                        <span>Replace existing list (delete all current allowed students)</span>
                    </label>
                </div>
                <button type="submit" class="btn btn-success">Upload List</button>
            </form>
        </div>

        <!-- Manual Add Section -->
        <div class="dashboard-section">
            <h2>➕ Add Student Manually</h2>
            <form method="POST">
                <div style="display: grid; grid-template-columns: 1fr 1fr auto; gap: 10px; align-items: end;">
                    <div class="form-group">
                        <label>Student Name *</label>
                        <input type="text" name="student_name" required placeholder="Full name as registered">
                    </div>
                    <div class="form-group">
                        <label>ID Number (Optional)</label>
                        <input type="text" name="student_id_number" placeholder="e.g., 22-11355">
                    </div>
                    <button type="submit" name="add_student" class="btn btn-primary">Add Student</button>
                </div>
            </form>
        </div>

        <!-- Allowed Students List -->
        <div class="dashboard-section">
            <h2>📋 Allowed Students (<?php echo count($allowed_students); ?>)</h2>

            <?php if (empty($allowed_students)): ?>
                <div class="empty-state">
                    <p>No students in the allowed list yet. Upload a CSV or add students manually.</p>
                    <p style="color: #666; font-size: 0.9em; margin-top: 10px;">
                        ⚠️ Note: If the allowed list is empty, ANY student can enroll in this subject.
                    </p>
                </div>
            <?php else: ?>
                <div class="table-container">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>Student Name</th>
                                <th>ID Number</th>
                                <th>Added On</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($allowed_students as $student): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($student['student_name']); ?></td>
                                    <td><?php echo $student['id_number'] ? htmlspecialchars($student['id_number']) : '-'; ?></td>
                                    <td><?php echo date('M d, Y', strtotime($student['added_at'])); ?></td>
                                    <td>
                                        <a href="?id=<?php echo $subject_id; ?>&delete=<?php echo $student['id']; ?>"
                                           class="btn btn-small btn-danger"
                                           onclick="return confirm('Remove this student from allowed list?')">
                                            Remove
                                        </a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>

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

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

        // Close notifications panel when clicking outside
        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');
            }
        });

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

        function downloadTemplate() {
            const csv = 'Student Name,ID Number\nJohn Doe,22-11111\nJane Smith,22-11112';
            const blob = new Blob([csv], { type: 'text/csv' });
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'student_list_template.csv';
            a.click();
            window.URL.revokeObjectURL(url);
        }
    </script>

    <style>
        .csv-example {
            background: rgba(102, 126, 234, 0.05);
            border: 1px solid rgba(102, 126, 234, 0.2);
            border-radius: 8px;
            padding: 15px;
            margin-top: 10px;
        }

        .csv-example pre {
            background: rgba(0, 0, 0, 0.05);
            padding: 10px;
            border-radius: 4px;
            margin: 10px 0;
            font-size: 0.9em;
        }

        .empty-state {
            text-align: center;
            padding: 40px 20px;
            color: #666;
        }

        @media (prefers-color-scheme: dark) {
            .csv-example {
                background: rgba(102, 126, 234, 0.1);
                border-color: rgba(102, 126, 234, 0.3);
            }

            .csv-example pre {
                background: rgba(255, 255, 255, 0.05);
            }
        }
    </style>
</body>
</html>
