<?php
require_once('../common.php');
require_once('checklogin.php');

// Mass mail is an administrative capability.
if (!in_array($_SESSION['editor_type'] ?? '', ['admin', 'superadmin'], true)) {
    http_response_code(403);
    exit('Access denied. Mail is restricted to administrators.');
}

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception as PHPMailerException;

function mfg_generate_csrf_token() {
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

function mfg_validate_csrf_token($token) {
    return isset($_SESSION['csrf_token']) && is_string($token)
        && hash_equals($_SESSION['csrf_token'], $token);
}

/**
 * Load SMTP settings from the mail_settings table (same source the rest of
 * the app uses) and return a configured PHPMailer instance, or null on error.
 */
function mfg_build_mailer(PDO $pdo) {
    $settings = [];
    foreach ($pdo->query("SELECT setting_key, setting_value FROM mail_settings") as $row) {
        $settings[$row['setting_key']] = $row['setting_value'];
    }
    if (empty($settings['mail_host']) || empty($settings['mail_username'])) {
        return null;
    }

    require_once('../phpmailer/src/PHPMailer.php');
    require_once('../phpmailer/src/SMTP.php');
    require_once('../phpmailer/src/Exception.php');

    $mail = new PHPMailer(true);
    $mail->isSMTP();
    $mail->Host       = $settings['mail_host'];
    $mail->SMTPAuth   = true;
    $mail->Username   = $settings['mail_username'];
    $mail->Password   = $settings['mail_password'] ?? '';
    $mail->SMTPSecure = $settings['mail_encryption'] ?? 'ssl';
    $mail->Port       = (int)($settings['mail_port'] ?? 465);
    $mail->CharSet    = 'UTF-8';
    $mail->setFrom(
        $settings['mail_from_address'] ?? $settings['mail_username'],
        $settings['mail_from_name'] ?? (string)($GLOBALS['site_name'] ?? 'Editor')
    );
    return $mail;
}

/**
 * Personalise a template, send it, and record the outcome.
 */
function mfg_send_to(PHPMailer $mail, array $poet, $subject, $message, array &$sent, array &$unsent) {
    $find    = ['[firstname]', '[lastname]', '[email]'];
    $replace = [$poet['author_name'] ?? '', $poet['author_lastname'] ?? '', $poet['email'] ?? ''];
    $label   = trim(($poet['author_name'] ?? '') . ' ' . ($poet['author_lastname'] ?? ''))
             . ' (' . ($poet['email'] ?? '') . ')';

    try {
        $mail->clearAddresses();
        $mail->addAddress($poet['email'], trim(($poet['author_name'] ?? '') . ' ' . ($poet['author_lastname'] ?? '')));
        $mail->Subject = $subject;
        $mail->msgHTML(nl2br(str_replace($find, $replace, $message)));
        $mail->AltBody = str_replace($find, $replace, $message);
        $mail->send();
        $sent[] = $label;
    } catch (PHPMailerException $e) {
        error_log('mail-center send failed for ' . ($poet['email'] ?? '?') . ': ' . $e->getMessage());
        $unsent[] = $label;
    }
}

$error = '';
$msg   = '';

if (isset($_POST['submit'])) {
    if (!mfg_validate_csrf_token($_POST['csrf_token'] ?? '')) {
        $error = '&nbsp; Invalid request. Please reload and try again. &nbsp;';
    } else {
        $subject = trim((string)($_POST['subject'] ?? ''));
        $message = (string)($_POST['message'] ?? '');
        $to      = (string)($_POST['to'] ?? '');

        if ($subject === '') {
            $error = '&nbsp; You cannot send a message without a subject &nbsp;';
        } elseif (trim($message) === '') {
            $error = '&nbsp; You cannot send a blank message &nbsp;';
        } else {
            $mail = mfg_build_mailer($pdo);
            if ($mail === null) {
                $error = '&nbsp; Mail is not configured. Set SMTP details on the SMTP page first. &nbsp;';
            } else {
                $sent = [];
                $unsent = [];

                if ($to === '0') {
                    // Everyone
                    $stmt = $pdo->query("SELECT id, email, author_name, author_lastname FROM sm_poets WHERE email IS NOT NULL AND email <> ''");
                    foreach ($stmt as $poet) {
                        mfg_send_to($mail, $poet, $subject, $message, $sent, $unsent);
                    }
                } elseif (strpos($to, 'edition-') === 0) {
                    // Poets with an accepted submission in a given edition
                    $editionid = (int)substr($to, strlen('edition-'));
                    $stmt = $pdo->prepare("SELECT DISTINCT poetid FROM sm_submissions WHERE status = 1 AND editionid = :eid");
                    $stmt->bindValue(':eid', $editionid, PDO::PARAM_INT);
                    $stmt->execute();
                    foreach ($stmt->fetchAll(PDO::FETCH_COLUMN, 0) as $pid) {
                        $poet = getPoet((int)$pid);
                        if ($poet && !empty($poet['email'])) {
                            mfg_send_to($mail, $poet, $subject, $message, $sent, $unsent);
                        }
                    }
                } else {
                    // A single poet
                    $poet = getPoet((int)$to);
                    if ($poet && !empty($poet['email'])) {
                        mfg_send_to($mail, $poet, $subject, $message, $sent, $unsent);
                    } else {
                        $error = '&nbsp; That recipient could not be found. &nbsp;';
                    }
                }

                if ($sent) {
                    $msg = '&nbsp; Successfully sent to: ' . implode(', ', $sent) . ' &nbsp;';
                }
                if ($unsent) {
                    $error = '&nbsp; Unable to send to: ' . implode(', ', $unsent) . ' &nbsp;';
                }
            }
        }
    }
}

include_once('header.php');
include_once('editors-menu.php');
?>

<h2>Mail</h2>
<span class="msg"><?php echo $msg; ?></span>
<span class="error"><?php echo $error; ?></span>

<form method="post">
    <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars(mfg_generate_csrf_token(), ENT_QUOTES, 'UTF-8'); ?>">
    <table cellpadding="5" cellspacing="0" border="0">
        <tr>
            <td>Send To:</td>
            <td>
                <select name="to">
                    <option value="0">Everyone</option>
                    <optgroup label="By Edition">
                        <?php
                        $stmt = $pdo->query("SELECT id, edition FROM sm_editions ORDER BY id");
                        foreach ($stmt as $row) {
                            echo '<option value="edition-' . (int)$row['id'] . '">'
                                . htmlspecialchars($row['edition'], ENT_QUOTES, 'UTF-8') . '</option>';
                        }
                        ?>
                    </optgroup>
                    <optgroup label="By Individual Poet">
                        <?php
                        $stmt = $pdo->query("SELECT id, email, author_name, author_lastname FROM sm_poets ORDER BY author_lastname, author_name");
                        foreach ($stmt as $row) {
                            echo '<option value="' . (int)$row['id'] . '">'
                                . htmlspecialchars(ucfirst((string)$row['author_lastname']) . ', ' . ucfirst((string)$row['author_name']) . ' (' . $row['email'] . ')', ENT_QUOTES, 'UTF-8')
                                . '</option>';
                        }
                        ?>
                    </optgroup>
                </select>
            </td>
        </tr>
        <tr>
            <td>Subject:</td>
            <td><input name="subject" size="73" value="<?php echo htmlspecialchars($_POST['subject'] ?? '', ENT_QUOTES, 'UTF-8'); ?>" type="text" required /></td>
        </tr>
        <tr>
            <td valign="top">Message:</td>
            <td>
                <textarea name="message" cols="70" rows="12" required><?php echo htmlspecialchars($_POST['message'] ?? '', ENT_QUOTES, 'UTF-8'); ?></textarea><br />
                <small>You can use these variables in your message: <i>[firstname] [lastname] [email]</i></small>
            </td>
        </tr>
        <tr>
            <td colspan="2" align="center"><input name="submit" value="Send Message" type="submit" /></td>
        </tr>
    </table>
</form>

<?php
include_once('footer.php');
