<?php
declare(strict_types=1);

/*
  افتح للتشخيص:
  https://hamdanlegalgroup.ae/HLG-Justice-Hub/cron_send_case_emails.php?debug=1
*/

$debug = (isset($_GET['debug']) && $_GET['debug'] === '1');

// لوج ملف
$logDir  = __DIR__ . '/logs';
$logFile = $logDir . '/cron_case_emails.log';
if (!is_dir($logDir)) { @mkdir($logDir, 0755, true); }

ini_set('display_errors', $debug ? '1' : '0');
ini_set('display_startup_errors', $debug ? '1' : '0');
ini_set('log_errors', '1');
ini_set('error_log', $logFile);
error_reporting(E_ALL);

// اطبع أي Fatal حتى لو السيرفر يمنع العرض
register_shutdown_function(function() use ($debug, $logFile){
  $e = error_get_last();
  if (!$e) return;
  $msg = "[FATAL] {$e['message']} in {$e['file']}:{$e['line']}";
  error_log($msg);
  if ($debug) {
    header('Content-Type: text/plain; charset=utf-8');
    echo $msg . "\n\nLog: " . $logFile;
  } else {
    http_response_code(500);
    echo "HTTP ERROR 500";
  }
  exit;
});

set_exception_handler(function(Throwable $e) use ($debug, $logFile){
  $msg = "[EXCEPTION] ".$e->getMessage()." in ".$e->getFile().":".$e->getLine();
  error_log($msg . "\n" . $e->getTraceAsString());
  if ($debug) {
    header('Content-Type: text/plain; charset=utf-8');
    echo $msg . "\n\nLog: " . $logFile;
  } else {
    http_response_code(500);
    echo "HTTP ERROR 500";
  }
  exit;
});

require_once __DIR__ . '/db.php';

/*
  مهم جداً: مسار PHPMailer الصحيح عندك
  public_html/HLG-Justice-Hub/vendor/phpmailer/phpmailer/src
*/
require_once __DIR__ . '/vendor/phpmailer/phpmailer/src/Exception.php';
require_once __DIR__ . '/vendor/phpmailer/phpmailer/src/PHPMailer.php';
require_once __DIR__ . '/vendor/phpmailer/phpmailer/src/SMTP.php';

use PHPMailer\PHPMailer\PHPMailer;

/* =========================
   Config
   ملاحظة: 465 لازم ssl
========================= */
const SMTP_HOST = 'mail.hamdanlegalgroup.ae';
const SMTP_PORT = 465;
const SMTP_USER = 'no-reply@hamdanlegalgroup.ae';
const SMTP_PASS = 'Saif1979s';
const SMTP_SEC  = 'ssl'; // 465 => ssl ، 587 => tls

const FROM_EMAIL = 'no-reply@hamdanlegalgroup.ae';
const FROM_NAME  = 'Hamdan Legal Group';
const REPLY_TO_EMAIL = 'contact@hamdanlegalgroup.ae';
const REPLY_TO_NAME  = 'Hamdan Legal Group';

const MAX_ATTEMPTS = 5;
const BATCH_SIZE   = 10;
const LOCK_MINUTES = 10;

function backoff_minutes(int $attempts): int {
  return match(true) {
    $attempts <= 0 => 1,
    $attempts === 1 => 2,
    $attempts === 2 => 5,
    $attempts === 3 => 15,
    default => 60,
  };
}

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

function build_case_email_html(string $caseNo, string $code, string $clientNotes=''): string {
  $link = "https://hlg.hamdanlegalgroup.ae/HLG-Justice-Hub/case_public.php?code=" . urlencode($code);

  $notesHtml = '';
  $clientNotes = trim((string)$clientNotes);
  if ($clientNotes !== '') {
    $notesHtml = '
      <div style="background:#fff7ed;border:1px solid #fed7aa;padding:14px;border-radius:12px;margin:12px 0">
        <div style="font-weight:700;color:#9a3412;margin-bottom:6px">ملاحظات خاصة لك</div>
        <div style="color:#7c2d12;white-space:pre-line">'.h($clientNotes).'</div>
      </div>
    ';
  }

  return '
  <div style="direction:rtl;text-align:right;font-family:Tajawal,Arial;line-height:1.9">
    <h2 style="color:#006a7a;margin:0 0 10px">تم تسجيل قضيتك بنجاح</h2>
    <p>عزيزي العميل،</p>
    <p>تم إنشاء ملف قضيتك لدينا، ويمكنك المتابعة عبر البيانات التالية:</p>

    <div style="background:#f4f7f8;padding:14px;border-radius:12px;margin:12px 0">
      <div style="margin:6px 0">رقم المتابعة: <span style="font-weight:700">'.h($caseNo).'</span></div>
      <div style="margin:6px 0">كود المتابعة: <span style="font-weight:700;letter-spacing:1px">'.h($code).'</span></div>
    </div>

    '.$notesHtml.'

    <p>رابط المتابعة:</p>
    <p><a href="'.h($link).'" style="color:#006a7a">'.h($link).'</a></p>

    <p style="color:#6b7a7f;font-size:13px;margin-top:16px">هذه رسالة آلية.</p>
  </div>';
}

