<?php
/**
 * reviewer_mailer.php
 * ─────────────────────────────────────────────────────────────
 * Drop this file in your /reviewer/config/ (or any shared dir).
 * Include it in submission_review.php BEFORE the POST handlers.
 *
 * Usage:
 *   require_once __DIR__ . '/config/reviewer_mailer.php';
 *   sendReviewerInvitation($reviewerEmail, $reviewerName, $data);
 *   sendReviewerReminder($reviewerEmail, $reviewerName, $data);
 *
 * $data keys expected:
 *   title, abstract, journal_name, response_due_date,
 *   review_due_date, access_key, submission_id, base_url
 *
 * HOW IT WORKS:
 *   1. Tries PHP mail() (works on most shared hosts).
 *   2. Falls back gracefully — errors are logged, never crash the page.
 *   3. The $data['access_key'] value is the link that auto-logs the reviewer in.
 * ─────────────────────────────────────────────────────────────
 */

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

// ── Send review invitation email ─────────────────────────────
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_name  = htmlspecialchars($data['journal_name']  ?? 'Communeglobal Journal', 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_name = htmlspecialchars($to_name ?: 'Reviewer', ENT_QUOTES, 'UTF-8');

    $access_url = buildReviewerAccessUrl(
        $data['access_key']    ?? '',
        (int)($data['submission_id'] ?? 0),
        $data['base_url'] ?? ''
    );

    $subject = "Review Invitation: {$title} — {$journal_name}";

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

  <!-- Header -->
  <tr>
    <td style='background:linear-gradient(135deg,#1d4ed8,#4f46e5);padding:32px 32px 28px;'>
      <table cellpadding='0' cellspacing='0' width='100%'>
        <tr>
          <td>
            <div style='width:40px;height:40px;background:rgba(255,255,255,0.2);border-radius:10px;display:inline-block;text-align:center;line-height:40px;'>
              <span style='color:white;font-weight:900;font-size:16px;font-family:Georgia,serif;'>C</span>
            </div>
          </td>
          <td style='padding-left:12px;'>
            <div style='color:rgba(255,255,255,0.9);font-size:13px;font-weight:700;'>Communeglobal Journals</div>
            <div style='color:rgba(255,255,255,0.6);font-size:11px;'>Peer Review System</div>
          </td>
        </tr>
      </table>
      <h1 style='margin:20px 0 0;color:#ffffff;font-size:18px;font-weight:700;line-height:1.4;'>
        📩 Peer Review Invitation
      </h1>
    </td>
  </tr>

  <!-- Body -->
  <tr>
    <td style='padding:28px 32px;'>
      <p style='margin:0 0 16px;color:#374151;font-size:14px;line-height:1.6;'>
        Dear <strong>{$reviewer_name}</strong>,
      </p>
      <p style='margin:0 0 20px;color:#374151;font-size:14px;line-height:1.6;'>
        We are pleased to invite you to review the following manuscript submitted to <strong>{$journal_name}</strong>.
        Your expertise makes you an ideal reviewer for this work.
      </p>

      <!-- Manuscript box -->
      <table width='100%' cellpadding='0' cellspacing='0' style='background:#f8fafc;border:1px solid #e2e8f0;border-radius:12px;margin-bottom:24px;overflow:hidden;'>
        <tr><td style='padding:18px 20px;'>
          <div style='font-size:11px;font-weight:700;color:#6b7280;text-transform:uppercase;letter-spacing:0.5px;margin-bottom:6px;'>Manuscript Title</div>
          <div style='font-size:15px;font-weight:700;color:#1e293b;line-height:1.4;margin-bottom:16px;'>{$title}</div>
          <table width='100%' cellpadding='0' cellspacing='0'>
            <tr>
              <td width='50%' style='padding-right:12px;'>
                <div style='font-size:11px;font-weight:700;color:#6b7280;text-transform:uppercase;letter-spacing:0.5px;margin-bottom:3px;'>Response Due</div>
                <div style='font-size:13px;font-weight:600;color:#1d4ed8;'>{$resp_due}</div>
              </td>
              <td width='50%'>
                <div style='font-size:11px;font-weight:700;color:#6b7280;text-transform:uppercase;letter-spacing:0.5px;margin-bottom:3px;'>Review Due</div>
                <div style='font-size:13px;font-weight:600;color:#1d4ed8;'>{$review_due}</div>
              </td>
            </tr>
          </table>
        </td></tr>
      </table>

      " . ($abstract ? "
      <!-- Abstract -->
      <div style='margin-bottom:24px;'>
        <div style='font-size:11px;font-weight:700;color:#6b7280;text-transform:uppercase;letter-spacing:0.5px;margin-bottom:8px;'>Abstract</div>
        <div style='font-size:13px;color:#4b5563;line-height:1.7;border-left:3px solid #3b82f6;padding-left:14px;'>{$abstract}</div>
      </div>" : "") . "

      <!-- CTA -->
      <div style='text-align:center;margin:28px 0;'>
        <a href='{$access_url}'
           style='display:inline-block;background:linear-gradient(135deg,#059669,#10b981);color:#ffffff;text-decoration:none;
                  padding:14px 36px;border-radius:12px;font-size:15px;font-weight:700;letter-spacing:0.3px;'>
          ✅ Accept &amp; Access Manuscript
        </a>
      </div>

      <p style='margin:0 0 8px;color:#374151;font-size:13px;line-height:1.6;'>
        Or use this link to view the full invitation page (accept, decline, or access your dashboard):
      </p>
      <div style='background:#f1f5f9;border:1px solid #e2e8f0;border-radius:8px;padding:10px 14px;margin-bottom:24px;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 6px;color:#6b7280;font-size:13px;'>
        If you are <strong>unable to review</strong> this manuscript, please use the link above to decline the invitation at your earliest convenience.
      </p>
    </td>
  </tr>

  <!-- Footer -->
  <tr>
    <td style='background:#f8fafc;border-top:1px solid #e2e8f0;padding:18px 32px;text-align:center;'>
      <p style='margin:0;color:#9ca3af;font-size:11px;'>
        © " . date('Y') . " Communeglobal International Journals. All rights reserved.<br>
        <a href='mailto:editorial.office@communeglobal.com' style='color:#6b7280;'>editorial.office@communeglobal.com</a>
      </p>
    </td>
  </tr>

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

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

// ── Send reminder email ───────────────────────────────────────
function sendReviewerReminder(
    string $to_email,
    string $to_name,
    array  $data
): bool {
    $title         = htmlspecialchars($data['title']        ?? 'Untitled Manuscript', ENT_QUOTES, 'UTF-8');
    $journal_name  = htmlspecialchars($data['journal_name'] ?? 'Communeglobal Journal', 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_name = htmlspecialchars($to_name ?: 'Reviewer', ENT_QUOTES, 'UTF-8');
    $access_url    = buildReviewerAccessUrl(
        $data['access_key']    ?? '',
        (int)($data['submission_id'] ?? 0),
        $data['base_url'] ?? ''
    );
    $subject = "Reminder: Review Due — {$title}";

    $body = "<!DOCTYPE html>
<html lang='en'><head><meta charset='UTF-8'></head>
<body style='margin:0;padding:0;background:#f1f5f9;font-family:Arial,sans-serif;'>
<table width='100%' cellpadding='0' cellspacing='0' border='0' style='background:#f1f5f9;'>
<tr><td align='center' style='padding:32px 16px;'>
<table width='100%' style='max-width:580px;background:#ffffff;border-radius:16px;border:1px solid #e2e8f0;' cellpadding='0' cellspacing='0'>
  <tr>
    <td style='background:linear-gradient(135deg,#b45309,#d97706);padding:28px 32px;'>
      <h1 style='margin:0;color:#ffffff;font-size:18px;font-weight:700;'>
        ⏰ Gentle Reminder
      </h1>
      <p style='margin:8px 0 0;color:rgba(255,255,255,0.85);font-size:13px;'>{$journal_name}</p>
    </td>
  </tr>
  <tr><td style='padding:28px 32px;'>
    <p style='margin:0 0 16px;color:#374151;font-size:14px;line-height:1.6;'>Dear <strong>{$reviewer_name}</strong>,</p>
    <p style='margin:0 0 16px;color:#374151;font-size:14px;line-height:1.6;'>
      This is a gentle reminder that we are awaiting your review for the manuscript:
    </p>
    <div style='background:#fffbeb;border:1px solid #fde68a;border-radius:10px;padding:16px 18px;margin-bottom:20px;'>
      <div style='font-size:15px;font-weight:700;color:#1e293b;line-height:1.4;margin-bottom:8px;'>{$title}</div>
      <div style='font-size:13px;color:#92400e;font-weight:600;'>Review due: {$review_due}</div>
    </div>
    <div style='text-align:center;margin:24px 0;'>
      <a href='{$access_url}' style='display:inline-block;background:#d97706;color:#ffffff;text-decoration:none;padding:12px 32px;border-radius:10px;font-size:14px;font-weight:700;'>
        Access Manuscript
      </a>
    </div>
    <p style='margin:0;color:#6b7280;font-size:12px;line-height:1.6;'>
      If you are unable to complete this review, please <a href='{$access_url}' style='color:#2563eb;'>click here</a> to decline so we can reassign in time.
    </p>
  </td></tr>
  <tr><td style='background:#f8fafc;border-top:1px solid #e2e8f0;padding:16px 32px;text-align:center;'>
    <p style='margin:0;color:#9ca3af;font-size:11px;'>© " . date('Y') . " Communeglobal International Journals</p>
  </td></tr>
</table>
</td></tr>
</table>
</body></html>";

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

// ── Internal: actual mail() call ─────────────────────────────
function _sendHtmlMail(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;
    }

    $from_name  = 'Communeglobal Editorial Office';
    $from_email = 'noreply@communeglobal.com'; // ← change to your verified sender address

    $headers  = "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=UTF-8\r\n";
    $headers .= "From: {$from_name} <{$from_email}>\r\n";
    $headers .= "Reply-To: editorial.office@communeglobal.com\r\n";
    $headers .= "X-Mailer: PHP/" . PHP_VERSION . "\r\n";

    // Encode name in subject to handle special chars
    $encoded_subject = '=?UTF-8?B?' . base64_encode($subject) . '?=';

    try {
        $sent = mail($to_email, $encoded_subject, $body, $headers);
        if (!$sent) {
            error_log("reviewer_mailer: mail() returned false for $to_email — subject: $subject");
        }
        return $sent;
    } catch (Throwable $e) {
        error_log("reviewer_mailer: exception sending to $to_email — " . $e->getMessage());
        return false;
    }
}


/*
═══════════════════════════════════════════════════════════════════
  HOW TO INTEGRATE INTO submission_review.php
═══════════════════════════════════════════════════════════════════

1) At the top of submission_review.php, add:
   require_once __DIR__ . '/config/reviewer_mailer.php';

──────────────────────────────────────────────────────────────────
2) In the "POST: Assign existing reviewer" block, AFTER the INSERT
   into review_assignments, add:

    // ── Send invitation email ──────────────────────────────
    try {
        $emailStmt = db()->prepare("
            SELECT u.first_name, u.last_name, u.email,
                   j.name AS journal_name,
                   mi.article_title AS title,
                   mi.abstract
            FROM users u
            JOIN reviewers rv ON rv.user_id = u.user_id
            LEFT JOIN submissions s  ON s.submission_id = ?
            LEFT JOIN journals j     ON j.journal_id = s.journal_id
            LEFT JOIN manuscript_info mi ON mi.submission_id = s.submission_id
            WHERE rv.id = ?
            LIMIT 1
        ");
        $emailStmt->execute([$sid, $reviewer_id]);
        $emailData = $emailStmt->fetch(PDO::FETCH_ASSOC);

        if ($emailData && !empty($emailData['email'])) {
            sendReviewerInvitation(
                $emailData['email'],
                trim(($emailData['first_name'] ?? '') . ' ' . ($emailData['last_name'] ?? '')),
                [
                    'title'              => $emailData['title']        ?? '',
                    'abstract'           => $emailData['abstract']     ?? '',
                    'journal_name'       => $emailData['journal_name'] ?? '',
                    'response_due_date'  => $resp_due,
                    'review_due_date'    => $review_due,
                    'access_key'         => $access_key,
                    'submission_id'      => $sid,
                ]
            );
        }
    } catch (Exception $emailEx) {
        error_log('Reviewer invitation email error: ' . $emailEx->getMessage());
        // non-fatal — assignment was saved successfully
    }
    // ── End email ──────────────────────────────────────────

──────────────────────────────────────────────────────────────────
3) In the "POST: Create new reviewer + assign" block, AFTER commit(),
   add the SAME block above (replace $reviewer_id with the new one).

──────────────────────────────────────────────────────────────────
4) For the reminder email (optional), wherever you handle reminder
   sending, call:

    sendReviewerReminder(
        $reviewer_email,
        $reviewer_name,
        [
            'title'          => $title,
            'journal_name'   => $journal_name,
            'review_due_date'=> $review_due_date,
            'access_key'     => $access_key,
            'submission_id'  => $sid,
        ]
    );

═══════════════════════════════════════════════════════════════════
*/