<?php
include('includes/dbconnection.php');

$class = $_POST['class'] ?? '';
$section = $_POST['section'] ?? '';
$group = $_POST['group'] ?? '';

$emails = [];

if ($group === 'students') {
    if ($class !== '' && $section !== '') {
        // Parent of a particular class and section
        $query = "SELECT DISTINCT email as email FROM students WHERE class = ? AND section = ?";
        $stmt = $con->prepare($query);
        $stmt->bind_param("ss", $class, $section);
    } elseif ($class !== '') {
        // Parent of a particular class
        $query = "SELECT DISTINCT email as email FROM students WHERE class = ?";
        $stmt = $con->prepare($query);
        $stmt->bind_param("s", $class);
    } else {
        // All parents
        $query = "SELECT DISTINCT email as email FROM students";
        $stmt = $con->prepare($query);
    }
} elseif ($group === 'parents') {
    if ($class !== '' && $section !== '') {
        // Parent of a particular class and section
        $query = "SELECT DISTINCT email as email FROM students WHERE class = ? AND section = ?";
        $stmt = $con->prepare($query);
        $stmt->bind_param("ss", $class, $section);
    } elseif ($class !== '') {
        // Parent of a particular class
        $query = "SELECT DISTINCT email as email FROM students WHERE class = ?";
        $stmt = $con->prepare($query);
        $stmt->bind_param("s", $class);
    } else {
        // All parents
        $query = "SELECT DISTINCT email as email FROM students";
        $stmt = $con->prepare($query);
    }
} elseif ($group === 'teachers') {
    $query = "SELECT DISTINCT email FROM tblusers WHERE Permission = 'Teacher' AND status = 2";
    $stmt = $con->prepare($query);
} elseif ($group === 'admins') {
    $query = "SELECT DISTINCT email FROM tblusers WHERE Permission = 'Admin' AND status = 1";
    $stmt = $con->prepare($query);
} elseif ($group === 'class_teachers') {
    $query = "SELECT DISTINCT tblusers.email 
    FROM teacher_assignments 
    JOIN tblusers ON teacher_assignments.teacher_id = tblusers.id 
    WHERE teacher_assignments.is_class_teacher = 1 
    AND tblusers.status = 2 
    AND tblusers.permission = 'Teacher'";
    $stmt = $con->prepare($query);
} else {
    echo '';
    exit;
}

$stmt->execute();
$result = $stmt->get_result();

while ($row = $result->fetch_assoc()) {
    if (!empty($row['email'])) {
        $emails[] = $row['email'];
    }
}

if (empty($emails)) {
    echo '';
} else {
    echo implode(', ', $emails);
}

$stmt->close();
$con->close();
?>