function send_smtp_mail(string $to, string $subject, string $html): array {
  $mail = new PHPMailer(true);
  try {
    $mail->CharSet = 'UTF-8';
    $mail->isSMTP();
    $mail->Host       = SMTP_HOST;
    $mail->SMTPAuth   = true;
    $mail->Username   = SMTP_USER;
    $mail->Password   = SMTP_PASS;
    $mail->Port       = SMTP_PORT;

    $mail->SMTPSecure = (SMTP_SEC === 'ssl')
      ? PHPMailer::ENCRYPTION_SMTPS
      : PHPMailer::ENCRYPTION_STARTTLS;

    $mail->setFrom(FROM_EMAIL, FROM_NAME);
    $mail->addReplyTo(REPLY_TO_EMAIL, REPLY_TO_NAME);
    $mail->addAddress($to);

    $mail->isHTML(true);
    $mail->Subject = $subject;
    $mail->Body    = $html;

    // بدون mb_substr حتى لو mbstring غير متوفر
    $alt = strip_tags(str_replace(["<br>", "<br/>", "<br />"], "\n", $html));
    $mail->AltBody = $alt;

    $mail->send();
    return ['ok'=>1, 'err'=>''];
  } catch (Throwable $e) {
    return ['ok'=>0, 'err'=>$e->getMessage()];
  }
}

/* =========================
   Main
========================= */
$pdo = db();
if (!$pdo instanceof PDO) { throw new RuntimeException('DB not ready'); }
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

$locker = gethostname() ?: 'cron';

// release stale locks
$pdo->prepare("
  UPDATE case_email_queue
  SET status='PENDING', locked_by=NULL, locked_at=NULL
  WHERE status='SENDING'
    AND locked_at IS NOT NULL
    AND locked_at < (NOW() - INTERVAL ".LOCK_MINUTES." MINUTE)
")->execute();

// pick jobs
$pdo->beginTransaction();

$rows = $pdo->query("
  SELECT id, case_id, to_email, case_no, client_code, client_notes, attempts
  FROM case_email_queue
  WHERE status='PENDING'
    AND (next_attempt_at IS NULL OR next_attempt_at <= NOW())
    AND attempts < ".(int)MAX_ATTEMPTS."
  ORDER BY id ASC
  LIMIT ".(int)BATCH_SIZE."
  FOR UPDATE
")->fetchAll();

if (!$rows) {
  $pdo->commit();
  header('Content-Type: text/plain; charset=utf-8');
  echo "OK - processed 0 job(s)";
  exit;
}

// lock them
$ids = array_map(fn($r)=> (int)$r['id'], $rows);
$in  = implode(',', array_fill(0, count($ids), '?'));

$stLock = $pdo->prepare("
  UPDATE case_email_queue
  SET status='SENDING', locked_by=?, locked_at=NOW()
  WHERE id IN ($in)
");
$stLock->execute(array_merge([$locker], $ids));

$pdo->commit();

// send
$processed = 0;

foreach ($rows as $r) {
  $id = (int)$r['id'];
  $to = (string)$r['to_email'];
  $caseNo = (string)$r['case_no'];
  $code = (string)$r['client_code'];
  $notes = (string)($r['client_notes'] ?? '');
  $attempts = (int)$r['attempts'];

  $subject = "رقم المتابعة لقضيتك: " . $caseNo;
  $html = build_case_email_html($caseNo, $code, $notes);

  $res = send_smtp_mail($to, $subject, $html);

  if ($res['ok'] === 1) {
    $pdo->prepare("
      UPDATE case_email_queue
      SET status='SENT', sent_at=NOW(), last_error=NULL, locked_by=NULL, locked_at=NULL
      WHERE id=?
    ")->execute([$id]);
  } else {
    $newAttempts = $attempts + 1;
    $mins = backoff_minutes($newAttempts);
    $newStatus = ($newAttempts >= MAX_ATTEMPTS) ? 'FAILED' : 'PENDING';

    $pdo->prepare("
      UPDATE case_email_queue
      SET status=?, attempts=?, last_error=?, next_attempt_at=(NOW() + INTERVAL ? MINUTE),
          locked_by=NULL, locked_at=NULL
      WHERE id=?
    ")->execute([$newStatus, $newAttempts, substr($res['err'], 0, 2000), $mins, $id]);
  }

  $processed++;
}

header('Content-Type: text/plain; charset=utf-8');
echo "OK - processed {$processed} job(s)";