<?php
// inc/mailer.php (FINAL) - robust mail + logging + PHPMailer SMTP + safe headers
declare(strict_types=1);

$cfg = __DIR__ . '/config.mail.php';
if (is_file($cfg)) require_once $cfg;

/* =========================
   Defaults (can override in config.mail.php)
   ========================= */
if (!defined('MAIL_FROM'))       define('MAIL_FROM', 'no-reply@hamdanlegalgroup.ae');
if (!defined('MAIL_FROM_NAME'))  define('MAIL_FROM_NAME', 'HLG HR');
if (!defined('MAIL_REPLY_TO'))   define('MAIL_REPLY_TO', 'contact@hamdanlegalgroup.ae');

if (!defined('MAIL_USE_SMTP'))   define('MAIL_USE_SMTP', true);
if (!defined('MAIL_SMTP_HOST'))  define('MAIL_SMTP_HOST', 'mail.hamdanlegalgroup.ae');
if (!defined('MAIL_SMTP_USER'))  define('MAIL_SMTP_USER', 'contact@hamdanlegalgroup.ae');
if (!defined('MAIL_SMTP_PASS'))  define('MAIL_SMTP_PASS', ''); // ضعها في config.mail.php
if (!defined('MAIL_SMTP_PORT'))  define('MAIL_SMTP_PORT', 465);
if (!defined('MAIL_SMTP_SECURE')) define('MAIL_SMTP_SECURE', 'ssl'); // ssl أو tls

// مسار PHPMailer عندك
if (!defined('MAILER_PHPMAILER_DIR')) {
  define('MAILER_PHPMAILER_DIR', __DIR__ . '/../vendor/phpmailer/phpmailer/src');
}

/* =========================
   Helpers
   ========================= */
if (!function_exists('mail_log_path')) {
  function mail_log_path(): string {
    $p1 = __DIR__ . '/../cron/cron_mail_error.log';
    $p2 = __DIR__ . '/cron_mail_error.log';
    return is_dir(dirname($p1)) ? $p1 : $p2;
  }
}

if (!function_exists('mail_log')) {
  function mail_log(string $line): void {
    @file_put_contents(mail_log_path(), $line . "\n", FILE_APPEND);
  }
}

if (!function_exists('mail_safe_str')) {
  function mail_safe_str(string $s): string {
    $s = str_replace(["\r", "\n"], ' ', $s); // منع حقن الهيدر
    return trim($s);
  }
}

if (!function_exists('mail_domain')) {
  function mail_domain(): string {
    $host = '';
    try {
      $host = (string)parse_url('https://hamdanlegalgroup.ae', PHP_URL_HOST);
    } catch (Throwable $e) {}
    $host = trim($host);
    if ($host === '') $host = (string)($_SERVER['HTTP_HOST'] ?? '');
    $host = preg_replace('~[^a-z0-9\.\-]~i', '', $host ?: '') ?: 'localhost';
    return strtolower($host);
  }
}

if (!function_exists('phpmailer_available')) {
  function phpmailer_available(): bool {
    $dir = (string)MAILER_PHPMAILER_DIR;
    return is_file($dir . '/PHPMailer.php') && is_file($dir . '/SMTP.php') && is_file($dir . '/Exception.php');
  }
}

if (!function_exists('phpmailer_bootstrap')) {
  function phpmailer_bootstrap(): void {
    if (class_exists(\PHPMailer\PHPMailer\PHPMailer::class)) return;
    $dir = (string)MAILER_PHPMAILER_DIR;
    require_once $dir . '/Exception.php';
    require_once $dir . '/PHPMailer.php';
    require_once $dir . '/SMTP.php';
  }
}

/* =========================
   Branch name helper (1=Abu Dhabi, 2=Dubai)
   تستخدمها في رسائل الإجازات
   ========================= */
if (!function_exists('branch_name_ar_from_id')) {
  function branch_name_ar_from_id(int $id): string {
    return match ($id) {
      1 => 'أبوظبي',
      2 => 'دبي',
      default => 'غير محدد',
    };
  }
}

/* =========================
   send_mail
   ========================= */
