<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
// Traitement du test SMTP : doit être tout en haut pour garantir une réponse JSON
if (isset($_GET['test']) && $_SERVER['REQUEST_METHOD'] === 'POST') {
  ini_set('display_errors', 1);
  ini_set('display_startup_errors', 1);
  error_reporting(E_ALL);
  set_error_handler(function($errno, $errstr, $errfile, $errline) {
    echo json_encode(['success'=>false,'message'=>'Erreur PHP: ' . $errstr . ' in ' . $errfile . ' line ' . $errline]);
    exit;
  });
  register_shutdown_function(function() {
    $error = error_get_last();
    if ($error && ($error['type'] === E_ERROR || $error['type'] === E_PARSE)) {
      echo json_encode(['success'=>false,'message'=>'Fatal error: ' . $error['message'] . ' in ' . $error['file'] . ' line ' . $error['line']]);
      exit;
    }
  });
  require_once '../config/config.php';
  require_once '../config/db.php';
  require_once __DIR__ . '/../phpmailer/src/PHPMailer.php';
  require_once __DIR__ . '/../phpmailer/src/SMTP.php';
  require_once __DIR__ . '/../phpmailer/src/Exception.php';
  $db = getDbConnection();
  $row = $db->query('SELECT * FROM smtp_config WHERE id=1')->fetch(PDO::FETCH_ASSOC);
  if (!$row) {
    echo json_encode(['success'=>false,'message'=>'Configuration SMTP introuvable']);
    exit;
  }
  if (empty($row['statut']) || $row['statut'] == '0') {
    echo json_encode(['success'=>false,'message'=>'SMTP désactivé dans la configuration.']);
    exit;
  }
  $mail = new PHPMailer(true);
  try {
    $mail->isSMTP();
    $mail->Host = $row['smtp_host'];
    $mail->Port = (int)$row['smtp_port'];
    $mail->SMTPAuth = true;
    $mail->Username = $row['smtp_user'];
    $mail->Password = $row['smtp_pass'];
    $mail->CharSet = 'UTF-8';
    $mail->setFrom($row['smtp_from'], $row['smtp_from_name'] ?? 'SERVICES-AE');
    $mail->addAddress($row['email_admin']);
    if (!empty($row['email_cc1'])) $mail->addCC($row['email_cc1']);
    if (!empty($row['email_cc2'])) $mail->addCC($row['email_cc2']);
    $mail->Subject = 'Test SMTP depuis le panel admin';
    $mail->Body = "Ceci est un test d'envoi SMTP depuis la configuration admin SERVICES-AE.";
    // Chiffrement
    if ($row['smtp_ssl'] === 'ssl') $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
    elseif ($row['smtp_ssl'] === 'tls') $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    else $mail->SMTPSecure = false;
    $mail->SMTPOptions = [
      'ssl' => [
        'verify_peer' => false,
        'verify_peer_name' => false,
        'allow_self_signed' => true
      ]
    ];
    $mail->send();
    echo json_encode(['success'=>true,'message'=>'Email envoyé à ' . $row['email_admin']]);
  } catch (Exception $e) {
    echo json_encode(['success'=>false,'message'=>'Erreur PHPMailer: ' . $mail->ErrorInfo]);
  }
  exit;
}
require_once '../config/config.php';
require_once '../config/db.php';
require_once 'auth-check.php';
$page_title = 'Configuration SMTP & Emails';
$current_page = 'smtp-config';

// Traitement du formulaire
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $fields = [
    'smtp_host', 'smtp_port', 'smtp_user', 'smtp_pass', 'smtp_from', 'smtp_from_name',
    'email_admin', 'email_cc1', 'email_cc2', 'smtp_ssl', 'statut', 'enabled_chat'
  ];
    $data = [];
    foreach ($fields as $f) {
        $data[$f] = trim($_POST[$f] ?? '');
    }
    $db = getDbConnection();
    $exists = $db->query('SELECT COUNT(*) FROM smtp_config')->fetchColumn();
    if ($exists) {
        $sql = "UPDATE smtp_config SET smtp_host=?, smtp_port=?, smtp_user=?, smtp_pass=?, smtp_from=?, smtp_from_name=?, email_admin=?, email_cc1=?, email_cc2=?, smtp_ssl=?, statut=?, enabled_chat=? WHERE id=1";
        $db->prepare($sql)->execute(array_values($data));
    } else {
        $sql = "INSERT INTO smtp_config (smtp_host, smtp_port, smtp_user, smtp_pass, smtp_from, smtp_from_name, email_admin, email_cc1, email_cc2, smtp_ssl, statut, enabled_chat) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)";
        $db->prepare($sql)->execute(array_values($data));
    }
    $success_message = 'Configuration enregistrée avec succès !';
}
// Charger la config existante
$db = getDbConnection();
$row = $db->query('SELECT * FROM smtp_config WHERE id=1')->fetch(PDO::FETCH_ASSOC);
if ($row) {
    foreach ($row as $k => $v) {
        ${$k} = $v;
    }
}

