<?php
declare(strict_types=1);

/*
|--------------------------------------------------------------------------
| OTP SENDER
|--------------------------------------------------------------------------
| إرسال رمز التحقق OTP عبر:
| - email باستخدام PHPMailer + SMTP
| - phone (placeholder لربط SMS API لاحقاً)
|--------------------------------------------------------------------------
*/

/* ===== تحميل PHPMailer من المسار الموجود فعليًا ===== */
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;
use PHPMailer\PHPMailer\Exception;

/*
|--------------------------------------------------------------------------
| إعدادات الإرسال
|--------------------------------------------------------------------------
*/
if (!defined('OTP_SENDER_NAME')) {
    define('OTP_SENDER_NAME', 'Hamdan Legal Group');
}

if (!defined('OTP_SENDER_EMAIL')) {
    define('OTP_SENDER_EMAIL', 'no-reply@hamdanlegalgroup.ae');
}

if (!defined('OTP_EMAIL_SUBJECT')) {
    define('OTP_EMAIL_SUBJECT', 'رمز التحقق لتوقيع العقد');
}

if (!defined('OTP_SMTP_HOST')) {
    define('OTP_SMTP_HOST', 'mail.hamdanlegalgroup.ae');
}

if (!defined('OTP_SMTP_PORT')) {
    define('OTP_SMTP_PORT', 465);
}

if (!defined('OTP_SMTP_SECURE')) {
    define('OTP_SMTP_SECURE', PHPMailer::ENCRYPTION_SMTPS);
}

if (!defined('OTP_SMTP_USERNAME')) {
    define('OTP_SMTP_USERNAME', 'no-reply@hamdanlegalgroup.ae');
}

if (!defined('OTP_SMTP_PASSWORD')) {
    define('OTP_SMTP_PASSWORD', 'Saif1979s');
}

/*
|--------------------------------------------------------------------------
| دوال مساعدة
|--------------------------------------------------------------------------
*/
if (!function_exists('otp_sender_build_message_ar')) {
    function otp_sender_build_message_ar(string $code, string $name = ''): string
    {
        $hello = $name !== '' ? "مرحباً {$name}،" : "مرحباً،";

        return $hello . "\n\n"
            . "رمز التحقق الخاص بتوقيع العقد هو:\n"
            . $code . "\n\n"
            . "مدة صلاحية الرمز: 10 دقائق.\n"
            . "يرجى عدم مشاركة هذا الرمز مع أي شخص.\n\n"
            . OTP_SENDER_NAME;
    }
}

if (!function_exists('otp_sender_build_message_en')) {
    function otp_sender_build_message_en(string $code, string $name = ''): string
    {
        $hello = $name !== '' ? "Hello {$name}," : "Hello,";

        return $hello . "\n\n"
            . "Your OTP code for contract signing is:\n"
            . $code . "\n\n"
            . "This code is valid for 10 minutes.\n"
            . "Please do not share this code with anyone.\n\n"
            . OTP_SENDER_NAME;
    }
}

if (!function_exists('otp_sender_build_html')) {
    function otp_sender_build_html(string $code, string $name = ''): string
    {
        $safeName = htmlspecialchars($name, ENT_QUOTES, 'UTF-8');
        $safeCode = htmlspecialchars($code, ENT_QUOTES, 'UTF-8');
        $safeBrand = htmlspecialchars(OTP_SENDER_NAME, ENT_QUOTES, 'UTF-8');

        $helloAr = $safeName !== '' ? "مرحباً {$safeName}" : 'مرحباً';
        $helloEn = $safeName !== '' ? "Hello {$safeName}" : 'Hello';

        return <<<HTML
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>رمز التحقق لتوقيع العقد</title>
</head>
<body style="margin:0;padding:0;background:#f4f7f8;font-family:Tahoma,Arial,sans-serif;direction:rtl;">
  <div style="max-width:640px;margin:30px auto;padding:20px;">
    <div style="background:#ffffff;border:1px solid #e5ecef;border-radius:18px;overflow:hidden;box-shadow:0 10px 30px rgba(0,66,79,.08);">
      
      <div style="background:linear-gradient(135deg,#00424f,#006a7a);padding:24px 28px;color:#ffffff;">
        <div style="font-size:22px;font-weight:700;">{$safeBrand}</div>
        <div style="margin-top:8px;font-size:15px;opacity:.95;">رمز التحقق لتوقيع العقد</div>
      </div>

      <div style="padding:28px;">
        <div style="font-size:16px;color:#17323a;line-height:2;">
          {$helloAr}<br><br>
          رمز التحقق الخاص بتوقيع العقد هو:
        </div>

        <div style="margin:22px 0;padding:18px;border-radius:14px;background:#f2f6f7;border:1px solid #d8e5e8;text-align:center;font-size:34px;letter-spacing:8px;font-weight:700;color:#00424f;">
          {$safeCode}
        </div>

        <div style="font-size:14px;color:#4b5d63;line-height:2;">
          مدة صلاحية الرمز: <strong>10 دقائق</strong><br>
          يرجى عدم مشاركة هذا الرمز مع أي شخص.
        </div>

        <div style="margin:28px 0;border-top:1px solid #e9eef0;"></div>

        <div dir="ltr" style="text-align:left;font-size:14px;color:#4b5d63;line-height:2;">
          <strong style="font-size:16px;color:#17323a;">{$helloEn},</strong><br><br>
          Your OTP code for contract signing is:
        </div>

        <div dir="ltr" style="margin:22px 0;padding:18px;border-radius:14px;background:#f2f6f7;border:1px solid #d8e5e8;text-align:center;font-size:34px;letter-spacing:8px;font-weight:700;color:#00424f;">
          {$safeCode}
        </div>

        <div dir="ltr" style="text-align:left;font-size:14px;color:#4b5d63;line-height:2;">
          This code is valid for <strong>10 minutes</strong>.<br>
          Please do not share this code with anyone.
        </div>

        <div style="margin-top:28px;font-size:13px;color:#7b8b90;">
          {$safeBrand}
        </div>
      </div>
    </div>
  </div>
</body>
</html>
HTML;
    }
}

