<?php
session_name('mini_admin_session');
session_start();
error_reporting(0);
include('includes/dbconnection.php');
require_once 'includes/session_term_helper.php';
$stResult = resolveCurrentSessionTerm($con);
$currentSessionName = $stResult['session_name'];
$currentTermName    = $stResult['term_name'];
include('includes/flash.php');

// Include PHPMailer
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';

// Load Composer dependencies
require_once 'vendor/autoload.php';

// Load environment variables
$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv->load();

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $message = trim($_POST['message'] ?? '');
    $subject = trim($_POST['subject'] ?? '');
    $manualEmailsInput = trim($_POST['manualEmails'] ?? '');
    $sendFrom = $_POST['send_from'] ?? 'general';

    // Role-to-email mapping
    switch ($sendFrom) {
        case 'admin':
            $senderEmail = $_ENV['ADMIN_EMAIL']; // admin@acionlineportal.com.ng
            $senderPass = $_ENV['ADMIN_PASS'];
            break;
        case 'admission':
            $senderEmail = $_ENV['ADMISSION_EMAIL']; // admissions@acionlineportal.com.ng
            $senderPass = $_ENV['ADMISSION_PASS'];
            break;
        case 'feedback':
            $senderEmail = $_ENV['FEEDBACK_EMAIL']; // feedback@acionlineportal.com.ng
            $senderPass = $_ENV['FEEDBACK_PASS'];
            break;
        case 'noreply':
            $senderEmail = $_ENV['NOREPLY_EMAIL']; // noreply@acionlineportal.com.ng
            $senderPass = $_ENV['NOREPLY_PASS'];
            break;
        case 'notification':
            $senderEmail = $_ENV['NOTIFICATION_EMAIL']; // notification@acionlineportal.com.ng
            $senderPass = $_ENV['NOTIFICATION_PASS'];
            break;
        case 'finance':
            $senderEmail = $_ENV['FINANCE_EMAIL'];
            $senderPass = $_ENV['FINANCE_PASS'];
            break;
        case 'teacher':
            $senderEmail = $_ENV['TEACHER_EMAIL'];
            $senderPass = $_ENV['TEACHER_PASS'];
            break;
        case 'class_teacher':
            $senderEmail = $_ENV['CLASS_TEACHER_EMAIL'];
            $senderPass = $_ENV['CLASS_TEACHER_PASS'];
            break;
        default:
            $senderEmail = $_ENV['SCHOOL_EMAIL']; // fallback to general
            $senderPass = $_ENV['SCHOOL_PASS'];
    }

    if (empty($message)) {
        flash_alert('Message cannot be empty.');
        header('Location: ' . ($_SERVER['HTTP_REFERER'] ?? 'javascript:history.back()')); exit;
        exit;
    }

    if (empty($manualEmailsInput)) {
        flash_alert('Please enter at least one email address.');
        header('Location: ' . ($_SERVER['HTTP_REFERER'] ?? 'javascript:history.back()')); exit;
        exit;
    }

    // Split emails and validate
    $manualEmails = array_map('trim', explode(',', $manualEmailsInput));
    $validEmails = [];

    foreach ($manualEmails as $email) {
        if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $validEmails[] = $email;
        }
    }

    if (empty($validEmails)) {
        flash_alert('No valid email addresses found.');
        header('Location: ' . ($_SERVER['HTTP_REFERER'] ?? 'javascript:history.back()')); exit;
        exit;
    }

    try {
        foreach ($validEmails as $recipient) {
            // Fresh PHPMailer instance for each email
            $mail = new PHPMailer(true);
            $mail->isSMTP();
            $mail->Host = $_ENV['SMTP_HOST'];
            $mail->SMTPAuth = true;
            $mail->Username = $senderEmail;
            $mail->Password = $senderPass;
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
            $mail->Port = $_ENV['SMTP_PORT'];
            $mail->Timeout = 10;

            $mail->setFrom($senderEmail, $_ENV['SCHOOL_NAME']);
            $mail->addReplyTo($senderEmail, $_ENV['SCHOOL_NAME']);
            $mail->Subject = $subject;
            $mail->Body = $message;
            $mail->isHTML(true);
            $mail->addAddress($recipient);

            // Handle Attachment (optional)
            if (!empty($_FILES['attachment']['name'])) {
                $uploadDir = 'uploads/';
                if (!is_dir($uploadDir)) {
                    mkdir($uploadDir, 0777, true);
                }
                $filePath = $uploadDir . basename($_FILES['attachment']['name']);
                move_uploaded_file($_FILES['attachment']['tmp_name'], $filePath);
                $mail->addAttachment($filePath);
            }

            if ($mail->send()) {
                $status = "Success";
                $stmt = $con->prepare("INSERT INTO email_logs (recipient, sender_email, subject, status, timestamp) VALUES (?, ?, ?, ?, NOW())");
                $stmt->bind_param("ssss", $recipient, $senderEmail, $subject, $status);
                $stmt->execute();
                $stmt->close();
            } else {
                $status = "Failed";
                $stmt = $con->prepare("INSERT INTO email_logs (recipient, sender_email, subject, status, timestamp) VALUES (?, ?, ?, ?, NOW())");
                $stmt->bind_param("ssss", $recipient, $senderEmail, $subject, $status);
                $stmt->execute();
                $stmt->close();
            }
            
        }

        flash_alert('Newsletter sent successfully!');
        header('Location: ' . ($_SERVER['HTTP_REFERER'] ?? 'javascript:history.back()')); exit;
    } catch (Exception $e) {
        flash_alert('Error: ' . addslashes($mail->ErrorInfo));
        header('Location: ' . ($_SERVER['HTTP_REFERER'] ?? 'javascript:history.back()')); exit;
    }

    $con->close();
    exit;
}

