<?php
include 'includes/conn.php';
include 'includes/functions.php';

$selected_class_id = $_POST['classroom_id'] ?? '';
$selected_class_id = (int)$selected_class_id;
$success_message = $error_message = "";

// Handle form submission
if (isset($_POST['assign_subjects'])) {
    $subject_ids = $_POST['subject_ids'] ?? [];

    if ($selected_class_id && !empty($subject_ids)) {
        $pdo->beginTransaction();
        try {
            $pdo->prepare("DELETE FROM class_subjects WHERE classroom_id = ?")->execute([$selected_class_id]);
            $insert_stmt = $pdo->prepare("INSERT INTO class_subjects (classroom_id, subject_id) VALUES (?, ?)");
            foreach ($subject_ids as $subject_id) {
                $insert_stmt->execute([$selected_class_id, $subject_id]);
            }
            $pdo->commit();
            $success_message = "✅ Subjects successfully assigned to this class!";
        } catch (Exception $e) {
            $pdo->rollBack();
            $error_message = "❌ Error assigning subjects: " . $e->getMessage();
        }
    } else {
        $error_message = "⚠️ Please select a class and at least one subject.";
    }
}

// Fetch data
$classes = $pdo->query("SELECT * FROM classrooms ORDER BY name ASC")->fetchAll();
$subjects = $pdo->query("SELECT * FROM subjects ORDER BY name ASC")->fetchAll();

$current_subjects = [];
if ($selected_class_id) {
    $stmt = $pdo->prepare("SELECT subject_id FROM class_subjects WHERE classroom_id = ?");
    $stmt->execute([$selected_class_id]);
    $current_subjects = $stmt->fetchAll(PDO::FETCH_COLUMN);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="icon" type="image/png" sizes="32x32" href="BCA-Logo.png">
    <link rel="icon" type="image/png" sizes="16x16" href="BCA-Logo.png">
    <title>Assign Subjects to Class</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="major.css" rel="stylesheet">
</head>
<body class="">
        <nav class="navbar navbar-expand-lg navbar-dark bg-success">
        <div class="container">
            <a class="navbar-brand" href="admin.php">
                <i class="fas fa-chalkboard-teacher"></i> Admin Portal
            </a>
            <div class="navbar-nav ms-auto">
                <span class="navbar-text me-3">
                    Welcome, <?php echo $_SESSION['first_name']; ?>
                </span>
                <button id="themeToggle" class="toggle-btn">
                    <i class="fas fa-moon"></i> Dark Mode
                </button>
                <script src="dark.js"></script>
                <a class="nav-link" href="admin.php">Dashboard</a>
                <a class="nav-link" href="logout.php">Logout</a>
            </div>
        </div>
    </nav>
<div class="container py-5">
    <div class="card shadow-lg">
        <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
            <h4 class="mb-0">Assign Subjects to Class</h4>
        </div>
        <div class="card-body">
            <?php if ($success_message): ?>
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    <?= htmlspecialchars($success_message) ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php elseif ($error_message): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <?= htmlspecialchars($error_message) ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <form method="POST" class="mb-4">
                <div class="mb-3">
                    <label for="classroom_id" class="form-label fw-bold">Select Class</label>
                    <select name="classroom_id" id="classroom_id" class="form-select" onchange="this.form.submit()">
                        <option value="">-- Choose Class --</option>
                        <?php foreach ($classes as $class): ?>
                            <option value="<?= $class['id'] ?>" <?= $selected_class_id == $class['id'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($class['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </form>

            <?php if ($selected_class_id): ?>
                <form method="POST">
                    <input type="hidden" name="classroom_id" value="<?= $selected_class_id ?>">
                    <div class="row">
                        <?php foreach ($subjects as $subject): ?>
                            <div class="col-md-4 mb-3">
                                <div class="form-check border rounded p-2 shadow-sm">
                                    <input class="form-check-input" type="checkbox" name="subject_ids[]" 
                                           value="<?= $subject['id'] ?>"
                                           id="sub<?= $subject['id'] ?>"
                                           <?= in_array($subject['id'], $current_subjects) ? 'checked' : '' ?>>
                                    <label class="form-check-label fw-semibold" for="sub<?= $subject['id'] ?>">
                                        <?= htmlspecialchars($subject['name']) ?>
                                    </label>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                    <div class="text-end mt-4">
                        <button type="submit" name="assign_subjects" class="btn btn-success px-4">
                            <i class="fas fa-save me-2"></i>Save Changes
                        </button>
                    </div>
                </form>
            <?php endif; ?>
        </div>
    </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
