<?php

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

// Restrict to admin / superadmin BEFORE emitting any HTML (mail credentials are sensitive).
if (!in_array($_SESSION['editor_type'] ?? '', ['admin', 'superadmin'], true)) {
    http_response_code(403);
    exit('Access denied. Mail Settings is restricted to administrators.');
}

// CSRF token for the forms on this page.
if (empty($_SESSION['token'])) {
    $_SESSION['token'] = bin2hex(random_bytes(32));
}

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

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

// Include the header and editors menu (after the auth gate).
include_once('header.php');
include_once('editors-menu.php');

// Fetch current mail settings using PDO (db() comes from functions.php via common.php)
function fetch_mail_settings() {
    $pdo = db();
    $stmt = $pdo->query("SELECT setting_key, setting_value FROM mail_settings");
    $settings = [];
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $settings[$row['setting_key']] = $row['setting_value'];
    }
    return $settings;
}

// Update mail settings form submission
if (isset($_POST['save_mail_settings'])) {
    if (!isset($_POST['token']) || !hash_equals($_SESSION['token'], (string)$_POST['token'])) {
        $error = 'Invalid request. Please reload and try again.';
    } else {
        $pdo = db();
        // Store values verbatim — SMTP passwords/hosts must NOT be HTML-encoded.
        foreach (($_POST['settings'] ?? []) as $key => $value) {
            $stmt = $pdo->prepare("UPDATE mail_settings SET setting_value = :value WHERE setting_key = :key");
            $stmt->bindValue(':value', (string)$value);
            $stmt->bindValue(':key', (string)$key);
            $stmt->execute();
        }
        $msg = "Mail settings successfully updated.";
    }
}

// Test sending email form submission
if (isset($_POST['send_test_email']) && isset($_POST['token']) && hash_equals($_SESSION['token'], (string)$_POST['token'])) {
    $mail_settings = fetch_mail_settings();
    $test_email = filter_var($_POST['test_email'], FILTER_VALIDATE_EMAIL); // Validate entered email

    if ($test_email) {
        $mail = new PHPMailer(true);
        try {
            // Server settings
            $mail->isSMTP();
            $mail->Host = $mail_settings['mail_host'];
            $mail->SMTPAuth = true;
            $mail->Username = $mail_settings['mail_username'];
            $mail->Password = $mail_settings['mail_password'];
            $mail->SMTPSecure = $mail_settings['mail_encryption'] ?? 'ssl';
            $mail->Port = $mail_settings['mail_port'];

            // Recipients
            $mail->setFrom($mail_settings['mail_from_address'], $mail_settings['mail_from_name']);
            $mail->addAddress($test_email); // Use the admin-entered test email

            // Email content
            $mail->isHTML(true);
            $mail->Subject = 'Test Email from Mail Settings';
            $mail->Body = 'This is a test email to verify the SMTP configuration.';

            // Attempt to send the email
            $mail->send();
            $msg = "Test email has been sent successfully to $test_email.";
        } catch (Exception $e) {
            $error = "Test email could not be sent. Mailer Error: {$mail->ErrorInfo}";
        }
    } else {
        $error = "Invalid email address. Please enter a valid email.";
    }
}