?>
<!DOCTYPE html>
<html lang="en">
<?php @include("includes/head.php"); ?>

<link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
<style>
    .container {
        background: white;
        padding: 20px;
        border-radius: 10px;
        box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
    }

    #editor {
        background: white;
        border: 1px solid #ddd;
        min-height: 200px;
        border-radius: 5px;
        padding: 10px;
        text-align: left;
    }

    .button-group {
        display: flex;
        gap: 10px;
        margin-top: 10px;
    }

    button {
        flex: 1;
        padding: 12px;
        background-color: #007bff;
        color: white;
        border: none;
        border-radius: 5px;
        font-size: 16px;
        cursor: pointer;
        transition: 0.3s;
    }

    button:hover {
        background-color: #0056b3;
    }

    #statusMessage {
        margin-top: 10px;
        font-size: 14px;
        display: none;
    }
</style>

<body class="hold-transition sidebar-mini layout-fixed">
    <div class="wrapper">
        <?php @include("includes/header2.php"); ?>
        <?php @include("includes/sidebar2.php"); ?>

        <div class="content-wrapper">
<section class="content-header premium-header">
    <div class="container-fluid">
        <div class="header-glass-card">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <div class="title-section">
                        <div class="icon-box bg-primary-gradient shadow-sm">
                            <i class="fas fa-calendar"></i>
                        </div>
                        <div>
                            <h1 class="premium-title text-primary">
                                Event Management
                                <span class="premium-subtitle text-secondary">Manage Newsletter</span>
                            </h1>

                    <div class="mt-1">
                      <?php if ($currentSessionName): ?>
                        <span class="badge badge-primary mr-1">
                          <i class="fas fa-calendar-alt"></i>
                          <?= htmlspecialchars($currentSessionName) ?>
                        </span>
                      <?php endif; ?>
                      <?php if ($currentTermName): ?>
                        <span class="badge badge-success">
                          <i class="fas fa-bookmark"></i>
                          <?= htmlspecialchars($currentTermName) ?>
                        </span>
                      <?php else: ?>
                        <span class="badge badge-warning">
                          <i class="fas fa-exclamation-triangle"></i> No active term
                        </span>
                      <?php endif; ?>
                    </div>                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <nav aria-label="breadcrumb">
                        <ol class="breadcrumb premium-breadcrumb">
                            <li class="breadcrumb-item"><a href="dashboard1.php" class="text-primary">Home</a></li>
                            <li class="breadcrumb-item active" aria-current="page">Add Newsletter</li>
                        </ol>
                    </nav>
                </div>
            </div>
        </div>
    </div>
