<?php
@session_start();
// Page configuration SMTP (centrale)
// Accès restreint admin

require_once __DIR__.'/config/connexion.php'; // $gc_pdo

if(!isset($_SESSION['user_role']) || !in_array($_SESSION['user_role'], ['Super admin','admin'])){
  http_response_code(403);
  echo 'Accès refusé';
  exit;
}

// Config globale unique (une seule ligne id=1)

function h($s){return htmlspecialchars($s??'',ENT_QUOTES,'UTF-8');}

// Génération / vérification d'un token CSRF simple
if(empty($_SESSION['csrf_email_cfg'])){ $_SESSION['csrf_email_cfg'] = bin2hex(random_bytes(16)); }
$csrf_token = $_SESSION['csrf_email_cfg'];

$existing = null; $msg=''; $msgType=''; $hasSupportCol=false; $hasWhatsappCol=false; $hasSupportTelCol=false;
// Créer table si absente (nouveau schéma sans compagnie_ref, une seule ligne id=1)
try{
  $gc_pdo->exec("CREATE TABLE IF NOT EXISTS email_settings_table (\n    id INT PRIMARY KEY,\n    smtp_host VARCHAR(255) NOT NULL,\n    smtp_port INT NOT NULL DEFAULT 587,\n    smtp_username VARCHAR(255) NULL,\n    smtp_password VARCHAR(255) NULL,\n    encryption VARCHAR(10) NOT NULL DEFAULT 'tls',\n    from_email VARCHAR(255) NOT NULL,\n    from_name VARCHAR(255) NULL,\n    support_email VARCHAR(255) NULL,\n    whatssap_msg TEXT NULL,\n    support_tel VARCHAR(40) NULL,\n    auth_enabled TINYINT(1) NOT NULL DEFAULT 1,\n    active TINYINT(1) NOT NULL DEFAULT 1,\n    created_at DATETIME NOT NULL,\n    updated_at DATETIME NOT NULL\n  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
}catch(Throwable $e){ /* ignore creation */ }
if($gc_pdo instanceof PDO){
  // Vérifier colonne support_email, créer si absente
  // Charger la ligne id=1
  try { $st=$gc_pdo->query('SELECT * FROM email_settings_table WHERE id=1 LIMIT 1'); $existing=$st->fetch(PDO::FETCH_ASSOC) ?: null; } catch(Throwable $e){ }
  if($existing){
    $hasSupportCol = array_key_exists('support_email',$existing);
    $hasWhatsappCol = array_key_exists('whatssap_msg',$existing);
    $hasSupportTelCol = array_key_exists('support_tel',$existing);
  } else { $hasSupportCol=$hasWhatsappCol=$hasSupportTelCol=true; }
}

if($_SERVER['REQUEST_METHOD']==='POST'){
  if(!hash_equals($csrf_token, $_POST['csrf_token'] ?? '')){ $msg='Token invalide.'; $msgType='danger'; }
  else {
    // Test d'envoi (utilise la configuration déjà sauvegardée)
    if(($_POST['action'] ?? '')==='test_email'){
      header('Content-Type: application/json; charset=utf-8');
      $resp=['ok'=>false,'log'=>[]];
      if(!$existing){ $resp['log'][]='Configuration inexistante: sauvegardez d\'abord.'; echo json_encode($resp); exit; }
      $to = trim($_POST['test_email_to'] ?? '');
      if($to==='' || !filter_var($to,FILTER_VALIDATE_EMAIL)) $to = $existing['support_email'] ?: ($existing['from_email'] ?? '');
      if($to==='' || !filter_var($to,FILTER_VALIDATE_EMAIL)) { $resp['log'][]='Destinataire test invalide.'; echo json_encode($resp); exit; }
      // Simple client SMTP (AUTH LOGIN / STARTTLS basique)
      $host = $existing['smtp_host'];
      $port = (int)$existing['smtp_port']; if(!$port) $port=25;
      $enc  = $existing['encryption'] ?? 'tls';
      $auth = !empty($existing['auth_enabled']);
      $user = $existing['smtp_username'] ?? '';
      $pass = $existing['smtp_password'] ?? '';
      $fromEmail = $existing['from_email'] ?? '';
      $fromName = $existing['from_name'] ?: $fromEmail;
      if($fromEmail===''){ $resp['log'][]='Email expéditeur manquant.'; echo json_encode($resp); exit; }
      $timeout=15;
      $transportHost = ($enc==='ssl' ? 'ssl://'.$host : $host);
      $fp = @stream_socket_client($transportHost.':'.$port,$errno,$errstr,$timeout,STREAM_CLIENT_CONNECT,stream_context_create(['ssl'=>['verify_peer'=>false,'verify_peer_name'=>false]]));
      if(!$fp){ $resp['log'][]='Connexion échouée: '.$errno.' '.$errstr; echo json_encode($resp); exit; }
      stream_set_timeout($fp,$timeout);
      $read = function() use($fp,&$resp){ $d=''; while(($l=fgets($fp,512))!==false){ $d.=$l; if(preg_match('~^[0-9]{3} ~',$l)) break; } $resp['log'][]='S: '.trim($d); return $d; };
      $cmd = function($c) use($fp,&$resp,$read){ $resp['log'][]='C: '.trim($c); fwrite($fp,$c."\r\n"); return $read(); };
      $banner=$read(); if(!preg_match('~^220~',$banner)){ $resp['log'][]='Bannière inattendue'; fclose($fp); echo json_encode($resp); exit; }
      $ehloResp=$cmd('EHLO local.test');
      if($enc==='tls' && stripos($ehloResp,'STARTTLS')!==false){
        $start=$cmd('STARTTLS'); if(!preg_match('~^220~',$start)){ $resp['log'][]='STARTTLS échec'; fclose($fp); echo json_encode($resp); exit; }
        if(!@stream_socket_enable_crypto($fp,true,STREAM_CRYPTO_METHOD_TLS_CLIENT)){ $resp['log'][]='Négociation TLS échouée'; fclose($fp); echo json_encode($resp); exit; }
        $ehloResp=$cmd('EHLO local.test');
      }
      if($auth){
        if($user===''||$pass===''){ $resp['log'][]='Identifiants manquants.'; fclose($fp); echo json_encode($resp); exit; }
        $a1=$cmd('AUTH LOGIN'); if(!preg_match('~^334~',$a1)){ $resp['log'][]='AUTH LOGIN refusé'; fclose($fp); echo json_encode($resp); exit; }
        $a2=$cmd(base64_encode($user)); if(!preg_match('~^334~',$a2)){ $resp['log'][]='Login rejeté'; fclose($fp); echo json_encode($resp); exit; }
        $a3=$cmd(base64_encode($pass)); if(!preg_match('~^235~',$a3)){ $resp['log'][]='Mot de passe rejeté'; fclose($fp); echo json_encode($resp); exit; }
      }
      $mfrom=$cmd('MAIL FROM:<'.$fromEmail.'>'); if(!preg_match('~^250~',$mfrom)){ $resp['log'][]='MAIL FROM refusé'; fclose($fp); echo json_encode($resp); exit; }
      $mrcpt=$cmd('RCPT TO:<'.$to.'>'); if(!preg_match('~^250|^251~',$mrcpt)){ $resp['log'][]='RCPT TO refusé'; fclose($fp); echo json_encode($resp); exit; }
      $data=$cmd('DATA'); if(!preg_match('~^354~',$data)){ $resp['log'][]='DATA refusé'; fclose($fp); echo json_encode($resp); exit; }
      $subject='Test configuration SMTP';
      $body="Ce message confirme le bon fonctionnement de la configuration SMTP.\r\nDate: ".date('Y-m-d H:i:s');
      $headers=[]; $headers[]='From: '.(mb_encode_mimeheader($fromName,'UTF-8')).' <'.$fromEmail.'>';
      $headers[]='To: <'.$to.'>';
      $headers[]='Subject: '.mb_encode_mimeheader($subject,'UTF-8');
      $headers[]='MIME-Version: 1.0';
      $headers[]='Content-Type: text/plain; charset=UTF-8';
      $msgFull=implode("\r\n",$headers)."\r\n\r\n".$body."\r\n.";
      fwrite($fp,$msgFull."\r\n");
      $end=$read(); if(!preg_match('~^250~',$end)){ $resp['log'][]='Envoi DATA non confirmé'; fclose($fp); echo json_encode($resp); exit; }
      $quit=$cmd('QUIT');
      fclose($fp);
      $resp['ok']=true; $resp['log'][]='Test terminé avec succès.'; $resp['to']=$to;
      echo json_encode($resp); exit;
    }
    $smtp_host = trim($_POST['smtp_host'] ?? '');
    $smtp_port = (int)($_POST['smtp_port'] ?? 0);
    $smtp_username = trim($_POST['smtp_username'] ?? '');
    $smtp_password = trim($_POST['smtp_password'] ?? '');
    $encryption = in_array($_POST['encryption'] ?? 'tls',['tls','ssl','none']) ? $_POST['encryption'] : 'tls';
  $from_email = trim($_POST['from_email'] ?? '');
  $support_email = trim($_POST['support_email'] ?? '');
    $from_name = trim($_POST['from_name'] ?? '');
    $whatssap_msg = trim($_POST['whatssap_msg'] ?? '');
    $tel_code = trim($_POST['tel_code'] ?? '');
    if($tel_code!=='' && $tel_code[0] !== '+') $tel_code = '+'.$tel_code;
    $support_tel_number_raw = trim($_POST['support_tel_number'] ?? '');
    $support_tel_number = preg_replace('~[^0-9]+~','',$support_tel_number_raw);
    $support_tel = '';
    if($support_tel_number !== ''){
      $support_tel = $tel_code.$support_tel_number;
    }
  $auth_enabled = isset($_POST['auth_enabled']) ? 1 : 0;
    $active = isset($_POST['active']) ? 1 : 0;

    if($smtp_host==='' || $from_email===''){
      $msg='Champs obligatoires manquants (hôte SMTP, email expéditeur).'; $msgType='danger';
    } elseif($support_email!=='' && !filter_var($support_email,FILTER_VALIDATE_EMAIL)) {
      $msg='Email support invalide.'; $msgType='danger';
    } else {
      try{
        if($existing){
          // Si mot de passe laissé vide on conserve l'ancien
          if($smtp_password==='') $smtp_password = $existing['smtp_password'];
          // Construction dynamique UPDATE
          $data = [
            'smtp_host'=>$smtp_host,
            'smtp_port'=>$smtp_port,
            'smtp_username'=>$smtp_username,
            'smtp_password'=>$smtp_password,
            'encryption'=>$encryption,
            'from_email'=>$from_email,
            'from_name'=>$from_name,
          ];
          if($hasSupportCol) $data['support_email']=$support_email;
          if($hasWhatsappCol) $data['whatssap_msg']=$whatssap_msg;
          if($hasSupportTelCol) $data['support_tel']=$support_tel;
          $data['auth_enabled']=$auth_enabled;
          $data['active']=$active;
          $setParts = [];
          foreach(array_keys($data) as $k){ $setParts[] = "$k=?"; }
          $sql = 'UPDATE email_settings_table SET '.implode(',', $setParts).', updated_at=NOW() WHERE id=1';
          $stmt = $gc_pdo->prepare($sql);
          $stmt->execute(array_values($data));
          $msg='Configuration mise à jour.'; $msgType='success';
          // Mettre à jour $existing pour ré-affichage
          foreach($data as $k=>$v){ $existing[$k]=$v; }
        } else {
          // Construction dynamique INSERT
          $cols = ['id','smtp_host','smtp_port','smtp_username','smtp_password','encryption','from_email','from_name'];
          $vals = [1,$smtp_host,$smtp_port,$smtp_username,$smtp_password,$encryption,$from_email,$from_name];
          if($hasSupportCol){ $cols[]='support_email'; $vals[]=$support_email; }
          if($hasWhatsappCol){ $cols[]='whatssap_msg'; $vals[]=$whatssap_msg; }
          if($hasSupportTelCol){ $cols[]='support_tel'; $vals[]=$support_tel; }
          $cols[]='auth_enabled'; $vals[]=$auth_enabled;
          $cols[]='active'; $vals[]=$active;
          $placeholders = rtrim(str_repeat('?,', count($cols)) , ',');
          $sql = 'INSERT INTO email_settings_table ('.implode(',',$cols).',created_at,updated_at) VALUES ('.$placeholders.',NOW(),NOW())';
          $ins = $gc_pdo->prepare($sql);
          $ins->execute($vals);
          $msg='Configuration enregistrée.'; $msgType='success';
          $existing = [ // refresh affichage
            'smtp_host'=>$smtp_host,'smtp_port'=>$smtp_port,'smtp_username'=>$smtp_username,'smtp_password'=>$smtp_password,'encryption'=>$encryption,'from_email'=>$from_email,'from_name'=>$from_name,'support_email'=>$support_email,'whatssap_msg'=>$whatssap_msg,'support_tel'=>$support_tel,'auth_enabled'=>$auth_enabled,'active'=>$active
          ];
        }
      }catch(Throwable $e){ $msg='Erreur enregistrement: '.$e->getMessage(); $msgType='danger'; }
    }
  }
}

// Valeurs pour formulaire
$val = function($key,$default='') use ($existing){ return h($existing[$key] ?? $default); };
$checked = function($key) use ($existing){ return !empty($existing[$key]) ? 'checked' : ''; };
$selected = function($key,$value,$default='tls') use ($existing){ $cur = $existing[$key] ?? $default; return $cur===$value? 'selected':''; };
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<title>Configuration Email SMTP</title>
<link rel="stylesheet" href="../vendor/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="../vendor/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="../css/ruang-admin.min.css">
<style>
  .card-email{border-left:4px solid #1cc88a;}
  .form-control[readonly]{background:#f8f9fc;}
</style>
</head>
<body id="page-top">
<div id="wrapper">
  <?php include __DIR__.'/sidebar.php'; ?>
  <div id="content-wrapper" class="d-flex flex-column">
    <div id="content">
  <?php include __DIR__.'/topbar.php'; ?>
      <div class="container-fluid">
        <div class="d-sm-flex align-items-center justify-content-between mb-4">
          <h1 class="h3 mb-0 text-gray-800"><i class="fas fa-envelope text-success"></i> SMTP</h1>
          <a href="../dashboard.php" class="btn btn-sm btn-secondary"><i class="fas fa-home"></i> Dashboard</a>
        </div>
        <div class="row">
          <div class="col-lg-10 col-xl-8 mb-4">
            <div class="card shadow card-email">
              <div class="card-header py-2"><strong>Configuration SMTP (Global)</strong></div>
              <div class="card-body">
                <?php if($msg): ?>
                  <div class="alert alert-<?=$msgType?> py-2"><?=h($msg)?></div>
                <?php endif; ?>
                <form method="post" autocomplete="off">
                  <input type="hidden" name="csrf_token" value="<?=h($csrf_token)?>">
                  <div class="form-row">
                    <div class="form-group col-md-6">
                      <label>Hôte SMTP *</label>
                      <input type="text" name="smtp_host" class="form-control form-control-sm" required value="<?=$val('smtp_host')?>">
                    </div>
                    <div class="form-group col-md-3">
                      <label>Port *</label>
                      <input type="number" name="smtp_port" class="form-control form-control-sm" required value="<?=$val('smtp_port',587)?>">
                    </div>
                    <div class="form-group col-md-3">
                      <label>Chiffrement</label>
                      <select name="encryption" class="form-control form-control-sm">
                        <option value="tls" <?=$selected('encryption','tls')?>>TLS</option>
                        <option value="ssl" <?=$selected('encryption','ssl')?>>SSL</option>
                        <option value="none" <?=$selected('encryption','none')?>>Aucun</option>
                      </select>
                    </div>
                  </div>
                  <div class="form-row">
                    <div class="form-group col-md-6">
                      <label>Utilisateur (login)</label>
                      <input type="text" name="smtp_username" class="form-control form-control-sm" value="<?=$val('smtp_username')?>">
                    </div>
                    <div class="form-group col-md-6">
                      <label>Mot de passe <?= $existing?'<small class="text-muted">(laisser vide pour ne pas changer)</small>':''; ?></label>
                      <input type="password" name="smtp_password" class="form-control form-control-sm" value="">
                    </div>
                  </div>
                  <div class="form-row">
                    <div class="form-group col-md-4">
                      <label>Email expéditeur *</label>
                      <input type="email" name="from_email" class="form-control form-control-sm" required value="<?=$val('from_email')?>">
                    </div>
                    <div class="form-group col-md-4">
                      <label>Email support (notifications)</label>
                      <input type="email" name="support_email" class="form-control form-control-sm" value="<?=$val('support_email')?>" placeholder="support@domaine.tld">
                    </div>
                    <div class="form-group col-md-4">
                      <label>Nom expéditeur</label>
                      <input type="text" name="from_name" class="form-control form-control-sm" value="<?=$val('from_name')?>">
                    </div>
                  </div>
                  <?php // Pré-remplir découpage téléphone
                    $tel_code_value = '+212'; $tel_number_value='';
                    if(!empty($existing['support_tel']) && preg_match('/^(\+\d{1,4})(\d{4,})$/',$existing['support_tel'],$mTel)){
                      $tel_code_value = $mTel[1]; $tel_number_value = $mTel[2];
                    }
                  ?>
                  <div class="form-group">
                    <label>Message WhatsApp (optionnel)</label>
                    <textarea name="whatssap_msg" class="form-control form-control-sm" rows="3" placeholder="Texte du message à utiliser pour WhatsApp."><?=$val('whatssap_msg')?></textarea>
                    <small class="form-text text-muted">Ce texte pourra être utilisé comme template pour des notifications WhatsApp.</small>
                  </div>
                  <div class="form-row">
                    <div class="form-group col-md-4">
                      <label>Tél. support (indicatif)</label>
                      <select name="tel_code" class="form-control form-control-sm">
                        <?php $codes=['+212'=>'+212 Maroc','+213'=>'+213 Algérie','+216'=>'+216 Tunisie','+33'=>'+33 France','+34'=>'+34 Espagne','+44'=>'+44 UK','+1'=>'+1 USA/Canada']; foreach($codes as $c=>$lbl): ?>
                          <option value="<?=h($c)?>" <?=$tel_code_value===$c?'selected':''?>><?=h($lbl)?></option>
                        <?php endforeach; ?>
                      </select>
                    </div>
                    <div class="form-group col-md-8">
                      <label>&nbsp;</label>
                      <input type="text" name="support_tel_number" class="form-control form-control-sm" value="<?=h($tel_number_value)?>" placeholder="Numéro sans indicatif">
                      <small class="form-text text-muted">Stocké sous la forme <?=$tel_code_value?>NUMERO.</small>
                    </div>
                  </div>
                  <div class="form-row">
                    <div class="form-group col-md-3">
                      <div class="form-check mt-4">
                        <input class="form-check-input" type="checkbox" name="auth_enabled" id="auth_enabled" <?=$checked('auth_enabled')?>>
                        <label class="form-check-label" for="auth_enabled">Authentification</label>
                      </div>
                    </div>
                    <div class="form-group col-md-3">
                      <div class="form-check mt-4">
                        <input class="form-check-input" type="checkbox" name="active" id="active" <?=$checked('active')?>>
                        <label class="form-check-label" for="active">Actif</label>
                      </div>
                    </div>
                  </div>
                  <div class="mt-3 d-flex align-items-center flex-wrap gap-2">
                    <button class="btn btn-success btn-sm mr-2"><i class="fas fa-save"></i> Enregistrer</button>
                    <a href="../dashboard.php" class="btn btn-outline-secondary btn-sm mr-3">Annuler</a>
                    <div class="form-inline mt-2 mt-sm-0">
                      <div class="input-group input-group-sm mr-2" style="max-width:260px;">
                        <input type="email" class="form-control" id="test_email_to" placeholder="Email de test (optionnel)">
                        <div class="input-group-append">
                          <button class="btn btn-info" type="button" id="btnTestEmail"><i class="fas fa-paper-plane"></i> Test</button>
                        </div>
                      </div>
                      <button type="button" class="btn btn-outline-info btn-sm" id="btnShowLog"><i class="fas fa-terminal"></i></button>
                    </div>
                  </div>
                  <div id="testEmailResult" class="mt-3" style="display:none;">
                    <div class="card border-info">
                      <div class="card-header py-1 d-flex justify-content-between align-items-center">
                        <span class="small font-weight-bold text-info"><i class="fas fa-envelope-open-text"></i> Journal Test SMTP</span>
                        <button type="button" class="close" id="btnCloseLog"><span>&times;</span></button>
                      </div>
                      <div class="card-body p-2" style="max-height:220px;overflow:auto;">
                        <pre id="testLog" class="small mb-0" style="white-space:pre-wrap; font-family:monospace;">(vide)</pre>
                      </div>
                    </div>
                  </div>
                </form>
                <hr>
                <p class="small text-muted mb-0">Les informations SMTP sont stockées en clair (mot de passe). En production, prévoir un chiffrement ou un coffre-fort de secrets.</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  <footer class="sticky-footer bg-white"><div class="container my-auto"><div class="text-center my-auto small">&copy; <?php echo date('Y'); ?> Backups</div></div></footer>
  </div>
</div>
<a class="scroll-to-top rounded" href="#page-top"><i class="fas fa-angle-up"></i></a>
<script src="../vendor/jquery/jquery.min.js"></script>
<script src="../vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../vendor/jquery-easing/jquery.easing.min.js"></script>
<script src="../js/ruang-admin.min.js"></script>
<script>
$(function(){
  const $btnTest = $('#btnTestEmail');
  const $logWrap = $('#testEmailResult');
  const $log = $('#testLog');
  $('#btnShowLog').on('click',function(){ $logWrap.show(); });
  $('#btnCloseLog').on('click',function(){ $logWrap.hide(); });
  $btnTest.on('click',function(){
    $logWrap.show();
    $log.text('Démarrage test...');
    $btnTest.prop('disabled',true).html('<i class="fas fa-spinner fa-spin"></i>');
    const to = $('#test_email_to').val();
    $.ajax({
      method:'POST',
      url:'email_config.php',
      data:{ action:'test_email', csrf_token:'<?=h($csrf_token)?>', test_email_to: to },
      dataType:'json'
    }).done(function(res){
      let out='';
      if(res.log){ out = res.log.join('\n'); }
      if(res.ok){ out+='\n-- OK (envoyé à '+(res.to||'')+')'; }
      else { out+='\n-- ECHEC'; }
      $log.text(out);
    }).fail(function(xhr){
      $log.text('Erreur AJAX: '+xhr.status+' '+xhr.statusText);
    }).always(function(){
      $btnTest.prop('disabled',false).html('<i class="fas fa-paper-plane"></i> Test');
    });
  });
});
</script>
</body>
</html>