// Get the current settings for display
$current_settings = fetch_mail_settings();

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Superadmin - Mail Settings</title>
    <link rel="stylesheet" href="../styles.css">
    <style>
        body {
            font-family: Arial, sans-serif;
        }

        .content-wrapper {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f9f9f9;
            border-radius: 10px;
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
        }

        h2 {
            text-align: center;
            font-size: 28px;
            margin-bottom: 20px;
        }

        .msg {
            text-align: center;
            font-size: 18px;
            color: #28a745;
            margin: 15px 0;
        }

        .error-msg {
            text-align: center;
            font-size: 18px;
            color: #dc3545;
            margin: 15px 0;
        }

        .gridtable {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }

        .gridtable th, .gridtable td {
            text-align: left;
            padding: 12px;
            border: 1px solid #ddd;
        }

        .gridtable th {
            background-color: #007bff;
            color: white;
        }

        .gridtable td {
            background-color: #f9f9f9;
        }

        .gridtable td input {
            width: 100%;
            padding: 8px;
            font-size: 16px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }

        .button-primary, .button-secondary {
            display: block;
            width: 100%;
            padding: 10px;
            font-size: 18px;
            background-color: #28a745;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            text-align: center;
            margin-bottom: 15px;
        }

        .button-secondary {
            background-color: #007bff;
        }

        .button-primary:hover, .button-secondary:hover {
            background-color: #218838;
        }

        @media screen and (max-width: 768px) {
            .gridtable th, .gridtable td {
                font-size: 14px;
            }
            .button-primary {
                font-size: 16px;
            }
        }
    </style>
</head>
<body>

<div class="content-wrapper">
    <h2>Mail Settings</h2>

    <!-- Display message after saving or error -->
    <?php if (isset($msg)) { echo "<p class='msg'>$msg</p>"; } ?>
    <?php if (isset($error)) { echo "<p class='error-msg'>$error</p>"; } ?>

    <!-- Mail Settings Form -->
    <form method="post">
        <input type="hidden" name="token" value="<?= htmlspecialchars($_SESSION['token'], ENT_QUOTES, 'UTF-8') ?>">
        <table class="gridtable">
            <tr>
                <th>Setting</th>
                <th>Value</th>
            </tr>
            <tr>
                <td>SMTP Host</td>
                <td><input type="text" name="settings[mail_host]" value="<?= htmlspecialchars($current_settings['mail_host'], ENT_QUOTES, 'UTF-8') ?>" /></td>
            </tr>
            <tr>
                <td>SMTP Port</td>
                <td><input type="text" name="settings[mail_port]" value="<?= htmlspecialchars($current_settings['mail_port'], ENT_QUOTES, 'UTF-8') ?>" /></td>
            </tr>
            <tr>
                <td>SMTP Username</td>
                <td><input type="text" name="settings[mail_username]" value="<?= htmlspecialchars($current_settings['mail_username'], ENT_QUOTES, 'UTF-8') ?>" /></td>
            </tr>
            <tr>
                <td>SMTP Password</td>
                <td><input type="password" name="settings[mail_password]" value="<?= htmlspecialchars($current_settings['mail_password'], ENT_QUOTES, 'UTF-8') ?>" /></td>
            </tr>
            <tr>
                <td>From Address</td>
                <td><input type="text" name="settings[mail_from_address]" value="<?= htmlspecialchars($current_settings['mail_from_address'], ENT_QUOTES, 'UTF-8') ?>" /></td>
            </tr>
            <tr>
                <td>From Name</td>
                <td><input type="text" name="settings[mail_from_name]" value="<?= htmlspecialchars($current_settings['mail_from_name'], ENT_QUOTES, 'UTF-8') ?>" /></td>
            </tr>
        </table>

        <input type="submit" name="save_mail_settings" value="Save Mail Settings" class="button-primary" />
    </form>

    <!-- Separate Section for Test Email -->
    <h2>Send Test Email</h2>
    <p>This will send a test email using the current SMTP settings to ensure they are working correctly.</p>
    
    <!-- Send Test Email Form -->
    <form method="post">
        <input type="hidden" name="token" value="<?= htmlspecialchars($_SESSION['token'], ENT_QUOTES, 'UTF-8') ?>">
        <label for="test_email">Enter test email address:</label>
        <input type="email" name="test_email" id="test_email" required placeholder="example@example.com" class="gridtable td input" />
        <input type="submit" name="send_test_email" value="Send Test Email" class="button-secondary" />
    </form>
</div>

<!-- Include the footer at the bottom -->
<?php
include_once('footer.php');
?>

</body>
</html>