ob_start();
?>
<div class="container-xxl flex-grow-1 container-p-y">
  <div class="row">
    <div class="col-lg-8 mx-auto">
      <div class="card mb-4">
        <div class="card-header d-flex align-items-center justify-content-between">
          <h4 class="mb-0">Configuration SMTP & Emails de Notification</h4>
        </div>
        <div class="card-body">
          <?php if (!empty($success_message)): ?>
            <div class="alert alert-success mb-3"> <?php echo $success_message; ?> </div>
          <?php endif; ?>
          <form method="post" action="smtp-config.php">
            <div class="row g-3">
              <div class="col-md-6">
                <label class="form-label">Chiffrement</label>
                <select name="smtp_ssl" class="form-select">
                  <option value="none" <?php if(($smtp_ssl ?? '')=='none') echo 'selected'; ?>>Aucun</option>
                  <option value="ssl" <?php if(($smtp_ssl ?? '')=='ssl') echo 'selected'; ?>>SSL</option>
                  <option value="tls" <?php if(($smtp_ssl ?? '')=='tls') echo 'selected'; ?>>TLS</option>
                </select>
              </div>
              <div class="col-md-6">
                <label class="form-label">Statut SMTP</label>
                <select name="statut" class="form-select">
                  <option value="1" <?php if(($statut ?? 1)==1) echo 'selected'; ?>>Activé</option>
                  <option value="0" <?php if(($statut ?? 1)==0) echo 'selected'; ?>>Désactivé</option>
                </select>
              </div>
              <div class="col-md-6">
                <label class="form-label">Serveur SMTP</label>
                <input type="text" name="smtp_host" class="form-control" required value="<?php echo htmlspecialchars($smtp_host ?? ''); ?>">
              </div>
              <div class="col-md-3">
                <label class="form-label">Port SMTP</label>
                <input type="number" name="smtp_port" class="form-control" required value="<?php echo htmlspecialchars($smtp_port ?? ''); ?>">
              </div>
              <div class="col-md-3">
                <label class="form-label">Nom d'utilisateur SMTP</label>
                <input type="text" name="smtp_user" class="form-control" required value="<?php echo htmlspecialchars($smtp_user ?? ''); ?>">
              </div>
              <div class="col-md-6">
                <label class="form-label">Mot de passe SMTP</label>
                <input type="password" name="smtp_pass" class="form-control" required value="<?php echo htmlspecialchars($smtp_pass ?? ''); ?>">
              </div>
              <div class="col-md-6">
                <label class="form-label">Email expéditeur (FROM)</label>
                <input type="email" name="smtp_from" class="form-control" required value="<?php echo htmlspecialchars($smtp_from ?? ''); ?>">
              </div>
              <div class="col-md-6">
                <label class="form-label">Nom expéditeur</label>
                <input type="text" name="smtp_from_name" class="form-control" value="<?php echo htmlspecialchars($smtp_from_name ?? ''); ?>">
              </div>
              <div class="col-md-6">
                <label class="form-label">Email administrateur (notification)</label>
                <input type="email" name="email_admin" class="form-control" required value="<?php echo htmlspecialchars($email_admin ?? ''); ?>">
              </div>
              <div class="col-md-6">
                <label class="form-label">Email copie 1 (CC)</label>
                <input type="email" name="email_cc1" class="form-control" value="<?php echo htmlspecialchars($email_cc1 ?? ''); ?>">
              </div>
              <div class="col-md-6">
                <label class="form-label">Email copie 2 (CC)</label>
                <input type="email" name="email_cc2" class="form-control" value="<?php echo htmlspecialchars($email_cc2 ?? ''); ?>">
              </div>
              <!-- Suppression du switch d'activation du widget de chat -->
            </div>
            <div class="mt-4 d-flex gap-2">
              <button type="submit" class="btn btn-primary">Enregistrer la configuration</button>
              <button type="button" class="btn btn-outline-info" onclick="testSmtp()">Envoyer un email de test</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</div>
<?php
$page_content = ob_get_clean();
// Script JS pour le bouton de test SMTP
$page_content .= '<script>
function testSmtp() {
  const btn = event.target;
  btn.disabled = true;
  btn.innerText = "Envoi en cours...";
  fetch("smtp-config.php?test=1", { method: "POST" })
    .then(r => r.json())
    .then(data => {
      alert(data.success ? "Test réussi : " + data.message : "Erreur : " + data.message);
    })
    .catch(e => alert("Erreur réseau : " + e.message))
    .finally(() => { btn.disabled = false; btn.innerText = "Envoyer un email de test"; });
}
</script>';
// Traitement du test SMTP
if (isset($_GET['test']) && $_SERVER['REQUEST_METHOD'] === 'POST') {
  // Charger la config
  $db = getDbConnection();
  $row = $db->query('SELECT * FROM smtp_config WHERE id=1')->fetch(PDO::FETCH_ASSOC);
  if (!$row) {
    echo json_encode(['success'=>false,'message'=>'Configuration SMTP introuvable']);
    exit;
  }
  // Test d'envoi (PHPMailer recommandé, ici version simple mail())
  $to = $row['email_admin'] ?? 'test@localhost';
  $subject = 'Test SMTP depuis le panel admin';
  $msg = "Ceci est un test d'envoi SMTP depuis la configuration admin SERVICES-AE.";
  $headers = [
    'From: ' . ($row['smtp_from'] ?? 'no-reply@localhost'),
    'Reply-To: ' . ($row['smtp_from'] ?? 'no-reply@localhost'),
    'Content-Type: text/plain; charset=utf-8'
  ];
  $ok = mail($to, $subject, $msg, implode("\r\n", $headers));
  echo json_encode(['success'=>$ok,'message'=>$ok ? 'Email envoyé à ' . $to : 'Échec d\'envoi. Vérifiez la config SMTP.']);
  exit;
}
include 'template.php';