<?php
session_start();
date_default_timezone_set('Africa/Lagos');
require __DIR__ . '/../config.php';
require __DIR__ . '/includes/auth_init.php';

if (!$isAdmin) {
    $_SESSION['flash_error'] = "You don't have permission to configure email settings.";
    header("Location: dashboard.php");
    exit;
}

// Release the session lock on plain page views; the POST branch below still
// needs to write flash data, so it keeps the session open for itself.
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    session_write_close();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_email'])) {
    $host = trim($_POST['smtp_host']);
    $port = (int) $_POST['smtp_port'];
    $user = trim($_POST['smtp_username']);
    $pass = trim($_POST['smtp_password']);
    $fromEmail = trim($_POST['from_email']);
    $fromName = trim($_POST['from_name']);
    $encryption = $_POST['encryption'];

    $existing = $conn->query("SELECT id FROM email_settings ORDER BY id DESC LIMIT 1")->fetch_assoc();
    if ($existing) {
        $stmt = $conn->prepare("UPDATE email_settings SET smtp_host=?, smtp_port=?, smtp_username=?, smtp_password=?, from_email=?, from_name=?, encryption=? WHERE id=?");
        $stmt->bind_param('sisssssi', $host, $port, $user, $pass, $fromEmail, $fromName, $encryption, $existing['id']);
    } else {
        $stmt = $conn->prepare("INSERT INTO email_settings (smtp_host, smtp_port, smtp_username, smtp_password, from_email, from_name, encryption) VALUES (?,?,?,?,?,?,?)");
        $stmt->bind_param('sisssss', $host, $port, $user, $pass, $fromEmail, $fromName, $encryption);
    }
    $stmt->execute();
    $stmt->close();
    $_SESSION['flash_success'] = "Email settings saved.";
    header("Location: email_settings.php");
    exit;
}

$settings = $conn->query("SELECT * FROM email_settings ORDER BY id DESC LIMIT 1")->fetch_assoc();

$pageTitle = 'Email (Mailtrap) Settings';
$pageSubtitle = 'Payroll Module';
require __DIR__ . '/includes/layout_header.php';
?>

<div class="bg-white border border-slate-200/80 rounded-xl p-4 shadow-xs max-w-2xl">
    <h3 class="text-xs font-black text-slate-900 uppercase tracking-tight mb-1">Mailtrap SMTP Settings</h3>
    <p class="text-[11px] text-slate-500 font-semibold mb-4">
        Get these from your Mailtrap inbox &rarr; "SMTP Settings". Use your Sending domain credentials for live delivery, or your sandbox inbox for testing.
        This also requires <code class="bg-slate-100 px-1 rounded">composer require phpmailer/phpmailer</code> in your app root.
    </p>
    <form method="POST" class="space-y-4">
        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <div>
                <label class="text-[10px] font-black text-slate-400 uppercase tracking-wider">SMTP Host</label>
                <input type="text" name="smtp_host" value="<?= h($settings['smtp_host'] ?? 'sandbox.smtp.mailtrap.io'); ?>" class="mt-1 w-full text-sm border border-slate-200 rounded-lg p-3">
            </div>
            <div>
                <label class="text-[10px] font-black text-slate-400 uppercase tracking-wider">SMTP Port</label>
                <input type="number" name="smtp_port" value="<?= h($settings['smtp_port'] ?? 587); ?>" class="mt-1 w-full text-sm border border-slate-200 rounded-lg p-3">
            </div>
            <div>
                <label class="text-[10px] font-black text-slate-400 uppercase tracking-wider">SMTP Username</label>
                <input type="text" name="smtp_username" value="<?= h($settings['smtp_username'] ?? ''); ?>" class="mt-1 w-full text-sm border border-slate-200 rounded-lg p-3">
            </div>
            <div>
                <label class="text-[10px] font-black text-slate-400 uppercase tracking-wider">SMTP Password</label>
                <input type="password" name="smtp_password" value="<?= h($settings['smtp_password'] ?? ''); ?>" class="mt-1 w-full text-sm border border-slate-200 rounded-lg p-3">
            </div>
            <div>
                <label class="text-[10px] font-black text-slate-400 uppercase tracking-wider">From Email</label>
                <input type="email" name="from_email" value="<?= h($settings['from_email'] ?? ''); ?>" class="mt-1 w-full text-sm border border-slate-200 rounded-lg p-3">
            </div>
            <div>
                <label class="text-[10px] font-black text-slate-400 uppercase tracking-wider">From Name</label>
                <input type="text" name="from_name" value="<?= h($settings['from_name'] ?? 'HR Payroll'); ?>" class="mt-1 w-full text-sm border border-slate-200 rounded-lg p-3">
            </div>
            <div>
                <label class="text-[10px] font-black text-slate-400 uppercase tracking-wider">Encryption</label>
                <select name="encryption" class="mt-1 w-full text-sm border border-slate-200 rounded-lg p-3">
                    <option value="tls" <?= ($settings['encryption'] ?? '') === 'tls' ? 'selected' : ''; ?>>TLS (STARTTLS)</option>
                    <option value="ssl" <?= ($settings['encryption'] ?? '') === 'ssl' ? 'selected' : ''; ?>>SSL</option>
                </select>
            </div>
        </div>
        <button type="submit" name="save_email" class="bg-indigo-600 hover:bg-indigo-700 text-white text-xs font-black uppercase tracking-wider px-5 py-2.5 rounded-lg transition active:scale-95 border border-indigo-700">
            Save Email Settings
        </button>
    </form>
</div>

<?php require __DIR__ . '/includes/layout_footer.php'; ?>
