<?php
declare(strict_types=1);

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;

require_once __DIR__ . '/../vendor/autoload.php';

function send_client_case_email(string $to, string $caseNo, string $code, array $cfg): array
{
    $out = [
        'ok'    => false,
        'error' => '',
        'debug' => '',
    ];

    $to     = trim($to);
    $caseNo = trim($caseNo);
    $code   = trim($code);

    if ($to === '' || !filter_var($to, FILTER_VALIDATE_EMAIL)) {
        $out['error'] = 'invalid_email';
        return $out;
    }

    if ($caseNo === '') {
        $out['error'] = 'invalid_case_no';
        return $out;
    }

    if ($code === '') {
        $out['error'] = 'invalid_code';
        return $out;
    }

    $host      = trim((string)($cfg['host'] ?? ''));
    $username  = trim((string)($cfg['username'] ?? ''));
    $password  = (string)($cfg['password'] ?? '');
    $port      = (int)($cfg['port'] ?? 0);
    $fromEmail = trim((string)($cfg['from_email'] ?? ''));
    $fromName  = trim((string)($cfg['from_name'] ?? ''));
    $replyTo   = trim((string)($cfg['reply_to'] ?? ''));
    $debug     = (int)($cfg['debug'] ?? 0);

    if (
        $host === '' ||
        $username === '' ||
        $password === '' ||
        $port <= 0 ||
        $fromEmail === '' ||
        !filter_var($fromEmail, FILTER_VALIDATE_EMAIL)
    ) {
        $out['error'] = 'smtp_config_invalid';
        return $out;
    }

define('CASE_URL', 'https://hlg.hamdanlegalgroup.ae/HLG-Justice-Hub/case_public.php');
$link = CASE_URL . '?code=' . urlencode($code);
    try {
        $mail = new PHPMailer(true);

        $mail->isSMTP();
        $mail->Host       = $host;
        $mail->SMTPAuth   = true;
        $mail->Username   = $username;
        $mail->Password   = $password;
        $mail->Port       = $port;
        $mail->Timeout    = 30;

        if ($port === 465) {
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        } else {
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        }

        $mail->SMTPOptions = [
            'ssl' => [
                'verify_peer'       => false,
                'verify_peer_name'  => false,
                'allow_self_signed' => true,
            ],
        ];

        if ($debug > 0) {
            $mail->SMTPDebug = $debug;
            $mail->Debugoutput = static function ($str, $level) use (&$out): void {
                $out['debug'] .= '[SMTP ' . $level . '] ' . $str . "\n";
            };
        }

        $mail->CharSet = 'UTF-8';
        $mail->setFrom($fromEmail, $fromName !== '' ? $fromName : 'Hamdan Legal Group');
        $mail->addAddress($to);

        if ($replyTo !== '' && filter_var($replyTo, FILTER_VALIDATE_EMAIL)) {
            $mail->addReplyTo($replyTo);
        }

        $safeCaseNo = htmlspecialchars($caseNo, ENT_QUOTES, 'UTF-8');
        $safeCode   = htmlspecialchars($code, ENT_QUOTES, 'UTF-8');
        $safeLink   = htmlspecialchars($link, ENT_QUOTES, 'UTF-8');

        $mail->isHTML(true);
        $mail->Subject = 'متابعة قضيتك - رقم القضية: ' . $caseNo;

        $mail->Body = '
        <div style="direction:rtl;text-align:right;font-family:Tajawal,Arial,sans-serif;background:#f8fbfc;padding:24px;color:#1f2937;line-height:1.9;">
          <div style="max-width:650px;margin:0 auto;background:#ffffff;border:1px solid #e5e7eb;border-radius:16px;overflow:hidden;">
            <div style="background:#00424f;padding:20px 24px;color:#ffffff;font-size:22px;font-weight:700;">
              مجموعة حمدان القانونية
            </div>

            <div style="padding:24px;">
              <p style="margin:0 0 14px;">تم تسجيل قضيتك بنجاح.</p>

              <p style="margin:0 0 10px;">
                رقم القضية:
                <strong>' . $safeCaseNo . '</strong>
              </p>

              <p style="margin:0 0 20px;">
                كود المتابعة:
                <strong>' . $safeCode . '</strong>
              </p>

              <p style="margin:0 0 22px;">
                يمكنك متابعة القضية عبر الرابط التالي:
              </p>

              <p style="margin:0 0 24px;">
                <a href="' . $safeLink . '" style="display:inline-block;padding:12px 22px;background:#d4af37;color:#111827;text-decoration:none;border-radius:10px;font-weight:700;">
                  متابعة القضية
                </a>
              </p>

              <p style="margin:0 0 10px;font-size:14px;color:#6b7280;">
                أو انسخ الرابط التالي وافتحه في المتصفح:
              </p>

              <p style="margin:0;font-size:14px;word-break:break-all;">
                <a href="' . $safeLink . '" style="color:#006a7a;text-decoration:none;">' . $safeLink . '</a>
              </p>
            </div>
          </div>
        </div>';

        $mail->AltBody =
            "تم تسجيل قضيتك بنجاح.\n\n" .
            "رقم القضية: {$caseNo}\n" .
            "كود المتابعة: {$code}\n" .
            "رابط المتابعة: {$link}\n";

        $mail->send();

        $out['ok'] = true;
        return $out;
    } catch (Throwable $e) {
        $out['error'] = $e->getMessage();
        return $out;
    }
}