<?php
declare(strict_types=1);

function mail_settings_from_files(array $appCfg): array
{
  $mailCfg = $appCfg['mail'] ?? null;
  if (!is_array($mailCfg) || empty($mailCfg)) {
    $mailFile = __DIR__ . '/../config/mail.php';
    if (is_file($mailFile)) {
      $mailCfg = require $mailFile;
    }
  }
  return is_array($mailCfg) ? $mailCfg : [];
}

function mail_parse_list($value): array
{
  if (is_array($value)) {
    $out = [];
    foreach ($value as $v) {
      $v = trim((string)$v);
      if ($v !== '') $out[] = $v;
    }
    return $out;
  }
  if (!is_string($value)) return [];
  $raw = trim($value);
  if ($raw === '') return [];

  $json = json_decode($raw, true);
  if (is_array($json)) {
    return mail_parse_list($json);
  }

  $parts = preg_split('/[,\n;]+/', $raw) ?: [];
  $out = [];
  foreach ($parts as $p) {
    $p = trim($p);
    if ($p !== '') $out[] = $p;
  }
  return $out;
}

function mail_normalize_config(array $cfg): array
{
  return [
    'enabled' => isset($cfg['enabled']) ? (bool)$cfg['enabled'] : true,
    'host' => (string)($cfg['host'] ?? ''),
    'port' => (int)($cfg['port'] ?? 465),
    'secure' => (string)($cfg['secure'] ?? 'ssl'),
    'username' => (string)($cfg['username'] ?? ''),
    'password' => (string)($cfg['password'] ?? ''),
    'from_email' => (string)($cfg['from_email'] ?? ''),
    'from_name' => (string)($cfg['from_name'] ?? ''),
    'to' => mail_parse_list($cfg['to'] ?? []),
    'subject_prefix' => (string)($cfg['subject_prefix'] ?? 'IVR Gunluk Onay Raporu'),
  ];
}

function ensure_mail_settings_table(PDO $pdo): void
{
  $pdo->exec("
    CREATE TABLE IF NOT EXISTS consent_email_settings (
      id tinyint(3) UNSIGNED NOT NULL PRIMARY KEY,
      enabled tinyint(1) NOT NULL DEFAULT 1,
      host varchar(190) DEFAULT NULL,
      port int(10) UNSIGNED NOT NULL DEFAULT 465,
      secure varchar(10) DEFAULT 'ssl',
      username varchar(190) DEFAULT NULL,
      password varchar(190) DEFAULT NULL,
      from_email varchar(190) DEFAULT NULL,
      from_name varchar(190) DEFAULT NULL,
      to_emails text DEFAULT NULL,
      subject_prefix varchar(255) DEFAULT NULL,
      updated_at datetime NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
  ");
}

function mail_fetch_settings_row(PDO $pdo): ?array
{
  try {
    $st = $pdo->query("SELECT * FROM consent_email_settings WHERE id=1 LIMIT 1");
    $row = $st ? $st->fetch(PDO::FETCH_ASSOC) : false;
    return $row ?: null;
  } catch (Throwable $e) {
    return null;
  }
}

function mail_save_settings(PDO $pdo, array $data): void
{
  $st = $pdo->prepare("
    INSERT INTO consent_email_settings
      (id, enabled, host, port, secure, username, password, from_email, from_name, to_emails, subject_prefix)
    VALUES
      (1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ON DUPLICATE KEY UPDATE
      enabled = VALUES(enabled),
      host = VALUES(host),
      port = VALUES(port),
      secure = VALUES(secure),
      username = VALUES(username),
      password = VALUES(password),
      from_email = VALUES(from_email),
      from_name = VALUES(from_name),
      to_emails = VALUES(to_emails),
      subject_prefix = VALUES(subject_prefix)
  ");

  $st->execute([
    (int)($data['enabled'] ?? 0),
    (string)($data['host'] ?? ''),
    (int)($data['port'] ?? 465),
    (string)($data['secure'] ?? 'ssl'),
    (string)($data['username'] ?? ''),
    (string)($data['password'] ?? ''),
    (string)($data['from_email'] ?? ''),
    (string)($data['from_name'] ?? ''),
    (string)($data['to_emails'] ?? ''),
    (string)($data['subject_prefix'] ?? ''),
  ]);
}

function mail_load_config(PDO $pdo, array $appCfg): array
{
  $base = mail_normalize_config(mail_settings_from_files($appCfg));
  ensure_mail_settings_table($pdo);
  $row = mail_fetch_settings_row($pdo);
  if ($row) {
    $override = [
      'enabled' => ((int)($row['enabled'] ?? 0) === 1),
      'host' => (string)($row['host'] ?? ''),
      'port' => (int)($row['port'] ?? 0),
      'secure' => (string)($row['secure'] ?? ''),
      'username' => (string)($row['username'] ?? ''),
      'password' => (string)($row['password'] ?? ''),
      'from_email' => (string)($row['from_email'] ?? ''),
      'from_name' => (string)($row['from_name'] ?? ''),
      'to' => (string)($row['to_emails'] ?? ''),
      'subject_prefix' => (string)($row['subject_prefix'] ?? ''),
    ];
    return mail_normalize_config(array_merge($base, $override));
  }
  return $base;
}
