<?php
require_once __DIR__ . '/../includes/functions.php';
startSecureSession();
requireAdmin();

$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrfVerify();
    $action = $_POST['action'] ?? '';
    $settings = getAdminSettings();

    if ($action === 'save_smtp' || $action === 'test_connection') {
        $updates = [
            'smtp_host' => trim($_POST['smtp_host'] ?? ''),
            'smtp_port' => (int)($_POST['smtp_port'] ?? 587),
            'smtp_user' => trim($_POST['smtp_user'] ?? ''),
            'smtp_encryption' => trim($_POST['smtp_encryption'] ?? 'tls'),
            'smtp_from_email' => trim($_POST['smtp_from_email'] ?? ''),
            'smtp_from_name' => trim($_POST['smtp_from_name'] ?? '')
        ];
        
        $smtpPass = trim($_POST['smtp_pass'] ?? '');
        if ($smtpPass !== '') {
            $updates['smtp_pass_encrypted'] = encryptData($smtpPass);
        }

        updateAdminSettings($updates);
        $settings = getAdminSettings(); // Refresh settings

        if ($action === 'save_smtp') {
            $message = 'SMTP settings saved successfully!';
            $messageType = 'success';
        } else {
            // Test Connection Logic
            require_once __DIR__ . '/../includes/PHPMailer/Exception.php';
            require_once __DIR__ . '/../includes/PHPMailer/PHPMailer.php';
            require_once __DIR__ . '/../includes/PHPMailer/SMTP.php';
            
            $mail = new \PHPMailer\PHPMailer\PHPMailer(true);
            try {
                $mail->isSMTP();
                $mail->Host = $settings['smtp_host'];
                $mail->SMTPAuth = !empty($settings['smtp_user']);
                if ($mail->SMTPAuth) {
                    $mail->Username = $settings['smtp_user'];
                    $mail->Password = decryptData($settings['smtp_pass_encrypted']);
                }
                if (!empty($settings['smtp_encryption']) && strtolower($settings['smtp_encryption']) !== 'none') {
                    $mail->SMTPSecure = strtolower($settings['smtp_encryption']) === 'ssl' ? \PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_SMTPS : \PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS;
                } else {
                    $mail->SMTPAutoTLS = false;
                }
                $mail->Port = $settings['smtp_port'];
                $mail->Timeout = 10;
                
                if ($mail->smtpConnect()) {
                    $mail->smtpClose();
                    $message = 'Connection Successful! Your SMTP settings are working perfectly.';
                    $messageType = 'success';
                } else {
                    $message = 'Connection failed. Please check your host, port, and credentials.';
                    $messageType = 'error';
                }
            } catch (Exception $e) {
                $message = 'Connection failed: ' . $e->getMessage();
                $messageType = 'error';
            }
        }
    } elseif ($action === 'test_smtp') {
        $testEmail = trim($_POST['test_email'] ?? '');
        if (!$testEmail) {
            $message = 'Please provide an email address to send the test email to.';
            $messageType = 'error';
        } else {
            $subject = "SMTP Test - FamGateway";
            $body = "<h2>SMTP Configuration Successful!</h2><p>If you are reading this, your SMTP configuration on FamGateway is working perfectly.</p>";
            if (sendSMTPMail($testEmail, $subject, $body, true)) {
                $message = "Test email sent successfully to $testEmail!";
                $messageType = 'success';
            } else {
                $message = "Failed to send test email. Check your SMTP settings and PHP error logs.";
                $messageType = 'error';
            }
        }
    }
}

