<?php
/**
 * Agentic Square - Premium SMTP Configuration Control Console
 * Path: admin/email-setting.php
 */

require_once __DIR__ . '/../config/config.php';

// SECURITY ACCESS GUARD: Strictly restrict structural modifications to verified administrators
if (!isset($_SESSION['user_id']) || !isset($_SESSION['user_role']) || $_SESSION['user_role'] !== 'admin') {
    header('Location: ../login.php');
    exit;
}

$success_message = '';
$error_message   = '';

// Handle Configuration Matrix Updates
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $smtp_host     = filter_var(trim($_POST['smtp_host'] ?? ''), FILTER_SANITIZE_SPECIAL_CHARS);
    $smtp_auth     = isset($_POST['smtp_auth']) ? (int)$_POST['smtp_auth'] : 1;
    $smtp_username = filter_var(trim($_POST['smtp_username'] ?? ''), FILTER_SANITIZE_SPECIAL_CHARS);
    $smtp_password = trim($_POST['smtp_password'] ?? ''); // Preserve original tracking characters safely
    $smtp_secure   = in_array($_POST['smtp_secure'] ?? '', ['none', 'ssl', 'tls']) ? $_POST['smtp_secure'] : 'tls';
    $smtp_port     = filter_var($_POST['smtp_port'] ?? 587, FILTER_VALIDATE_INT);
    $from_email    = filter_var(trim($_POST['from_email'] ?? ''), FILTER_SANITIZE_EMAIL);
    $from_name     = filter_var(trim($_POST['from_name'] ?? ''), FILTER_SANITIZE_SPECIAL_CHARS);

    if (empty($smtp_host) || empty($from_email)) {
        $error_message = "Operational failure: Server architecture requires a valid SMTP host and Outbound Origin Address.";
    } else {
        try {
            $updateQuery = "UPDATE smtp_settings SET 
                smtp_host = :smtp_host,
                smtp_auth = :smtp_auth,
                smtp_username = :smtp_username,
                smtp_password = :smtp_password,
                smtp_secure = :smtp_secure,
                smtp_port = :smtp_port,
                from_email = :from_email,
                from_name = :from_name
                WHERE id = 1";
            
            $stmt = $pdo->prepare($updateQuery);
            $stmt->execute([
                'smtp_host'     => $smtp_host,
                'smtp_auth'     => $smtp_auth,
                'smtp_username' => $smtp_username,
                'smtp_password' => $smtp_password,
                'smtp_secure'   => $smtp_secure,
                'smtp_port'     => $smtp_port,
                'from_email'    => $from_email,
                'from_name'     => $from_name
            ]);
            
            $success_message = "Global transactional email matrices reorganized successfully.";
        } catch (\PDOException $e) {
            $error_message = "Database Pipeline Error: " . $e->getMessage();
        }
    }
}

// Fetch current setting row sequence mapping
$settings = $pdo->query("SELECT * FROM smtp_settings WHERE id = 1 LIMIT 1")->fetch(PDO::FETCH_ASSOC);

require_once __DIR__ . '/../sections/header.php';
?>

