<?php
/**
 * reviewer_mailer.php
 * ─────────────────────────────────────────────────────────────
 * Sends reviewer emails via Gmail SMTP using PHPMailer.
 * Uses constants already defined in your config:
 *   GMAIL_SMTP_HOST, GMAIL_SMTP_PORT, GMAIL_SMTP_USER,
 *   GMAIL_SMTP_PASS, GMAIL_FROM_EMAIL, GMAIL_FROM_NAME
 *
 * Place this file at:  /admin/config/reviewer_mailer.php
 *
 * Then add ONE line to submission_review.php after require_role():
 *   require_once __DIR__ . '/config/reviewer_mailer.php';
 * ─────────────────────────────────────────────────────────────
 */

/**
 * reviewer_mailer.php
 * Corrected PHPMailer loading for your folder structure
 */

// ── Load PHPMailer ────────────────────────────────────────────
// Your PHPMailer is located at: public_html/reviewer/vendor/phpmailer/phpmailer/

$_pm_loaded = false;

// 1. Try Composer autoload (Recommended - this is usually the best way)
$autoload_paths = [
    __DIR__ . '/../../reviewer/vendor/autoload.php',     // from admin/config/ → reviewer/vendor/
    __DIR__ . '/../reviewer/vendor/autoload.php',
    __DIR__ . '/../../../reviewer/vendor/autoload.php',  // extra safety
    __DIR__ . '/../../vendor/autoload.php',              // if you have vendor in admin too
];

foreach ($autoload_paths as $path) {
    if (file_exists($path)) {
        require_once $path;
        $_pm_loaded = true;
        error_log("PHPMailer loaded successfully via autoload: " . $path);
        break;
    }
}

// 2. Manual fallback (if autoload doesn't work)
if (!$_pm_loaded) {
    $manual_base = __DIR__ . '/../../reviewer/vendor/phpmailer/phpmailer/src';
    if (file_exists($manual_base . '/PHPMailer.php')) {
        require_once $manual_base . '/Exception.php';
        require_once $manual_base . '/PHPMailer.php';
        require_once $manual_base . '/SMTP.php';
        $_pm_loaded = true;
        error_log("PHPMailer loaded manually from: " . $manual_base);
    }
}

// 3. Final check
if (!$_pm_loaded) {
    error_log('CRITICAL ERROR: PHPMailer could not be loaded. Check paths in reviewer_mailer.php');
    // You can uncomment the line below temporarily for testing
    // die("PHPMailer loading failed. Check error log.");
}

// Use the classes
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception as PHPMailerException;

// ── Constants fallback ────────────────────────────────────────
if (!defined('GMAIL_SMTP_HOST'))  define('GMAIL_SMTP_HOST',  'smtp.gmail.com');
if (!defined('GMAIL_SMTP_PORT'))  define('GMAIL_SMTP_PORT',  587);
if (!defined('GMAIL_SMTP_USER'))  define('GMAIL_SMTP_USER',  'editorialoffice@rsis-international.org');
if (!defined('GMAIL_SMTP_PASS'))  define('GMAIL_SMTP_PASS',  'vbawhqzzusdgeahe');
if (!defined('GMAIL_FROM_EMAIL')) define('GMAIL_FROM_EMAIL', GMAIL_SMTP_USER);
if (!defined('GMAIL_FROM_NAME'))  define('GMAIL_FROM_NAME',  'Editorial Office');


// ─────────────────────────────────────────────────────────────
// INTERNAL: Send HTML email via Gmail SMTP
// ─────────────────────────────────────────────────────────────
function _sendHtmlMailSMTP(
    string $to_email,
    string $to_name,
    string $subject,
    string $body
): bool {
    if (!filter_var($to_email, FILTER_VALIDATE_EMAIL)) {
        error_log("reviewer_mailer: invalid email address — $to_email");
        return false;
    }

    try {
        $mail = new PHPMailer(true);

        // Server
        $mail->isSMTP();
        $mail->Host       = GMAIL_SMTP_HOST;
        $mail->SMTPAuth   = true;
        $mail->Username   = GMAIL_SMTP_USER;
        $mail->Password   = GMAIL_SMTP_PASS;
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port       = GMAIL_SMTP_PORT;
        $mail->CharSet    = PHPMailer::CHARSET_UTF8;

        // Addresses
        $mail->setFrom(GMAIL_FROM_EMAIL, GMAIL_FROM_NAME);
        $mail->addAddress($to_email, $to_name ?: $to_email);
        $mail->addReplyTo(GMAIL_FROM_EMAIL, GMAIL_FROM_NAME);

        // Content
        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body    = $body;
        $mail->AltBody = wordwrap(
            strip_tags(str_replace(['<br>', '<br/>', '<br />', '</p>', '</div>'], "\n", $body)),
            80
        );

        $mail->send();
        return true;

    } catch (PHPMailerException $e) {
        error_log("reviewer_mailer SMTP error → $to_email | " . $e->getMessage());
        return false;
    } catch (\Throwable $e) {
        error_log("reviewer_mailer unexpected error → $to_email | " . $e->getMessage());
        return false;
    }
}


