<?php
include('inc/check_login.php');
require_once('inc/db.php');

// Nur Admins dürfen Mails senden
if ($_SESSION['role'] !== 'admin') {
    header("Location: index.php");
    exit();
}

define('APP_URL', 'https://domili.borgal.de');

$message = '';
$message_type = '';

function get_all_users($conn)
{
    $stmt = mysqli_prepare($conn, "SELECT id, username FROM users ORDER BY username");
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    $users = [];
    while ($row = mysqli_fetch_assoc($result)) {
        $users[] = $row;
    }
    mysqli_stmt_close($stmt);
    return $users;
}

// --- MAIL SENDEN ---
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
        $message = "PHPMailer nicht verfügbar.";
        $message_type = 'danger';
    } else {
        require_once __DIR__ . '/vendor/autoload.php';

        $subject = trim($_POST['subject'] ?? '');
        $body = trim($_POST['body'] ?? '');
        $recipient_ids = $_POST['recipients'] ?? [];

        if (empty($subject) || empty($body)) {
            $message = "Betreff und Nachricht sind erforderlich.";
            $message_type = 'danger';
        } else {
            $all_users = get_all_users($conn);
            if (in_array('all', $recipient_ids)) {
                $recipient_ids = array_column($all_users, 'id');
            } else {
                $recipient_ids = array_filter(array_map('intval', $recipient_ids));
            }

            if (empty($recipient_ids)) {
                $message = "Keine Empfänger ausgewählt.";
                $message_type = 'warning';
            } else {
                $placeholders = str_repeat('?,', count($recipient_ids) - 1) . '?';
                $stmt = mysqli_prepare($conn, "SELECT id, username, email FROM users WHERE id IN ($placeholders) AND email IS NOT NULL AND email != ''");
                mysqli_stmt_bind_param($stmt, str_repeat('i', count($recipient_ids)), ...$recipient_ids);
                mysqli_stmt_execute($stmt);
                $recipients = mysqli_fetch_all(mysqli_stmt_get_result($stmt), MYSQLI_ASSOC);
                mysqli_stmt_close($stmt);

                if (empty($recipients)) {
                    $message = "Keine gültigen Empfänger mit E-Mail gefunden.";
                    $message_type = 'warning';
                } else {
                    foreach ($recipients as $r) {
                        try {
                            $mail = new \PHPMailer\PHPMailer\PHPMailer(true);
                            $mail->CharSet = 'UTF-8';
                            $mail->isSMTP();
                            $mail->Host       = SMTP_HOST;
                            $mail->SMTPAuth   = true;
                            $mail->Username   = SMTP_USERNAME;
                            $mail->Password   = SMTP_PASSWORD;
                            $mail->SMTPSecure = SMTP_ENCRYPTION;
                            $mail->Port       = SMTP_PORT;
                            $mail->setFrom(MAIL_FROM_ADDRESS, MAIL_FROM_NAME);

                            $html_body = "<p>Hallo <strong>" . htmlspecialchars($r['username']) . "</strong>,</p>\n<p>" . nl2br(htmlspecialchars($body)) . "</p>\n<p><em>Dein DoMiLi-Admin</em></p>";
                            $text_body = "Hallo " . $r['username'] . ",\n\n" . $body . "\n\nDein DoMiLi-Admin";

                            $mail->isHTML(true);
                            $mail->Subject = $subject;
                            $mail->Body    = $html_body;
                            $mail->AltBody = $text_body;
                            $mail->addAddress($r['email']);
                            $mail->send();
                        } catch (Exception $e) {
                            error_log("Mail-Fehler an {$r['email']}: " . $mail->ErrorInfo);
                        }
                    }
                    $message = "E-Mail wurde an " . count($recipients) . " Empfänger gesendet.";
                    $message_type = 'success';
                }
            }
        }
    }
}

$all_users = get_all_users($conn);

require_once('inc/header.php');
?>

<div class="container mt-5 mb-4">
    <?php if ($message): ?>
        <div class="alert alert-<?= htmlspecialchars($message_type) ?> alert-dismissible fade show" role="alert">
            <?= htmlspecialchars($message) ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <h2 class="mb-4">📧 Nachricht senden</h2>

    <div class="card shadow">
        <div class="card-body">
            <form method="POST">
                <div class="mb-3">
                    <label class="form-label">Empfänger</label>
                    <div class="form-check mb-2">
                        <input class="form-check-input" type="checkbox" id="select_all" onchange="document.querySelectorAll('.recipient').forEach(el => el.checked = this.checked)">
                        <label class="form-check-label" for="select_all">Alle auswählen</label>
                    </div>
                    <div style="max-height: 150px; overflow-y: auto; border: 1px solid #ddd; padding: 0.5em; border-radius: 0.375rem;">
                        <?php foreach ($all_users as $u): ?>
                            <div class="form-check">
                                <input class="form-check-input recipient" type="checkbox" name="recipients[]" value="<?= $u['id'] ?>" id="rec_<?= $u['id'] ?>">
                                <label class="form-check-label" for="rec_<?= $u['id'] ?>"><?= htmlspecialchars($u['username']) ?></label>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
                <div class="mb-3">
                    <label class="form-label">Betreff</label>
                    <input type="text" class="form-control" name="subject" required>
                </div>
                <div class="mb-3">
                    <label class="form-label">Nachricht</label>
                    <textarea class="form-control" name="body" rows="5" required></textarea>
                </div>
                <button type="submit" class="btn btn-primary">E-Mail senden</button>
                <a href="javascript:history.back()" class="btn btn-outline-secondary ms-2">Zurück</a>
            </form>
        </div>
    </div>
</div>

<script>
    document.getElementById('select_all').addEventListener('change', function() {
        document.querySelectorAll('.recipient').forEach(cb => cb.checked = this.checked);
    });
</script>

<?php include('inc/footer.php'); ?>