<body class="bg-nftDark text-white antialiased overflow-x-hidden">
    <?php require_once __DIR__ . '/admin-sidebar.php'; ?>

    <main class="lg:ml-64 min-h-screen pt-24 lg:pt-10 pb-16 px-4 sm:px-6 lg:px-8">
        <div class="max-w-4xl mx-auto space-y-8">
            <div class="border-b border-slate-900/60 pb-6">
                <span class="text-xs font-bold tracking-widest text-nftAccentCyan uppercase block mb-1">// Automation Infrastructure</span>
                <h1 class="text-3xl font-extrabold tracking-tight text-white">SMTP Communications Hub</h1>
                <p class="text-sm text-nftTextGray mt-1">Configure global operational parameters governing transactional delivery routes and PHPMailer authentication protocols.</p>
            </div>

            <?php if ($success_message): ?>
                <div class="bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 p-4 rounded-xl text-xs font-mono">
                    <?= $success_message ?>
                </div>
            <?php endif; ?>

            <?php if ($error_message): ?>
                <div class="bg-rose-500/10 border border-rose-500/20 text-rose-400 p-4 rounded-xl text-xs font-mono">
                    <?= $error_message ?>
                </div>
            <?php endif; ?>

            <form action="email-setting.php" method="POST" class="space-y-6">
                <div class="glass-card p-6 rounded-2xl border border-slate-800/80 bg-slate-950/20 space-y-6">
                    <h2 class="text-sm font-bold text-nftAccentCyan uppercase tracking-wider border-b border-slate-900 pb-3">// Gateway Access Variables</h2>
                    
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div class="space-y-2">
                            <label class="text-xs font-bold uppercase text-nftTextGray">Relay Host Address (SMTP Server)</label>
                            <input type="text" name="smtp_host" required value="<?= htmlspecialchars($settings['smtp_host'] ?? '') ?>" placeholder="e.g., smtp.mailgun.org" class="w-full bg-slate-950 border border-slate-800 focus:border-nftAccentCyan rounded-xl px-4 py-3 text-sm text-white placeholder-slate-600 focus:outline-none transition-all">
                        </div>
                        <div class="space-y-2">
                            <label class="text-xs font-bold uppercase text-nftTextGray">Authentication Mode</label>
                            <select name="smtp_auth" class="w-full bg-slate-950 border border-slate-800 focus:border-nftAccentCyan rounded-xl px-4 py-3 text-sm text-white focus:outline-none transition-all">
                                <option value="1" <?= ($settings['smtp_auth'] ?? 1) == 1 ? 'selected' : '' ?>>Enabled (Required for security protocols)</option>
                                <option value="0" <?= ($settings['smtp_auth'] ?? 1) == 0 ? 'selected' : '' ?>>Disabled (Unauthenticated transmission)</option>
                            </select>
                        </div>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div class="space-y-2">
                            <label class="text-xs font-bold uppercase text-nftTextGray">Server Access User Name</label>
                            <input type="text" name="smtp_username" value="<?= htmlspecialchars($settings['smtp_username'] ?? '') ?>" placeholder="system-auth@domain.com" class="w-full bg-slate-950 border border-slate-800 focus:border-nftAccentCyan rounded-xl px-4 py-3 text-sm text-white placeholder-slate-600 focus:outline-none transition-all">
                        </div>
                        <div class="space-y-2">
                            <label class="text-xs font-bold uppercase text-nftTextGray">Server Security Passphrase</label>
                            <input type="password" name="smtp_password" value="<?= htmlspecialchars($settings['smtp_password'] ?? '') ?>" placeholder="••••••••••••" class="w-full bg-slate-950 border border-slate-800 focus:border-nftAccentCyan rounded-xl px-4 py-3 text-sm text-white placeholder-slate-600 focus:outline-none transition-all">
                        </div>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div class="space-y-2">
                            <label class="text-xs font-bold uppercase text-nftTextGray">Transport Layer Security (Encryption)</label>
                            <select name="smtp_secure" class="w-full bg-slate-950 border border-slate-800 focus:border-nftAccentCyan rounded-xl px-4 py-3 text-sm text-white focus:outline-none transition-all">
                                <option value="none" <?= ($settings['smtp_secure'] ?? '') === 'none' ? 'selected' : '' ?>>None (Plain-text)</option>
                                <option value="ssl" <?= ($settings['smtp_secure'] ?? '') === 'ssl' ? 'selected' : '' ?>>SSL (Implicit connection protocol)</option>
                                <option value="tls" <?= ($settings['smtp_secure'] ?? '') === 'tls' ? 'selected' : '' ?>>TLS / STARTTLS (Explicit encryption)</option>
                            </select>
                        </div>
                        <div class="space-y-2">
                            <label class="text-xs font-bold uppercase text-nftTextGray">Connection Port Identifier</label>
                            <input type="number" name="smtp_port" required value="<?= htmlspecialchars($settings['smtp_port'] ?? 587) ?>" placeholder="587" class="w-full bg-slate-950 border border-slate-800 focus:border-nftAccentCyan rounded-xl px-4 py-3 text-sm text-white placeholder-slate-600 focus:outline-none transition-all">
                        </div>
                    </div>
                </div>

                <div class="glass-card p-6 rounded-2xl border border-slate-800/80 bg-slate-950/20 space-y-6">
                    <h2 class="text-sm font-bold text-nftAccentPurple uppercase tracking-wider border-b border-slate-900 pb-3">// Outbound Sender Signature</h2>
                    
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div class="space-y-2">
                            <label class="text-xs font-bold uppercase text-nftTextGray">Outbound Distribution Address (From Email)</label>
                            <input type="email" name="from_email" required value="<?= htmlspecialchars($settings['from_email'] ?? '') ?>" placeholder="no-reply@yourdomain.com" class="w-full bg-slate-950 border border-slate-800 focus:border-nftAccentCyan rounded-xl px-4 py-3 text-sm text-white placeholder-slate-600 focus:outline-none transition-all">
                        </div>
                        <div class="space-y-2">
                            <label class="text-xs font-bold uppercase text-nftTextGray">Outbound Mask Label (From Name)</label>
                            <input type="text" name="from_name" required value="<?= htmlspecialchars($settings['from_name'] ?? '') ?>" placeholder="Agentic Square Engine" class="w-full bg-slate-950 border border-slate-800 focus:border-nftAccentCyan rounded-xl px-4 py-3 text-sm text-white placeholder-slate-600 focus:outline-none transition-all">
                        </div>
                    </div>
                </div>

                <div class="flex justify-end pt-2">
                    <button type="submit" class="px-8 py-4 rounded-xl bg-gradient-to-r from-nftAccentCyan to-nftAccentPurple font-bold text-xs text-white uppercase tracking-widest hover:opacity-90 transition-all shadow-lg shadow-nftAccentCyan/10">
                        Synchronize Mail Engine
                    </button>
                </div>
            </form>
        </div>
    </main>
</body>
</html>