<?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');
include('includes/flash.php');

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

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

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

// Session guard
if (empty($_SESSION['sid'])) {
    header('Location: logout.php');
    exit;
}

// Only accept POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: registration_token.php');
    exit;
}

$action = $_POST['action'] ?? '';

if ($action === 'single') {
    handle_single($con);
} elseif ($action === 'bulk') {
    handle_bulk($con);
} else {
    flash_alert('Invalid action.');
    header('Location: registration_token.php');
    exit;
}

// ---------------------------------------------------------------------------
// build_reminder_email — returns the HTML email body
// ---------------------------------------------------------------------------
function build_reminder_email(string $studentName, string $token, string $schoolName, string $registrationUrl = ''): string
{
    $safeName   = htmlspecialchars($studentName,     ENT_QUOTES, 'UTF-8');
    $safeToken  = htmlspecialchars($token,           ENT_QUOTES, 'UTF-8');
    $safeSchool = htmlspecialchars($schoolName,      ENT_QUOTES, 'UTF-8');
    $fullUrl    = rtrim($registrationUrl, '/') . '/portal/registration.php';
    $safeUrl    = htmlspecialchars($fullUrl, ENT_QUOTES, 'UTF-8');

    $linkBlock = $registrationUrl
        ? "<p style=\"text-align:center;margin:24px 0;\">
             <a href=\"{$safeUrl}\" style=\"background:#003366;color:#fff;padding:12px 28px;
                border-radius:5px;text-decoration:none;font-size:15px;font-weight:bold;\">
               Go to Registration Portal
             </a>
           </p>
           <p style=\"font-size:12px;color:#888;text-align:center;\">
             Or copy this link into your browser:<br>
             <a href=\"{$safeUrl}\" style=\"color:#003366;\">{$safeUrl}</a>
           </p>"
        : "<p>Please visit the school registration portal and enter your token when prompted.</p>";

    return <<<HTML
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <style>
    body { font-family: Arial, sans-serif; background: #f4f4f4; margin: 0; padding: 0; }
    .container { max-width: 600px; margin: 30px auto; background: #fff;
                 border-radius: 8px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,.1); }
    .header { background: #003366; color: #fff; padding: 24px 32px; text-align: center; }
    .header h1 { margin: 0; font-size: 22px; }
    .body { padding: 32px; color: #333; line-height: 1.6; }
    .token-box { background: #f0f4ff; border: 2px solid #003366; border-radius: 6px;
                 text-align: center; padding: 20px; margin: 24px 0; }
    .token-box span { font-size: 28px; font-weight: bold; color: #003366;
                      letter-spacing: 4px; }
    .footer { background: #f4f4f4; text-align: center; padding: 16px;
              font-size: 12px; color: #888; }
  </style>
</head>
<body>
  <div class="container">
    <div class="header">
      <h1>{$safeSchool}</h1>
      <p style="margin:4px 0 0">Student Registration Reminder</p>
    </div>
    <div class="body">
      <p>Dear <strong>{$safeName}</strong>,</p>
      <p>This is a reminder that your registration token has been issued but not yet used.
         Please use the token below to complete your registration form:</p>
      <div class="token-box">
        <span>{$safeToken}</span>
      </div>
      {$linkBlock}
      <p>If you have already completed your registration, please disregard this message.</p>
      <p>For assistance, contact the school administration.</p>
    </div>
    <div class="footer">
      &copy; {$safeSchool}. All rights reserved.
    </div>
  </div>
</body>
</html>
HTML;
}

// ---------------------------------------------------------------------------
// handle_single — send reminder to one student
// ---------------------------------------------------------------------------
function handle_single($con): void
{
    $tokenId = intval($_POST['token_id'] ?? 0);

    if ($tokenId <= 0) {
        flash_alert('Invalid token ID.');
        header('Location: registration_token.php');
        exit;
    }

    // Fetch the token record
    $stmt = $con->prepare("SELECT * FROM registration_tokens WHERE id = ? LIMIT 1");
    $stmt->bind_param("i", $tokenId);
    $stmt->execute();
    $result = $stmt->get_result();
    $row    = $result->fetch_assoc();
    $stmt->close();

    if (!$row) {
        flash_alert('Token record not found.');
        header('Location: registration_token.php');
        exit;
    }

    $studentName = $row['student_name'];
    $token       = $row['token'];
    $email       = trim($row['email']);

    if (empty($email)) {
        flash_alert('No email on record for ' . htmlspecialchars($studentName) . '.');
        header('Location: registration_token.php');
        exit;
    }

    $schoolName  = $_ENV['SCHOOL_NAME'];
    $senderEmail = $_ENV['SMTP_USERNAME'];
    $subject     = 'Registration Token Reminder – ' . $schoolName;
    $body        = build_reminder_email($studentName, $token, $schoolName, $_ENV['BASE_URL'] ?? '');
    $status      = 'Failed';
    
    try {
        $mail = new PHPMailer(true);
        $mail->isSMTP();
        $mail->Host       = $_ENV['SMTP_HOST'];
        $mail->SMTPAuth   = true;
        $mail->Username   = $_ENV['SMTP_USERNAME'];
        $mail->Password   = $_ENV['SMTP_PASSWORD'];
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        $mail->Port       = 465;
        $mail->Timeout    = 10;

        $mail->setFrom($senderEmail, $schoolName);
        $mail->addReplyTo($senderEmail, $schoolName);
        $mail->addAddress($email, $studentName);
        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body    = $body;

        $mail->send();
        $status = 'Success';
        flash_alert('Reminder sent to ' . htmlspecialchars($studentName) . ' (' . htmlspecialchars($email) . ').');
    } catch (Exception $e) {
        $status = 'Failed';
        flash_alert('Failed to send reminder to ' . htmlspecialchars($studentName) . ': ' . addslashes($mail->ErrorInfo));
    }

    // Log the attempt
    $logStmt = $con->prepare(
        "INSERT INTO email_logs (recipient, sender_email, subject, status, timestamp) VALUES (?, ?, ?, ?, NOW())"
    );
    $logStmt->bind_param("ssss", $email, $senderEmail, $subject, $status);
    $logStmt->execute();
    $logStmt->close();

    header('Location: registration_token.php');
    exit;
}

// ---------------------------------------------------------------------------
// handle_bulk — send reminders to all pending students with a valid email
// ---------------------------------------------------------------------------
function handle_bulk($con): void
{
    $schoolName  = $_ENV['SCHOOL_NAME'];
    $senderEmail = $_ENV['SMTP_USERNAME'];
    $subject     = 'Registration Token Reminder – ' . $schoolName;

    // Fetch all pending tokens with a non-empty email
    $stmt = $con->prepare(
        "SELECT * FROM registration_tokens WHERE token_status = 'pending' AND email != '' AND email IS NOT NULL"
    );
    $stmt->execute();
    $result = $stmt->get_result();
    $rows   = $result->fetch_all(MYSQLI_ASSOC);
    $stmt->close();

    if (empty($rows)) {
        flash_alert('No pending tokens with a valid email address found.');
        header('Location: registration_token.php');
        exit;
    }

    $sent   = 0;
    $failed = 0;

    foreach ($rows as $row) {
        $studentName = $row['student_name'];
        $token       = $row['token'];
        $email       = trim($row['email']);
        $status      = 'Failed';

        try {
            $mail = new PHPMailer(true);
            $mail->isSMTP();
            $mail->Host       = $_ENV['SMTP_HOST'];
            $mail->SMTPAuth   = true;
            $mail->Username   = $_ENV['SMTP_USERNAME'];
            $mail->Password   = $_ENV['SMTP_PASSWORD'];
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
            $mail->Port       = 465;
            $mail->Timeout    = 10;

            $mail->setFrom($senderEmail, $schoolName);
            $mail->addReplyTo($senderEmail, $schoolName);
            $mail->addAddress($email, $studentName);
            $mail->isHTML(true);
            $mail->Subject = $subject;
            $mail->Body    = build_reminder_email($studentName, $token, $schoolName, $_ENV['BASE_URL'] ?? '');

            $mail->send();
            $status = 'Success';
            $sent++;
        } catch (Exception $e) {
            $status = 'Failed';
            $failed++;
        }

        // Log each attempt independently
        $logStmt = $con->prepare(
            "INSERT INTO email_logs (recipient, sender_email, subject, status, timestamp) VALUES (?, ?, ?, ?, NOW())"
        );
        $logStmt->bind_param("ssss", $email, $senderEmail, $subject, $status);
        $logStmt->execute();
        $logStmt->close();
    }

    flash_alert("Bulk reminder sent: {$sent} succeeded, {$failed} failed.");
    header('Location: registration_token.php');
    exit;
}