</section>  

            <section class="content">
                <div class="container-fluid">
                    <div class="row">
                        <div class="col-md-12">
                            <div class="card card-primary">
                                <div class="card-header">
                                    <h5 class="card-title font-weight-bold"><i class="fas fa-newspaper"></i> Create Newsletter</h5>
                                </div>
                                <div class="container">
                                    <h5><i class="fas fa-newspaper"></i> Design Your Newsletter</h5>
                                    <p>Use the editor below to create your newsletter content.</p>

                                    <form id="newsletterForm" action="newslettersp.php" method="POST" enctype="multipart/form-data">
                                        <input type="hidden" name="message" id="hiddenMessage">
                                        <!-- Send From Role -->
                                        <div class="form-group">
                                            <label for="send_from"><i class="fas fa-mail-bulk"></i> Send From:</label>
                                        <select name="send_from" id="send_from" class="form-control select2" required>
                                            <option value="">-- Select Role --</option>
                                            <option value="general">General Email (info@acionlineportal.com.ng)</option>
                                            <option value="admin">Admin Email (admin@acionlineportal.com.ng)</option>
                                            <option value="admission">Admission Team Email (admissions@acionlineportal.com.ng)</option>
                                            <option value="finance">Finance Department Email (finance@acionlineportal.com.ng)</option>
                                            <option value="teacher">Teacher Email (teacher@acionlineportal.com.ng)</option>
                                            <option value="class_teacher">Class Teacher Email (class_teacher@acionlineportal.com.ng)</option>
                                            <option value="feedback">Feedback Email (feedback@acionlineportal.com.ng)</option>
                                            <option value="noreply">No Reply Email (noreply@acionlineportal.com.ng)</option>
                                            <option value="notification">Notification Email (notification@acionlineportal.com.ng)</option>
                                        </select>
                                        </div>

                                        <!-- Recipient Emails -->
                                        <div class="form-group">
                                            <label for="manualEmails"><i class="fas fa-envelope"></i> Recipient Emails (Comma Separated):</label>
                                            <input type="text" id="manualEmails" name="manualEmails"
                                                placeholder="e.g. email1@example.com, email2@example.com"
                                                class="form-control" required>
                                        </div>
                                        <!-- Subject -->
                                        <div class="form-group">
                                            <label for="subject"><i class="fas fa-heading"></i> Subject:</label>
                                            <input type="text" id="subject" name="subject"
                                                placeholder="e.g. Notification on Admission Updates"
                                                class="form-control" required>
                                        </div>
                                        <!-- Editor -->
                                        <div class="form-group">
                                            <label for="editor"><i class="fas fa-pencil-alt"></i> Message:</label>
                                            <div id="editor" style="min-height: 200px; border: 1px solid #ddd; border-radius: 5px; padding: 10px;"></div>
                                        </div>

                                        <!-- File Attachment -->
                                        <div class="form-group">
                                            <label for="attachment"><i class="fas fa-paperclip"></i> Attach File (Optional):</label>
                                            <input type="file" id="attachment" name="attachment" class="form-control-file">
                                        </div>
                                        <!-- Submit Button -->
                                        <div class="form-group text-center mt-3">
                                            <button type="submit" id="sendButton" class="btn btn-primary">
                                                <i class="fas fa-check-circle"></i> Send Newsletter
                                            </button>
                                        </div>

                                        <!-- Status Message -->
                                        <div id="statusMessage" class="mt-3 text-center text-info"></div>
                                    </form>
                                </div>
                                <script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>
                                <script>
                                    document.addEventListener("DOMContentLoaded", function() {
                                        var quill = new Quill('#editor', {
                                            theme: 'snow',
                                            placeholder: 'Start designing your newsletter...',
                                            modules: {
                                                toolbar: true
                                            }
                                        });

                                        var form = document.getElementById("newsletterForm");
                                        var hiddenMessage = document.getElementById("hiddenMessage");

                                        form.addEventListener("submit", function(event) {
                                            hiddenMessage.value = quill.root.innerHTML.trim();

                                            if (hiddenMessage.value === "<p><br></p>" || hiddenMessage.value === "") {
                                                alert("âš ï¸ Please enter a message before sending!");
                                                event.preventDefault();
                                                return;
                                            }

                                            var emailInput = document.getElementById("manualEmails").value.trim();
                                            if (emailInput === "") {
                                                alert("âš ï¸ Please enter at least one email address.");
                                                event.preventDefault();
                                                return;
                                            }

                                            var emailList = emailInput.split(",");
                                            var invalidEmails = emailList.filter(function(email) {
                                                var trimmed = email.trim();
                                                var regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                                                return !regex.test(trimmed);
                                            });

                                            if (invalidEmails.length > 0) {
                                                alert("âŒ Invalid email(s) found: " + invalidEmails.join(", "));
                                                event.preventDefault();
                                            }
                                        });
                                    });
                                </script>
                            </div>
                        </div>
                    </div>
                </div>
            </section>
        </div>

        <?php @include("includes/footer.php"); ?>
    </div>

    <?php @include("includes/foot.php"); ?>
    <script src="dist/js/select2.min.js"></script>
    <script>
        $(document).ready(function() {
            $('.select2').select2();
        });
    </script>
</body>

</html>
