<?php
session_name('super_admin_session');
if (!is_dir(dirname(__DIR__) . '/session_data/super')) {
    mkdir(dirname(__DIR__) . '/session_data/super', 0700, true);
}
session_save_path(dirname(__DIR__) . '/session_data/super');
session_set_cookie_params(['path' => '/', 'httponly' => true, 'samesite' => 'Strict']);
session_start();
error_reporting(0);
include('includes/dbconnection.php');
require_once __DIR__ . '/includes/session_term_helper.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'phpmailer/src/Exception.php';
require 'phpmailer/src/PHPMailer.php';
require 'phpmailer/src/SMTP.php';
require_once 'vendor/autoload.php';

$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();

// Validate input
if (!isset($_POST['teachers']) || !is_array($_POST['teachers']) || empty($_POST['teachers'])) {
    $_SESSION['msg'] = 'No teacher selected for notification.';
    header("Location: {$_SERVER['HTTP_REFERER']}");
    exit();
}

$class = mysqli_real_escape_string($con, $_POST['class'] ?? '');
$section = mysqli_real_escape_string($con, $_POST['section'] ?? '');
$triggered_by = $_POST['triggered_by'] ?? 'admin';

function fetchCurrentSessionTerm($con)
{
    $st = resolveCurrentSessionTerm($con);
    return [$st['session_id'], $st['term_id']];
}

list($session_id, $term_id) = fetchCurrentSessionTerm($con);

// Get list of teacher IDs and sanitize
$teacher_ids = array_map('intval', $_POST['teachers']);
$teacher_ids_sql = implode(',', $teacher_ids);

// Fetch subject(s) for each teacher
$query = "
    SELECT 
        t.id AS teacher_id,
        t.name,
        t.lastname,
        t.email,
        sc.subject_name
    FROM teacher_assignments ta
    JOIN tblusers t ON ta.teacher_id = t.id
    JOIN subjectcombination sc ON ta.subject_id = sc.id
    JOIN class_section cs ON sc.class = cs.class AND sc.section = cs.section
    WHERE cs.class = '$class' AND cs.section = '$section'
      AND ta.teacher_id IN ($teacher_ids_sql)
";

$result = mysqli_query($con, $query);

// Group subject names by teacher
$teachers_map = [];
while ($row = mysqli_fetch_assoc($result)) {
    $tid = $row['teacher_id'];
    if (!isset($teachers_map[$tid])) {
        $teachers_map[$tid] = [
            'name' => $row['name'],
            'lastname' => $row['lastname'],
            'email' => $row['email'],
            'subjects' => [],
        ];
    }
    $teachers_map[$tid]['subjects'][] = $row['subject_name'];
}

// Initialize PHPMailer
$mail = new PHPMailer(true);
$mail->isSMTP();
$mail->Host = $_ENV['SMTP_HOST'];
$mail->SMTPAuth = true;
$mail->Username = $_ENV['SMTP_NO_REPLY'];
$mail->Password = $_ENV['SMTP_NO_REPLY_PASSWORD'];
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
$mail->Port = $_ENV['SMTP_PORT'];
$mail->Timeout = 10;
$mail->setFrom($_ENV['SMTP_NO_REPLY'], $_ENV['SCHOOL_NAME']);

$sent = 0;
$failed = 0;

foreach ($teachers_map as $tid => $data) {
    if (empty($data['email'])) {
        $failed++;
        continue;
    }

    $subject_list = implode(', ', array_unique($data['subjects']));

    try {
        $mail->clearAddresses();
        $mail->addAddress($data['email'], $data['name'] . ' ' . $data['lastname']);
        $mail->isHTML(true);

        $subject = "Reminder: Submit Your Result(s) for $class $section";
        $body = "
    <h3 style='color:#2a2a2a;'>Result Submission Reminder</h3>
    <p>Dear <strong>{$data['name']} {$data['lastname']}</strong>,</p>
    <p>You have not yet submitted the result(s) for the following subject(s):</p>
    <ul><li><strong>$subject_list</strong></li></ul>
    <p><strong>Class:</strong> $class $section</p>
    <p>Please submit as soon as possible. If you've already submitted, kindly check again for some incomplete details.</p>
    <br>
    <p>Regards,<br><strong>School Admin</strong></p>
        ";

        $mail->Subject = $subject;
        $mail->Body = $body;
        $mail->send();
        $sent++;
    } catch (Exception $e) {
        $failed++;
    }
}

// Redirect back with message
$_SESSION['msg'] = "$sent reminder(s) sent.";
$_SESSION['msg_type'] = ($failed === 0) ? 'alert-success' : 'alert-warning';
$redirect = (!empty($_SERVER['HTTP_REFERER'])) ? $_SERVER['HTTP_REFERER'] : 'admin_track_submissions.php';
header("Location: $redirect");
exit();
// End of file send_bulk_notifications.php
?>
