<?php
require_once __DIR__ . '/mailer.php';

/**
 * Build an absolute URL for images/links inside emails.
 * e.g. _abs_url('img/logo.jpg') -> https://uofs.edu.sd/admission3/img/logo.jpg
 */
function _abs_url(string $rel): string {
    $host = $_SERVER['HTTP_HOST'] ?? 'nu.edu.sd';
    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $base = rtrim(dirname($_SERVER['SCRIPT_NAME'] ?? '/admission'), '/');
    if ($base === '.' || $base === '/') $base = '';
    return $scheme . '://' . $host . ($base ? $base : '') . '/' . ltrim($rel, '/');
}

/** Fetch student core fields */
function _student_row(mysqli $db, string $student_id): ?array {
    $st = $db->prepare("
        SELECT student_id, student_name, email, phone_number, program_id
        FROM students
        WHERE student_id=? LIMIT 1
    ");
    if (!$st) return null;
    $st->bind_param("s", $student_id);
    $st->execute();
    $row = $st->get_result()->fetch_assoc();
    $st->close();
    return $row ?: null;
}

/**
 * Pretty, brandable email template with logo + bilingual sections.
 * $headlineAr / $headlineEn: main headings
 * $bodyArHtml / $bodyEnHtml: html blocks
 * $ctaText: button caption (Arabic | English ok)
 * $ctaUrl : absolute link target
 */
function _email_template(string $headlineAr, string $headlineEn, string $bodyArHtml, string $bodyEnHtml, string $ctaText, string $ctaUrl): string {
    $LOGO_ABS_URL = _abs_url('img/logo.jpg');     // <-- change if your logo path differs
    $PORTAL_URL   = $ctaUrl;

    // Colors / brand
    $brand = [
        'primary' => '#0d6efd',    // button blue
        'ink'     => '#111827',
        'muted'   => '#6b7280',
        'line'    => '#eef2f7',
        'bg'      => '#f6f9fc',
        'card'    => '#ffffff',
    ];

    // Inline, email-safe CSS (no external CSS files)
    $css = <<<CSS
      body{margin:0;background:{$brand['bg']};-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%;}
      table{border-collapse:collapse}
      img{border:0;max-width:100%;height:auto}
      .wrap{width:100%;background:{$brand['bg']};padding:20px 0}
      .container{width:100%;max-width:600px;margin:0 auto;background:{$brand['card']};border:1px solid {$brand['line']};border-radius:14px;overflow:hidden}
      .header{padding:20px 24px;text-align:center;background:#ffffff}
      .brand-logo{max-height:64px}
      .content{padding:8px 24px 20px 24px}
      h1,h2,h3{margin:0 0 8px 0;color:{$brand['ink']};font-weight:800;line-height:1.25}
      p{margin:8px 0;color:{$brand['ink']};line-height:1.6}
      .rtl{direction:rtl;text-align:right;font-family:'Cairo', Arial, Helvetica, sans-serif !important;}
      .muted{color:{$brand['muted']};font-size:13px}
      .divider{height:1px;background:{$brand['line']};margin:12px 0}
      .btn{display:inline-block;padding:12px 18px;background:{$brand['primary']};color:#fff;text-decoration:none;border-radius:10px;font-weight:700}
      .footer{padding:14px 24px;text-align:center;background:#fff}
      .card{border:1px solid {$brand['line']};border-radius:12px;padding:14px;background:#fff}
      .space{height:10px}
CSS;

    // Use Google Fonts link for Cairo — some clients will ignore, that’s OK.
    $fontLink = '<link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;800&display=swap" rel="stylesheet">';

    return <<<HTML
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
{$fontLink}
<style type="text/css">{$css}</style>
</head>
<body>
  <div class="wrap">
    <table role="presentation" class="container" cellpadding="0" cellspacing="0" width="100%">
      <tr>
        <td class="header">
          <img src="{$LOGO_ABS_URL}" alt="University Logo" class="brand-logo">
        </td>
      </tr>

      <tr>
        <td class="content">
          <!-- Arabic block -->
          <div class="rtl">
            <h2>{$headlineAr}</h2>
            <div class="card">
              {$bodyArHtml}
            </div>
            <div class="space"></div>
            <a href="{$PORTAL_URL}" class="btn">الانتقال إلى البوابة</a>
          </div>

          <div class="divider"></div>

          <!-- English block -->
          <div>
            <h3>{$headlineEn}</h3>
            <div class="card">
              {$bodyEnHtml}
            </div>
            <div class="space"></div>
            <a href="{$PORTAL_URL}" class="btn">Open Portal</a>
          </div>
        </td>
      </tr>

      <tr>
        <td class="footer">
          <p class="muted">This is an automated message from  University Of Technolgy -Admissions.</p>
        </td>
      </tr>
    </table>
  </div>
</body>
</html>
HTML;
}

/** 1) Submission received */
function notify_submission_received(mysqli $db, string $student_id): void {
    $s = _student_row($db, $student_id);
    if (!$s || empty($s['email'])) { error_log("[MAIL] submission_received: no email for $student_id"); return; }

    $name = htmlspecialchars($s['student_name'] ?? '', ENT_QUOTES, 'UTF-8');
    $id   = htmlspecialchars($s['student_id'] ?? '', ENT_QUOTES, 'UTF-8');
    $portal = _abs_url('student_login.php');

    $headlineAr = 'تم استلام طلبك';
    $headlineEn = 'Submission Received';

    $bodyAr = "
      <p>عزيزي/عزيزتي <strong>{$name}</strong>، تم استلام بياناتك بنجاح.</p>
      <p>رقم الطالب: <code>{$id}</code></p>
      <p>سيتم إشعارك بنتيجة المراجعة أو طلب استكمال مستندات إن لزم.</p>
    ";

    $bodyEn = "
      <p>Dear <strong>{$name}</strong>, your profile has been received successfully.</p>
      <p>Student ID: <code>{$id}</code></p>
      <p>We will notify you when the review is complete, or if more documents are required.</p>
    ";

    $html = _email_template($headlineAr, $headlineEn, $bodyAr, $bodyEn, 'الانتقال إلى البوابة | Open Portal', $portal);
    $r = send_email($s['email'], 'تم استلام طلبك | Submission received', $html);
    if (!$r['ok']) error_log('[MAIL] submission_received failed: '.($r['error'] ?? 'unknown'));
}

/** 2) Decision: accepted */
function notify_decision_accepted(mysqli $db, string $student_id): void {
    $s = _student_row($db, $student_id);
    if (!$s || empty($s['email'])) { error_log("[MAIL] decision_accepted: no email for $student_id"); return; }

    $name = htmlspecialchars($s['student_name'] ?? '', ENT_QUOTES, 'UTF-8');
    $id   = htmlspecialchars($s['student_id'] ?? '', ENT_QUOTES, 'UTF-8');
    $portal = _abs_url('student_login.php');

    $headlineAr = 'قبول مبدئي';
    $headlineEn = 'Provisional Acceptance';

    $bodyAr = "
      <p>نبارك لك <strong>{$name}</strong>! تم قبولك مبدئيًا في البرنامج.</p>
      <p>رقم الطالب: <code>{$id}</code></p>
      <p>يرجى متابعة حسابك لاستكمال إجراءات التسجيل وسداد الرسوم.</p>
    ";

    $bodyEn = "
      <p>Congratulations, <strong>{$name}</strong>! You have been provisionally accepted.</p>
      <p>Student ID: <code>{$id}</code></p>
      <p>Please check your portal for next steps and fee payment instructions.</p>
    ";

    $html = _email_template($headlineAr, $headlineEn, $bodyAr, $bodyEn, 'الانتقال إلى البوابة | Open Portal', $portal);
    $r = send_email($s['email'], 'قبول مبدئي | Provisional acceptance', $html);
    if (!$r['ok']) error_log('[MAIL] decision_accepted failed: '.($r['error'] ?? 'unknown'));
}

/** 3) Decision: rejected (includes reason) */
function notify_decision_rejected(mysqli $db, string $student_id, string $reason = ''): void {
    $s = _student_row($db, $student_id);
    if (!$s || empty($s['email'])) { error_log("[MAIL] decision_rejected: no email for $student_id"); return; }

    $name = htmlspecialchars($s['student_name'] ?? '', ENT_QUOTES, 'UTF-8');
    $id   = htmlspecialchars($s['student_id'] ?? '', ENT_QUOTES, 'UTF-8');
    $portal = _abs_url('student_login.php');

    $reasonAr = htmlspecialchars($reason, ENT_QUOTES, 'UTF-8');
    $reasonEn = htmlspecialchars($reason, ENT_QUOTES, 'UTF-8');

    $headlineAr = 'نتيجة القبول';
    $headlineEn = 'Application Decision';

    $bodyAr = "
      <p>نأسف لإبلاغك يا <strong>{$name}</strong> بأن طلبك لم يُقبل في هذه المرحلة.</p>
      <p>رقم الطالب: <code>{$id}</code></p>"
      . ($reasonAr !== '' ? "<p><strong>سبب الرفض:</strong> {$reasonAr}</p>" : "") .
      "<p>يمكنك مراجعة حسابك لمعرفة الخيارات المتاحة أو تحديث بياناتك لاحقًا.</p>";

    $bodyEn = "
      <p>We are sorry to inform you, <strong>{$name}</strong>, that your application was not successful at this time.</p>
      <p>Student ID: <code>{$id}</code></p>"
      . ($reasonEn !== '' ? "<p><strong>Reason:</strong> {$reasonEn}</p>" : "") .
      "<p>Please visit your portal for available options or to update your information in the future.</p>";

    $html = _email_template($headlineAr, $headlineEn, $bodyAr, $bodyEn, 'الانتقال إلى البوابة | Open Portal', $portal);
    $r = send_email($s['email'], 'نتيجة القبول | Application decision', $html);
    if (!$r['ok']) error_log('[MAIL] decision_rejected failed: '.($r['error'] ?? 'unknown'));
}