// ─────────────────────────────────────────────────────────────
// Build reviewer access URL
// ─────────────────────────────────────────────────────────────
function buildReviewerAccessUrl(string $access_key, int $submission_id, string $base_url = ''): string
{
    if (!$base_url) {
        $scheme   = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
        $base_url = $scheme . '://' . ($_SERVER['HTTP_HOST'] ?? 'communeglobal.com');
    }
    return rtrim($base_url, '/')
         . '/reviewer/reviewer_access.php'
         . '?access_key='    . urlencode($access_key)
         . '&submission_id=' . (int)$submission_id;
}


// ─────────────────────────────────────────────────────────────
// PUBLIC: Send review INVITATION email
// ─────────────────────────────────────────────────────────────
/**
 * @param string $to_email     Reviewer's email address
 * @param string $to_name      Reviewer's full name
 * @param array  $data {
 *   title, abstract, journal_name,
 *   response_due_date (Y-m-d), review_due_date (Y-m-d),
 *   access_key, submission_id,
 *   base_url (optional, auto-detected if empty)
 * }
 * @return bool  true = email sent, false = failed (check error log)
 */
function sendReviewerInvitation(string $to_email, string $to_name, array $data): bool
{
    $title      = htmlspecialchars($data['title']        ?? 'Untitled Manuscript', ENT_QUOTES, 'UTF-8');
    $abstract   = htmlspecialchars($data['abstract']     ?? '',                    ENT_QUOTES, 'UTF-8');
    $journal    = htmlspecialchars($data['journal_name'] ?? 'RSIS International',  ENT_QUOTES, 'UTF-8');
    $resp_due   = !empty($data['response_due_date'])
                    ? date('d M Y', strtotime($data['response_due_date']))
                    : 'As soon as possible';
    $review_due = !empty($data['review_due_date'])
                    ? date('d M Y', strtotime($data['review_due_date']))
                    : 'TBA';
    $reviewer   = htmlspecialchars($to_name ?: 'Reviewer', ENT_QUOTES, 'UTF-8');
    $access_url = buildReviewerAccessUrl(
        $data['access_key']   ?? '',
        (int)($data['submission_id'] ?? 0),
        $data['base_url'] ?? ''
    );

    $from_email = GMAIL_FROM_EMAIL;
    $year       = date('Y');

    $subject = "Article Review Request – {$journal}";

    $body = <<<HTML
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"></head>
<body style="margin:0;padding:0;background:#f1f5f9;font-family:Arial,Helvetica,sans-serif;">
<table width="100%" cellpadding="0" cellspacing="0" border="0" style="background:#f1f5f9;padding:32px 0;">
<tr><td align="center">
<table width="100%" style="max-width:640px;background:#ffffff;border-radius:12px;border:1px solid #e2e8f0;overflow:hidden;" cellpadding="0" cellspacing="0">

  <!-- HEADER -->
  <tr>
    <td style="background:linear-gradient(135deg,#1d4ed8 0%,#4f46e5 100%);padding:32px 36px 28px;">
      <table cellpadding="0" cellspacing="0">
        <tr>
          <td style="width:44px;height:44px;background:rgba(255,255,255,0.18);border-radius:10px;text-align:center;vertical-align:middle;">
            <span style="color:#fff;font-size:22px;font-weight:900;font-family:Georgia,serif;line-height:44px;">R</span>
          </td>
          <td style="padding-left:12px;">
            <div style="color:rgba(255,255,255,0.95);font-size:14px;font-weight:700;">RSIS International</div>
            <div style="color:rgba(255,255,255,0.60);font-size:11px;">Peer Review System</div>
          </td>
        </tr>
      </table>
      <h1 style="margin:20px 0 4px;color:#ffffff;font-size:20px;font-weight:700;line-height:1.3;">
        &#9993; Peer Review Invitation
      </h1>
      <p style="margin:0;color:rgba(255,255,255,0.75);font-size:13px;">{$journal}</p>
    </td>
  </tr>

  <!-- BODY -->
  <tr>
    <td style="padding:32px 36px;">

      <p style="margin:0 0 16px;color:#374151;font-size:14px;line-height:1.75;">
        Dear <strong style="color:#1e293b;">{$reviewer}</strong>,
      </p>
      <p style="margin:0 0 24px;color:#374151;font-size:14px;line-height:1.75;">
        We are pleased to invite you to review a manuscript submitted to
        <strong>{$journal}</strong>. Your expertise in this field makes you
        an ideal reviewer for this work, and we hope you will be able to accept
        this invitation.
      </p>

      <!-- Manuscript details box -->
      <table width="100%" cellpadding="0" cellspacing="0"
             style="background:#f8fafc;border:1px solid #e2e8f0;border-radius:10px;margin-bottom:24px;">
        <tr>
          <td style="padding:20px 22px;">
            <div style="font-size:10px;font-weight:700;color:#6b7280;text-transform:uppercase;
                        letter-spacing:0.8px;margin-bottom:6px;">Manuscript Title</div>
            <div style="font-size:15px;font-weight:700;color:#1e293b;line-height:1.4;
                        margin-bottom:18px;">{$title}</div>
            <table width="100%" cellpadding="0" cellspacing="0">
              <tr>
                <td width="50%" style="padding-right:8px;">
                  <div style="background:#fff;border:1px solid #e2e8f0;border-radius:8px;padding:12px 14px;">
                    <div style="font-size:10px;font-weight:700;color:#6b7280;
                                text-transform:uppercase;letter-spacing:0.6px;margin-bottom:4px;">Response Due</div>
                    <div style="font-size:13px;font-weight:700;color:#1d4ed8;">{$resp_due}</div>
                  </div>
                </td>
                <td width="50%">
                  <div style="background:#fff;border:1px solid #e2e8f0;border-radius:8px;padding:12px 14px;">
                    <div style="font-size:10px;font-weight:700;color:#6b7280;
                                text-transform:uppercase;letter-spacing:0.6px;margin-bottom:4px;">Review Due</div>
                    <div style="font-size:13px;font-weight:700;color:#1d4ed8;">{$review_due}</div>
                  </div>
                </td>
              </tr>
            </table>
          </td>
        </tr>
      </table>
HTML;

    // Abstract (only if present)
    if ($abstract) {
        $body .= <<<HTML
      <div style="margin-bottom:24px;">
        <div style="font-size:10px;font-weight:700;color:#6b7280;text-transform:uppercase;
                    letter-spacing:0.8px;margin-bottom:8px;">Abstract</div>
        <div style="font-size:13px;color:#4b5563;line-height:1.75;border-left:3px solid #3b82f6;
                    padding:12px 14px;background:#f8fafc;border-radius:0 6px 6px 0;">
          {$abstract}
        </div>
      </div>
HTML;
    }

    $body .= <<<HTML
      <!-- Primary CTA button -->
      <table width="100%" cellpadding="0" cellspacing="0" style="margin:28px 0;">
        <tr>
          <td align="center">
            <a href="{$access_url}"
               style="display:inline-block;background:linear-gradient(135deg,#059669,#10b981);
                      color:#ffffff;text-decoration:none;padding:15px 44px;border-radius:10px;
                      font-size:15px;font-weight:700;letter-spacing:0.3px;">
              &#10003;&nbsp;&nbsp;Accept &amp; Access Manuscript
            </a>
          </td>
        </tr>
      </table>

      <!-- Secondary text link -->
      <p style="margin:0 0 6px;color:#374151;font-size:13px;line-height:1.6;">
        You can also <strong>accept, decline, or access your reviewer dashboard</strong>
        using the link below:
      </p>
      <div style="background:#f1f5f9;border:1px solid #e2e8f0;border-radius:8px;
                  padding:10px 14px;margin-bottom:22px;word-break:break-all;">
        <a href="{$access_url}" style="color:#2563eb;font-size:12px;text-decoration:none;">
          {$access_url}
        </a>
      </div>

      <p style="margin:0 0 0;color:#6b7280;font-size:13px;line-height:1.65;">
        If you are <strong>unable to review</strong> this manuscript, please use the
        link above to decline the invitation at your earliest convenience so we can
        arrange an alternative reviewer in time.
      </p>
      <p style="margin:14px 0 0;color:#6b7280;font-size:13px;">
        Thank you for supporting scholarly communication.
      </p>

    </td>
  </tr>

  <!-- FOOTER -->
  <tr>
    <td style="background:#f8fafc;border-top:1px solid #e2e8f0;padding:18px 36px;">
      <table width="100%" cellpadding="0" cellspacing="0">
        <tr>
          <td style="color:#9ca3af;font-size:11px;line-height:1.6;">
            <strong style="color:#6b7280;">RSIS International</strong> — Editorial Office<br>
            <a href="mailto:{$from_email}" style="color:#6b7280;text-decoration:none;">{$from_email}</a>
          </td>
          <td align="right" style="color:#9ca3af;font-size:11px;line-height:1.6;">
            &copy; {$year} RSIS International<br>All rights reserved.
          </td>
        </tr>
      </table>
    </td>
  </tr>

</table>
</td></tr>
</table>
</body>
</html>
HTML;

    return _sendHtmlMailSMTP($to_email, $to_name, $subject, $body);
}