$settings = getAdminSettings();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php $pageTitle = "SMTP Settings — Admin Control Panel"; include __DIR__ . '/admin-style.php'; ?>
</head>
<body>
<?php include __DIR__ . '/admin-nav.php'; ?>
    <div class="wrap">

      <div style="margin-bottom:24px;">
        <h1 style="font-size:22px;font-weight:700;color:var(--color-ink);letter-spacing:-0.5px;display:flex;align-items:center;gap:8px;">
          <i data-lucide="mail" style="color:#6366f1;width:24px;height:24px;"></i> SMTP Configuration
        </h1>
        <p style="font-size:13px;color:var(--color-ink-mute);margin-top:4px;">Configure your custom SMTP server for outgoing system emails (Welcome, Password Reset, etc).</p>
      </div>

      <?php if ($message): ?>
        <div class="callout callout-<?= $messageType === 'success' ? 'success' : 'error' ?>" style="margin-bottom:20px;">
          <?= htmlspecialchars($message) ?>
        </div>
      <?php endif; ?>

      <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%, 320px),1fr));gap:20px;">

        <!-- SMTP Settings Card -->
        <div class="card" style="margin-bottom:0;">
          <div class="card-title" style="margin-bottom:6px;"><i data-lucide="server" style="width:18px;height:18px;color:#8b5cf6;"></i> Server Credentials</div>
          <div class="card-sub" style="margin-bottom:20px;">Enter your SMTP provider details (Hostinger, SendGrid, Amazon SES, etc).</div>
          <form method="POST">
            <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
            
            <div class="form-group">
              <label class="form-label">SMTP Host</label>
              <input type="text" name="smtp_host" class="form-input" value="<?= htmlspecialchars($settings['smtp_host']) ?>" placeholder="smtp.hostinger.com">
            </div>
            
            <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%, 150px),1fr));gap:15px;">
              <div>
                <label class="form-label" style="font-size:12px;">Port</label>
                <input type="number" name="smtp_port" class="form-input" value="<?= htmlspecialchars($settings['smtp_port']) ?>" required>
              </div>
              <div>
                <label class="form-label" style="font-size:12px;">Encryption</label>
                <select name="smtp_encryption" class="form-input">
                  <option value="none" <?= strtolower($settings['smtp_encryption']) === 'none' ? 'selected' : '' ?>>None</option>
                  <option value="tls" <?= strtolower($settings['smtp_encryption']) === 'tls' ? 'selected' : '' ?>>TLS / STARTTLS</option>
                  <option value="ssl" <?= strtolower($settings['smtp_encryption']) === 'ssl' ? 'selected' : '' ?>>SSL</option>
                </select>
              </div>
            </div>

            <div class="form-group">
              <label class="form-label">SMTP Username (Email)</label>
              <input type="text" name="smtp_user" class="form-input" value="<?= htmlspecialchars($settings['smtp_user']) ?>" placeholder="no-reply@yourdomain.com">
            </div>
            <div class="form-group">
              <label class="form-label">SMTP Password <span style="font-weight:400;color:var(--color-ink-mute);"><?= $settings['smtp_pass_encrypted'] ? '(blank = keep current)' : '' ?></span></label>
              <input type="password" name="smtp_pass" class="form-input" placeholder="<?= $settings['smtp_pass_encrypted'] ? '••••••••••••••••' : 'Your Email Password' ?>">
            </div>
            
            <hr style="border:0;border-top:1px solid #eaeaea;margin:20px 0;">
            
            <div class="form-group">
              <label class="form-label">Sender Email (From)</label>
              <input type="email" name="smtp_from_email" class="form-input" value="<?= htmlspecialchars($settings['smtp_from_email']) ?>" placeholder="no-reply@yourdomain.com">
            </div>
            <div class="form-group">
              <label class="form-label">Sender Name (From Name)</label>
              <input type="text" name="smtp_from_name" class="form-input" value="<?= htmlspecialchars($settings['smtp_from_name']) ?>" placeholder="FamGateway">
            </div>

            <div style="display:flex; gap:10px; margin-top:4px;">
                <button type="submit" name="action" value="save_smtp" class="btn btn-primary" style="flex:1;"><i data-lucide="save" style="width:15px;height:15px;"></i> Save Config</button>
                <button type="submit" name="action" value="test_connection" class="btn btn-secondary" style="flex:1;background:#f3f4f6;color:#374151;border:1px solid #d1d5db;"><i data-lucide="zap" style="width:15px;height:15px;color:#f59e0b;"></i> Test Connection</button>
            </div>
          </form>
        </div>

        <!-- Right column: Test SMTP -->
        <div style="display:flex;flex-direction:column;gap:20px;">
          <div class="card" style="margin-bottom:0;">
            <div class="card-title" style="margin-bottom:6px;"><i data-lucide="send" style="width:18px;height:18px;color:#10b981;"></i> Send Test Email</div>
            <div class="card-sub" style="margin-bottom:18px;">Send a test email to verify your settings before making them live. Save settings first!</div>
            <form method="POST">
              <input type="hidden" name="action" value="test_smtp">
              <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
              <div class="form-group">
                <label class="form-label">Recipient Email</label>
                <input type="email" name="test_email" class="form-input" placeholder="you@gmail.com" required>
              </div>
              <button type="submit" class="btn btn-secondary" style="width:100%;"><i data-lucide="mail-check" style="width:15px;height:15px;"></i> Send Test Mail</button>
            </form>
            <?php if (!empty($settings['smtp_host'])): ?>
              <div style="font-size:12px;color:var(--color-success-text);margin-top:12px;font-weight:600;">✓ Configured: <?= htmlspecialchars($settings['smtp_host']) ?></div>
            <?php else: ?>
              <div style="font-size:12px;color:var(--color-ink-mute);margin-top:12px;">SMTP is currently disabled (using default PHP mailer).</div>
            <?php endif; ?>
          </div>
        </div>

      </div>
    </div>
  </main>
</div>
<script>if (window.lucide) { lucide.createIcons(); }</script>
</body>
</html>
