<?php
session_start();
include '../../includes/db_connection.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: /school_management/public/index.php");
    exit();
}

$message = '';
$error = '';

$class_id = $_GET['class_id'] ?? '';

// Handle form submission to add or remove subjects
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $class_id = $_POST['class_id'];
    
    if (isset($_POST['add_subject'])) {
        $subject_id = $_POST['subject_id'];
        $sql = "INSERT INTO class_subjects (class_id, subject_id) VALUES (?, ?)";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("ii", $class_id, $subject_id);
        if ($stmt->execute()) {
            $message = "Subject added to class successfully!";
        } else {
            $error = "Error: " . $stmt->error;
        }
        $stmt->close();

    } elseif (isset($_POST['remove_subject'])) {
        $subject_id = $_POST['subject_id'];
        $sql = "DELETE FROM class_subjects WHERE class_id = ? AND subject_id = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("ii", $class_id, $subject_id);
        if ($stmt->execute()) {
            $message = "Subject removed from class successfully!";
        } else {
            $error = "Error: " . $stmt->error;
        }
        $stmt->close();
    }
}

// Fetch all classes
$classes_sql = "SELECT class_id, class_name FROM classes ORDER BY class_name";
$classes_result = $conn->query($classes_sql);

$class_name = '';
$assigned_subjects = [];
$available_subjects = [];

if ($class_id) {
    // Fetch class name
    $class_name_sql = "SELECT class_name FROM classes WHERE class_id = ?";
    $stmt_class_name = $conn->prepare($class_name_sql);
    $stmt_class_name->bind_param("i", $class_id);
    $stmt_class_name->execute();
    $result_class_name = $stmt_class_name->get_result();
    $class_data = $result_class_name->fetch_assoc();
    $class_name = $class_data['class_name'] ?? 'N/A';

    // Fetch assigned subjects for the selected class
    $assigned_subjects_sql = "SELECT s.subject_id, s.subject_name FROM subjects s
                              JOIN class_subjects cs ON s.subject_id = cs.subject_id
                              WHERE cs.class_id = ? ORDER BY s.subject_name";
    $stmt_assigned = $conn->prepare($assigned_subjects_sql);
    $stmt_assigned->bind_param("i", $class_id);
    $stmt_assigned->execute();
    $assigned_result = $stmt_assigned->get_result();
    while ($row = $assigned_result->fetch_assoc()) {
        $assigned_subjects[$row['subject_id']] = $row['subject_name'];
    }
    $stmt_assigned->close();

    // Fetch subjects not assigned to this class
    $available_subjects_sql = "SELECT subject_id, subject_name FROM subjects WHERE subject_id NOT IN (SELECT subject_id FROM class_subjects WHERE class_id = ?) ORDER BY subject_name";
    $stmt_available = $conn->prepare($available_subjects_sql);
    $stmt_available->bind_param("i", $class_id);
    $stmt_available->execute();
    $available_result = $stmt_available->get_result();
    while ($row = $available_result->fetch_assoc()) {
        $available_subjects[$row['subject_id']] = $row['subject_name'];
    }
    $stmt_available->close();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Class Subjects</title>
    <link rel="stylesheet" href="/school_management/public/css/style.css">
    <style>
        .subject-form-container {
            display: flex;
            justify-content: space-around;
            gap: 20px;
        }
        .subject-list, .add-subject {
            width: 45%;
        }
        .subject-list ul, .add-subject ul {
            list-style-type: none;
            padding: 0;
        }
        .subject-list li, .add-subject li {
            background-color: #ecf0f1;
            padding: 10px;
            margin-bottom: 5px;
            border-radius: 5px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
    </style>
</head>
<body>
<div class="header">
    <h1>School Management System</h1>
    <div class="nav">
        <a href="/school_management/public/dashboard.php">Dashboard</a>
        <a href="/school_management/public/students/students_list.php">Students</a>
        <a href="/school_management/public/teachers/teachers_list.php">Teachers</a>
        <a href="/school_management/public/fees/fee_collection.php">Fees</a>
        <a href="/school_management/public/subjects/subjects_list.php">Subjects</a>
        <a href="/school_management/public/exam_results/add_exam_result.php">Exams</a>
        <a href="/school_management/public/attendance/record_attendance.php">Attendance</a>
        <a href="/school_management/public/change_password.php">Change Password</a>
        <a href="/school_management/public/logout.php">Logout</a>
    </div>
</div>

<div class="content">
    <div class="container">
        <h2>Manage Subjects by Class</h2>
        <?php if ($message): ?><p style='color:green;'><?php echo $message; ?></p><?php endif; ?>
        <?php if ($error): ?><p style='color:red;'><?php echo $error; ?></p><?php endif; ?>

        <form action="" method="GET">
            <label for="class_id">Select Class:</label>
            <select id="class_id" name="class_id" onchange="this.form.submit()" required>
                <option value="">--Select a Class--</option>
                <?php
                while($row = $classes_result->fetch_assoc()) {
                    $selected = ($class_id == $row['class_id']) ? 'selected' : '';
                    echo "<option value='" . htmlspecialchars($row['class_id']) . "' " . $selected . ">" . htmlspecialchars($row['class_name']) . "</option>";
                }
                ?>
            </select>
        </form>

        <?php if ($class_id && $class_name): ?>
        <h3>Subjects for Class: <?php echo htmlspecialchars($class_name); ?></h3>
        <div class="subject-form-container">
            <div class="subject-list">
                <h4>Assigned Subjects</h4>
                <?php if (empty($assigned_subjects)): ?>
                    <p>No subjects assigned to this class yet.</p>
                <?php else: ?>
                    <ul>
                        <?php foreach ($assigned_subjects as $subject_id => $subject_name): ?>
                            <li>
                                <?php echo htmlspecialchars($subject_name); ?>
                                <form action="" method="POST" style="display:inline;">
                                    <input type="hidden" name="class_id" value="<?php echo htmlspecialchars($class_id); ?>">
                                    <input type="hidden" name="subject_id" value="<?php echo htmlspecialchars($subject_id); ?>">
                                    <button type="submit" name="remove_subject" class="button">Remove</button>
                                </form>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                <?php endif; ?>
            </div>
            
            <div class="add-subject">
                <h4>Available Subjects</h4>
                <?php if (empty($available_subjects)): ?>
                    <p>No new subjects to add.</p>
                <?php else: ?>
                    <ul>
                        <?php foreach ($available_subjects as $subject_id => $subject_name): ?>
                            <li>
                                <?php echo htmlspecialchars($subject_name); ?>
                                <form action="" method="POST" style="display:inline;">
                                    <input type="hidden" name="class_id" value="<?php echo htmlspecialchars($class_id); ?>">
                                    <input type="hidden" name="subject_id" value="<?php echo htmlspecialchars($subject_id); ?>">
                                    <button type="submit" name="add_subject" class="button">Add</button>
                                </form>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>
    </div>
    <div class="footer">
        <p>&copy; <?php echo date("Y"); ?> School Management System. All Rights Reserved.</p>
    </div>
</div>
</body>
</html>