// ─────────────────────────────────────────────────────────────
// PUBLIC: Send review REMINDER email
// ─────────────────────────────────────────────────────────────
/**
 * @param string $to_email
 * @param string $to_name
 * @param array  $data { title, journal_name, review_due_date, access_key, submission_id }
 */
function sendReviewerReminder(string $to_email, string $to_name, array $data): bool
{
    $title      = htmlspecialchars($data['title']        ?? 'Untitled Manuscript', ENT_QUOTES, 'UTF-8');
    $journal    = htmlspecialchars($data['journal_name'] ?? 'RSIS International',  ENT_QUOTES, 'UTF-8');
    $review_due = !empty($data['review_due_date'])
                    ? date('d M Y', strtotime($data['review_due_date']))
                    : 'as soon as possible';
    $reviewer   = htmlspecialchars($to_name ?: 'Reviewer', ENT_QUOTES, 'UTF-8');
    $access_url = buildReviewerAccessUrl(
        $data['access_key']   ?? '',
        (int)($data['submission_id'] ?? 0),
        $data['base_url'] ?? ''
    );

    $from_email = GMAIL_FROM_EMAIL;
    $year       = date('Y');
    $subject    = "Reminder: Review Due – {$title}";

    $body = <<<HTML
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"></head>
<body style="margin:0;padding:0;background:#f1f5f9;font-family:Arial,Helvetica,sans-serif;">
<table width="100%" cellpadding="0" cellspacing="0" border="0" style="background:#f1f5f9;padding:32px 0;">
<tr><td align="center">
<table width="100%" style="max-width:600px;background:#ffffff;border-radius:12px;border:1px solid #e2e8f0;overflow:hidden;" cellpadding="0" cellspacing="0">

  <!-- HEADER -->
  <tr>
    <td style="background:linear-gradient(135deg,#b45309,#d97706);padding:28px 36px;">
      <h1 style="margin:0 0 4px;color:#ffffff;font-size:18px;font-weight:700;">
        &#9200; Gentle Reminder
      </h1>
      <p style="margin:0;color:rgba(255,255,255,0.80);font-size:13px;">{$journal}</p>
    </td>
  </tr>

  <!-- BODY -->
  <tr>
    <td style="padding:28px 36px;">
      <p style="margin:0 0 16px;color:#374151;font-size:14px;line-height:1.75;">
        Dear <strong style="color:#1e293b;">{$reviewer}</strong>,
      </p>
      <p style="margin:0 0 20px;color:#374151;font-size:14px;line-height:1.75;">
        This is a gentle reminder that we are still awaiting your review for:
      </p>

      <!-- Manuscript box -->
      <div style="background:#fffbeb;border:1px solid #fde68a;border-radius:10px;
                  padding:18px 20px;margin-bottom:22px;">
        <div style="font-size:15px;font-weight:700;color:#1e293b;line-height:1.4;
                    margin-bottom:10px;">{$title}</div>
        <div style="font-size:13px;font-weight:700;color:#92400e;">
          &#128197; Review due: {$review_due}
        </div>
      </div>

      <!-- CTA -->
      <table width="100%" cellpadding="0" cellspacing="0" style="margin:22px 0;">
        <tr>
          <td align="center">
            <a href="{$access_url}"
               style="display:inline-block;background:#d97706;color:#ffffff;text-decoration:none;
                      padding:13px 38px;border-radius:10px;font-size:14px;font-weight:700;">
              Access Manuscript
            </a>
          </td>
        </tr>
      </table>

      <p style="margin:0;color:#6b7280;font-size:13px;line-height:1.65;">
        If you are unable to complete this review, please
        <a href="{$access_url}" style="color:#2563eb;">click here to decline</a>
        so we can reassign promptly. We sincerely appreciate your time and expertise.
      </p>
    </td>
  </tr>

  <!-- FOOTER -->
  <tr>
    <td style="background:#f8fafc;border-top:1px solid #e2e8f0;padding:16px 36px;text-align:center;">
      <p style="margin:0;color:#9ca3af;font-size:11px;">
        &copy; {$year} RSIS International &mdash;
        <a href="mailto:{$from_email}" style="color:#6b7280;text-decoration:none;">{$from_email}</a>
      </p>
    </td>
  </tr>

</table>
</td></tr>
</table>
</body>
</html>
HTML;

    return _sendHtmlMailSMTP($to_email, $to_name, $subject, $body);
}