<?php
require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../includes/functions.php';
startSession(); requireLogin(); requireRole('superadmin', 'admin');
$db   = Database::getInstance();
$page = 'Email Settings';

// smtp_settings is a single shared row (like company_settings) used for
// every outgoing email the app sends — right now that's Payroll → Send
// Payslip by Email, but any future "email this" feature reuses the same
// config. See migration_smtp_settings.sql.
$settings = null;
$migrationMissing = false;
try {
    $settings = $db->fetchOne("SELECT * FROM smtp_settings ORDER BY id DESC LIMIT 1");
} catch (Throwable $e) {
    $migrationMissing = true;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !$migrationMissing) {
    verifyCsrf();
    $data = [
        'host'       => post('host'),
        'port'       => cleanInt(post('port')) ?: 587,
        'username'   => post('username'),
        'encryption' => in_array(post('encryption'), ['tls','ssl','none']) ? post('encryption') : 'tls',
        'from_email' => post('from_email'),
        'from_name'  => post('from_name') ?: 'HR Team',
    ];
    // Only overwrite the stored password if a new one was actually typed
    // — otherwise leaving it blank on every edit would wipe it out.
    if (post('password') !== '') {
        $data['password'] = post('password');
    }

    if ($settings) {
        $db->updateRow('smtp_settings', $data, $settings['id']);
    } else {
        $data['password'] = post('password'); // required on first save
        $db->insertRow('smtp_settings', $data);
    }
    setFlash('success', 'Email settings saved.');
    header('Location: ' . BASE_URL . '/modules/company/email_settings.php'); exit;
}

// "Send test email" — quick way to confirm the SMTP details actually
// work before relying on them for real payslip emails.
if (isset($_GET['test']) && !$migrationMissing) {
    require_once __DIR__ . '/../../includes/mailer.php';
    $me = currentUser();
    $meEmail = $db->fetchValue(
        "SELECT COALESCE(official_email, personal_email) FROM employees WHERE id=?",
        [$me['emp_id']]
    );
    if (!$meEmail) {
        setFlash('error', 'No email on file for your own account to send the test to.');
    } else {
        $result = sendAppEmail($meEmail, $me['name'], 'Seyalix HRMS — Test Email', '<p>This is a test email from your Seyalix HRMS Email Settings page. If you got this, SMTP is working correctly.</p>');
        setFlash($result['ok'] ? 'success' : 'error', $result['ok'] ? "Test email sent to $meEmail." : ('Test failed: ' . $result['error']));
    }
    header('Location: ' . BASE_URL . '/modules/company/email_settings.php'); exit;
}

include __DIR__ . '/../../includes/header.php';
?>
<div class="row g-3">
  <div class="col-md-7">
    <div class="pc-card">
      <div class="pc-card-title"><i class="ti ti-mail me-2"></i>Outgoing Email (SMTP)</div>
      <p class="text-muted small mb-3">Used to send payslips by email (Payroll → Send Payslip by Email) and any future email features. Works with Gmail, Outlook, or your own mail server's SMTP.</p>

      <?php if ($migrationMissing): ?>
        <div class="alert alert-warning">
          <strong>One-time setup needed.</strong> Run <code>migration_smtp_settings.sql</code>
          (phpMyAdmin → SQL tab → paste the file → Go), then reload this page.
        </div>
      <?php else: ?>
        <form method="POST">
          <?= csrfField() ?>
          <div class="row g-2">
            <div class="col-md-8"><label class="pc-label">SMTP Host <span class="text-danger">*</span></label>
              <input type="text" name="host" class="form-control form-control-sm" placeholder="smtp.gmail.com" value="<?= clean($settings['host'] ?? '') ?>" required></div>
            <div class="col-md-4"><label class="pc-label">Port <span class="text-danger">*</span></label>
              <input type="number" name="port" class="form-control form-control-sm" value="<?= clean($settings['port'] ?? '587') ?>" required></div>

            <div class="col-md-6"><label class="pc-label">Username / Email <span class="text-danger">*</span></label>
              <input type="text" name="username" class="form-control form-control-sm" value="<?= clean($settings['username'] ?? '') ?>" required></div>
            <div class="col-md-6"><label class="pc-label">Password <?= $settings ? '' : '<span class="text-danger">*</span>' ?></label>
              <input type="password" name="password" class="form-control form-control-sm" placeholder="<?= $settings ? 'Leave blank to keep current password' : 'App password (not your login password)' ?>" <?= $settings ? '' : 'required' ?>></div>

            <div class="col-md-4"><label class="pc-label">Encryption</label>
              <select name="encryption" class="form-select form-select-sm">
                <?php foreach (['tls'=>'TLS (recommended)','ssl'=>'SSL','none'=>'None'] as $v=>$l): ?>
                <option value="<?= $v ?>" <?= ($settings['encryption']??'tls')===$v?'selected':'' ?>><?= $l ?></option>
                <?php endforeach; ?>
              </select></div>
            <div class="col-md-4"><label class="pc-label">From Name</label>
              <input type="text" name="from_name" class="form-control form-control-sm" value="<?= clean($settings['from_name'] ?? 'HR Team') ?>"></div>
            <div class="col-md-4"><label class="pc-label">From Email <span class="text-danger">*</span></label>
              <input type="email" name="from_email" class="form-control form-control-sm" value="<?= clean($settings['from_email'] ?? '') ?>" required></div>
          </div>
          <div class="mt-3 d-flex gap-2">
            <button class="btn btn-pc"><i class="ti ti-device-floppy me-1"></i>Save</button>
            <?php if ($settings): ?>
              <a href="?test=1" class="btn btn-outline-secondary btn-sm"><i class="ti ti-send me-1"></i>Send Test Email</a>
            <?php endif; ?>
          </div>
        </form>
      <?php endif; ?>
    </div>
  </div>

  <div class="col-md-5">
    <div class="pc-card">
      <div class="pc-card-title"><i class="ti ti-info-circle me-2"></i>Gmail Quick Setup</div>
      <ol class="small text-muted ps-3 mb-0">
        <li>Host: <code>smtp.gmail.com</code>, Port: <code>587</code>, Encryption: TLS</li>
        <li>Username: your full Gmail address</li>
        <li>Password: an <strong>App Password</strong>, not your normal Gmail password —
          Google Account → Security → 2-Step Verification (turn on) → App Passwords → generate one for "Mail"</li>
        <li>From Email: same Gmail address (Gmail rejects a different "From")</li>
      </ol>
    </div>
  </div>
</div>
<?php include __DIR__ . '/../../includes/footer.php'; ?>
