<?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'];

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

require_once 'vendor/autoload.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $message = trim($_POST['message'] ?? '');
    $subject = trim($_POST['subject'] ?? '');

    if (empty($message)) {
        die("âŒ Message cannot be empty.");
    }

    // Fetch Unique Emails
    $stmt = $con->prepare("SELECT DISTINCT email FROM students");
    $stmt->execute();
    $result = $stmt->get_result();
    $emails = $result->fetch_all(MYSQLI_ASSOC);
    $stmt->close();

    if (empty($emails)) {
        die("âš ï¸ No subscribers found.");
    }

    $mail = new PHPMailer(true);
    try {
        $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 = $_ENV['SMTP_PORT'];
        $mail->Timeout = 10;

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

        // Handle Attachments
        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);
        }

        // Send Emails & Log
        foreach ($emails as $email) {
            $recipient = $email['email'];
            $mail->addAddress($recipient);

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

            $mail->clearAddresses();
        }

        echo "âœ… Newsletter sent successfully!";
    } catch (Exception $e) {
        echo "âŒ Error: " . $mail->ErrorInfo;
    }

    $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;
    }

    .modal {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
    }

    .modal-content {
        background: white;
        padding: 20px;
        border-radius: 10px;
        width: 100%;
        max-width: 500px;
    }

    .close {
        float: right;
        font-size: 20px;
        cursor: pointer;
    }
</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="newsletter.php" method="POST" enctype="multipart/form-data">
                                        <input type="hidden" name="message" id="hiddenMessage">
                                        <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" style="width: 100%; padding: 10px; margin-bottom: 10px;" required>

                                        <div id="editor"></div>

                                        <label for="attachment"><i class="fas fa-paperclip"></i> Attach File (Optional):</label>
                                        <input type="file" id="attachment" name="attachment">

                                        <div class="button-group">
                                            <button type="submit" id="sendButton"><i class="fas fa-check-circle"></i> Send Newsletter</button>
                                        </div>
                                        <div id="statusMessage"></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 previewButton = document.getElementById("previewButton");
                                        var sendButton = document.getElementById("sendButton");
                                        var statusMessage = document.getElementById("statusMessage");
                                        var modal = document.getElementById("previewModal");
                                        var closeModal = document.querySelector(".close");

                                        previewButton.addEventListener("click", function() {
                                            let message = quill.root.innerHTML.trim();
                                            if (message === "<p><br></p>") {
                                                alert("âš ï¸ Please design your newsletter before previewing!");
                                                return;
                                            }
                                            document.getElementById("previewContent").innerHTML = message;
                                            modal.style.display = "flex";
                                        });

                                        closeModal.addEventListener("click", function() {
                                            modal.style.display = "none";
                                        });

                                        window.addEventListener("click", function(event) {
                                            if (event.target === modal) {
                                                modal.style.display = "none";
                                            }
                                        });
                                    });
                                </script>
                            </div>

                        </div>
                    </div>
                </div>
            </section>
        </div>


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

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

</body>

</html>