if (!function_exists('send_mail')) {
  function send_mail(
    string $to,
    string $subject,
    string $html,
    string $fromEmail = '',
    string $fromName = '',
    bool $isHtml = true
  ): array {

    $to = trim($to);
    if ($to === '' || !filter_var($to, FILTER_VALIDATE_EMAIL)) {
      mail_log(date('Y-m-d H:i:s') . " send_mail FAIL invalid_to to={$to}");
      return ['ok'=>0,'err'=>'invalid_to','to'=>$to];
    }

    $fromEmail = trim($fromEmail ?: (string)MAIL_FROM);
    $fromName  = trim($fromName  ?: (string)MAIL_FROM_NAME);

    if ($fromEmail === '' || !filter_var($fromEmail, FILTER_VALIDATE_EMAIL)) {
      $fromEmail = (string)MAIL_FROM;
    }

    $subjectSafe  = mail_safe_str($subject);
    $fromNameSafe = mail_safe_str($fromName);

    $messageId = sprintf('<%s.%s@%s>', gmdate('YmdHis'), bin2hex(random_bytes(6)), mail_domain());

    // 1) PHPMailer
    if (phpmailer_available()) {
      try {
        phpmailer_bootstrap();

        $m = new \PHPMailer\PHPMailer\PHPMailer(true);
        $m->CharSet  = 'UTF-8';
        $m->Encoding = 'base64';

        $m->MessageID = $messageId;
        $m->XMailer   = 'HLG-HR';

        $m->setFrom($fromEmail, $fromNameSafe);

        $replyTo = (string)MAIL_REPLY_TO;
        if ($replyTo !== '' && filter_var($replyTo, FILTER_VALIDATE_EMAIL)) {
          $m->addReplyTo($replyTo, $fromNameSafe);
        }

        $m->Sender = $fromEmail; // Return-Path / envelope

        $m->addAddress($to);
        $m->Subject = $subjectSafe;

        if ($isHtml) {
          $m->isHTML(true);
          $m->Body    = $html;
          $m->AltBody = trim(strip_tags($html));
        } else {
          $m->isHTML(false);
          $m->Body = $html;
        }

        // SMTP
        if (MAIL_USE_SMTP) {
          $host = trim((string)MAIL_SMTP_HOST);
          $user = trim((string)MAIL_SMTP_USER);
          $pass = (string)MAIL_SMTP_PASS;

          if ($host === '' || $user === '' || $pass === '') {
            throw new RuntimeException('SMTP enabled but host/user/pass not set (set in config.mail.php)');
          }

          $m->isSMTP();
          $m->Host       = $host;
          $m->SMTPAuth   = true;
          $m->Username   = $user;
          $m->Password   = $pass;
          $m->Port       = (int)MAIL_SMTP_PORT;

          $sec = strtolower(trim((string)MAIL_SMTP_SECURE));
          if ($sec === 'ssl') {
            $m->SMTPSecure = \PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_SMTPS;
          } elseif ($sec === 'tls') {
            $m->SMTPSecure = \PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS;
          } else {
            $m->SMTPSecure = '';
            $m->SMTPAutoTLS = false;
          }

          $m->send();

          mail_log(date('Y-m-d H:i:s') . " send_mail OK via=smtp to={$to} mid={$messageId} subj=" . json_encode($subjectSafe, JSON_UNESCAPED_UNICODE));
          return ['ok'=>1,'mid'=>$messageId,'via'=>'smtp','to'=>$to];
        }

        // non-smtp transport
        try {
          if (is_file('/usr/sbin/sendmail') || is_file('/usr/lib/sendmail')) $m->isSendmail();
          else $m->isMail();

          $m->send();

          mail_log(date('Y-m-d H:i:s') . " send_mail OK via=phpmailer to={$to} mid={$messageId} subj=" . json_encode($subjectSafe, JSON_UNESCAPED_UNICODE));
          return ['ok'=>1,'mid'=>$messageId,'via'=>'phpmailer','to'=>$to];

        } catch (Throwable $e2) {
          mail_log(date('Y-m-d H:i:s') . " send_mail PHPMailer transport FAIL to={$to} mid={$messageId} err=" . $e2->getMessage());
        }

      } catch (Throwable $e) {
        mail_log(date('Y-m-d H:i:s') . " send_mail PHPMailer FAIL to={$to} mid={$messageId} err=" . $e->getMessage());
      }
    } else {
      mail_log(date('Y-m-d H:i:s') . " send_mail NOTE PHPMailer not found dir=" . (string)MAILER_PHPMAILER_DIR);
    }
if (MAIL_USE_SMTP) {
    mail_log(date('Y-m-d H:i:s') . " send_mail STOP fallback disabled because SMTP is enabled to={$to} mid={$messageId}");
    return [
        'ok' => 0,
        'err' => 'smtp_failed_no_fallback',
        'mid' => $messageId,
        'to' => $to
    ];
}
    // 2) native mail()
    $encodedSubject = '=?UTF-8?B?' . base64_encode($subjectSafe) . '?=';

    $headers = [];
    $headers[] = "MIME-Version: 1.0";
    $headers[] = $isHtml ? "Content-Type: text/html; charset=UTF-8" : "Content-Type: text/plain; charset=UTF-8";
    $headers[] = "From: {$fromNameSafe} <{$fromEmail}>";

    $replyTo = (string)MAIL_REPLY_TO;
    if ($replyTo !== '' && filter_var($replyTo, FILTER_VALIDATE_EMAIL)) {
      $headers[] = "Reply-To: {$replyTo}";
    }

    $headers[] = "Message-ID: {$messageId}";
    $headers[] = "X-Mailer: PHP/" . PHP_VERSION;

    $headersStr = implode("\r\n", $headers);

    $extraParams = '';
    if (filter_var($fromEmail, FILTER_VALIDATE_EMAIL)) {
      $extraParams = '-f ' . escapeshellarg($fromEmail);
    }

    $ok = false;
    $lastErr = '';

    @error_clear_last();
    try {
      if ($extraParams !== '') $ok = @mail($to, $encodedSubject, $html, $headersStr, $extraParams);
      else $ok = @mail($to, $encodedSubject, $html, $headersStr);

      $e = error_get_last();
      if ($e && !empty($e['message'])) $lastErr = (string)$e['message'];

    } catch (Throwable $e) {
      $lastErr = $e->getMessage();
      $ok = false;
    }

    if ($ok) {
      mail_log(date('Y-m-d H:i:s') . " send_mail OK via=mail to={$to} mid={$messageId} subj=" . json_encode($subjectSafe, JSON_UNESCAPED_UNICODE));
      return ['ok'=>1,'mid'=>$messageId,'via'=>'mail','to'=>$to];
    }

    mail_log(date('Y-m-d H:i:s') . " send_mail FAIL via=mail to={$to} mid={$messageId} err=" . json_encode($lastErr, JSON_UNESCAPED_UNICODE));
    return ['ok'=>0,'err'=>'mail_failed','detail'=>$lastErr,'mid'=>$messageId,'to'=>$to];
  }
}