if (!function_exists('otp_sender_build_alt_body')) {
    function otp_sender_build_alt_body(string $code, string $name = ''): string
    {
        $bodyAr = otp_sender_build_message_ar($code, $name);
        $bodyEn = otp_sender_build_message_en($code, $name);

        return $bodyAr . "\n\n------------------------------\n\n" . $bodyEn;
    }
}

if (!function_exists('otp_sender_send_email_smtp')) {
    function otp_sender_send_email_smtp(
        string $to,
        string $subject,
        string $htmlBody,
        ?string $altBody = null,
        ?string &$error = null
    ): bool {
        $mail = new PHPMailer(true);

        try {
            $mail->isSMTP();
            $mail->Host       = OTP_SMTP_HOST;
            $mail->SMTPAuth   = true;
            $mail->Username   = OTP_SMTP_USERNAME;
            $mail->Password   = OTP_SMTP_PASSWORD;
            $mail->SMTPSecure = OTP_SMTP_SECURE;
            $mail->Port       = OTP_SMTP_PORT;
            $mail->CharSet    = 'UTF-8';

            $mail->setFrom(OTP_SENDER_EMAIL, OTP_SENDER_NAME);
            $mail->addAddress($to);

            $mail->Subject = $subject;
            $mail->Body    = $htmlBody;
            $mail->AltBody = $altBody ?? strip_tags(str_replace(['<br>', '<br/>', '<br />'], "\n", $htmlBody));
            $mail->isHTML(true);

            return $mail->send();
        } catch (Exception $e) {
            $error = $mail->ErrorInfo ?: $e->getMessage();
            return false;
        }
    }
}
if (!function_exists('otp_sender_send_sms_placeholder')) {
    function otp_sender_send_sms_placeholder(string $phone, string $message): bool
    {
        return false;
    }
}

/*
|--------------------------------------------------------------------------
| الدالة الرئيسية المستخدمة في signing.php
|--------------------------------------------------------------------------
*/
if (!function_exists('send_contract_otp')) {
    function send_contract_otp(array $payload): bool
    {
        $channel = trim((string)($payload['channel'] ?? ''));
        $to      = trim((string)($payload['to'] ?? ''));
        $code    = trim((string)($payload['code'] ?? ''));
        $name    = trim((string)($payload['name'] ?? ''));

        if ($channel === '' || $to === '' || $code === '') {
            return false;
        }

        if ($channel === 'email') {
            if (!filter_var($to, FILTER_VALIDATE_EMAIL)) {
                return false;
            }

            $subject = OTP_EMAIL_SUBJECT;
            $htmlBody = otp_sender_build_html($code, $name);
            $altBody  = otp_sender_build_alt_body($code, $name);

            $smtpError = null;
            return otp_sender_send_email_smtp($to, $subject, $htmlBody, $altBody, $smtpError);
        }

        if ($channel === 'phone') {
            $message = "رمز التحقق لتوقيع العقد: {$code} - " . OTP_SENDER_NAME;
            return otp_sender_send_sms_placeholder($to, $message);
        }

        return false;
    }
}