<?php
// author/check_review.php  (public page - no login needed)
error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);
require_once __DIR__ . '/config/db.php';

$review  = null;
$error   = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $code  = strtoupper(trim($_POST['code']  ?? ''));
    $email = strtolower(trim($_POST['email'] ?? ''));

    if (!$code || !$email) {
        $error = "Please enter both Tracking Code and Email.";
    } else {
        // 1. Find submission by tracking_code + verify author email
        $sq = db()->prepare("
            SELECT s.submission_id, s.tracking_code,
                   mi.article_title, mi.running_title
            FROM submissions s
            LEFT JOIN manuscript_info mi ON mi.submission_id = s.submission_id
            JOIN submission_authors sa
                 ON sa.submission_id = s.submission_id
                AND LOWER(sa.email) = ?
            WHERE s.tracking_code = ?
            LIMIT 1
        ");
        $sq->execute([$email, $code]);
        $sub = $sq->fetch(PDO::FETCH_ASSOC);

        if (!$sub) {
            $error = "No record found or email does not match our records.";
        } else {
            // 2. Get LATEST editorial decision only
            $dq = db()->prepare("
                SELECT ed.*,
                       au.first_name AS editor_first,
                       au.last_name  AS editor_last
                FROM editorial_decisions ed
                LEFT JOIN admin_users au ON au.id = ed.editor_id
                WHERE ed.submission_id = ?
                ORDER BY ed.created_at DESC
                LIMIT 1
            ");
            $dq->execute([$sub['submission_id']]);
            $review = $dq->fetch(PDO::FETCH_ASSOC);

            if (!$review) {
                $error = "No editorial decision has been issued for this submission yet.";
            } else {
                // merge submission info into review array
                $review['tracking_code']  = $sub['tracking_code'];
                $review['article_title']  = $sub['article_title'] ?: $sub['running_title'] ?: 'Untitled';
            }
        }
    }
}

// ── helpers ────────────────────────────────────────────────────────
function decisionLabel($d) {
    $map = [
        'accepted'              => ['Accepted',              '#0e7a4f', '#d1fae5'],
        'accepted_with_changes' => ['Accepted with Changes', '#b45309', '#fef3c7'],
        'resubmit'              => ['Resubmit for Review',   '#6d28d9', '#ede9fe'],
        'rejected'              => ['Rejected',              '#b91c1c', '#fee2e2'],
    ];
    return $map[$d] ?? ['Under Review', '#1d4ed8', '#e8effe'];
}
function p($v) { return htmlspecialchars($v ?? '', ENT_QUOTES, 'UTF-8'); }
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Check Review Feedback – Communeglobal</title>
<style>
/* ── reset & base ── */
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
body{font-family:Arial,Helvetica,sans-serif;background:#f0f3f8;color:#111827}

/* ── form card ── */
.wrap{min-height:100vh;display:flex;align-items:center;justify-content:center;padding:32px 16px}
.form-card{background:#fff;border-radius:16px;box-shadow:0 4px 24px rgba(0,0,0,.08);
           padding:36px 32px;width:100%;max-width:480px}
.form-card h2{font-size:1.25rem;font-weight:700;margin-bottom:6px;color:#111827}
.form-card p{font-size:.84rem;color:#6b7280;margin-bottom:24px}
.form-logo{font-size:1.1rem;font-weight:800;color:#1d4ed8;margin-bottom:18px}
label{font-size:.8rem;font-weight:700;color:#374151;display:block;margin-bottom:5px}
input[type=text],input[type=email]{
    width:100%;padding:10px 14px;border:1px solid #d1d5db;border-radius:8px;
    font-size:.9rem;outline:none;margin-bottom:18px;transition:border .2s}
input:focus{border-color:#1d4ed8}
.btn-check{width:100%;padding:12px;background:#1d4ed8;color:#fff;border:none;
           border-radius:8px;font-size:.95rem;font-weight:700;cursor:pointer}
.btn-check:hover{background:#1e40af}
.error-box{background:#fee2e2;border:1px solid #fca5a5;border-radius:8px;
           padding:11px 14px;font-size:.84rem;color:#b91c1c;margin-bottom:18px}

/* ── paper (result) ── */
.paper-wrap{max-width:800px;margin:0 auto;padding:28px 16px 60px}
.paper{background:#fff;border:1px solid #000;border-radius:0;
       padding:14mm 14mm 14mm 14mm;
       font-size:11pt;line-height:1.35;color:#000}

.journal-name{font-size:15pt;font-weight:700;color:#1d4ed8;
              text-align:center;margin-bottom:6px}
.paper-title{font-size:13pt;font-weight:700;text-align:center;margin-bottom:14px}
.paper-meta{font-size:10pt;margin-bottom:6px}
.paper-meta span{font-weight:700}

/* decision badge */
.dec-badge{display:inline-block;padding:6px 22px;border-radius:999px;
           font-size:11pt;font-weight:700;margin:12px auto 16px;
           border:2px solid currentColor}

.divider{border:none;border-top:1px solid #000;margin:12px 0}

/* score boxes */
.scores{display:flex;gap:12px;flex-wrap:wrap;margin:18px 0;justify-content:center}
.score{flex:1;min-width:120px;border:2px solid #000;border-radius:8px;
       padding:10px 8px;text-align:center;font-size:10pt;font-weight:600}
.score .sval{display:inline-block;margin-top:7px;padding:4px 14px;
             border-radius:6px;color:#fff;font-size:9pt;font-weight:700;
             -webkit-print-color-adjust:exact;print-color-adjust:exact}
.sc-orig .sval{background:#1d4ed8}
.sc-pres .sval{background:#0d7a4f}
.sc-appl .sval{background:#b45309;color:#fff}
.sc-over .sval{background:#111827}

/* sections */
.section{margin:16px 0;padding:12px 14px;border:1px solid #000;
         border-radius:6px;background:#f9f9f9;page-break-inside:avoid}
.section h6{font-size:11pt;font-weight:700;margin-bottom:8px;
            padding-left:10px;border-left:5px solid}
.sec-str h6{border-left-color:#0d7a4f;color:#0d7a4f}
.sec-weak h6{border-left-color:#b91c1c;color:#b91c1c}
.sec-sugg h6{border-left-color:#b45309;color:#b45309}
.sec-rec h6{border-left-color:#6d28d9;color:#6d28d9}
.sec-note h6{border-left-color:#1d4ed8;color:#1d4ed8}
.sec-content{font-size:10.5pt;line-height:1.65;text-align:justify;
             white-space:pre-wrap;min-height:36px}

/* final rec pill */
.final-rec{border-radius:50px;padding:14px 24px;text-align:center;
           font-size:17pt;font-weight:700;margin:20px 0 8px;color:#fff;
           -webkit-print-color-adjust:exact;print-color-adjust:exact}

/* due date */
.due-row{text-align:center;font-size:10pt;margin-top:4px}
.overdue{color:#b91c1c;font-weight:700}

/* footer sig */
.sig{margin-top:24px;font-size:9.5pt;color:#444;border-top:1px solid #ccc;
     padding-top:10px}

/* print btn */
.print-bar{text-align:center;margin-top:22px}
.btn-print{padding:12px 32px;background:#0d7a4f;color:#fff;border:none;
           border-radius:8px;font-size:1rem;font-weight:700;cursor:pointer}
.btn-print:hover{background:#065f3f}
.btn-back{padding:12px 24px;background:#fff;color:#1d4ed8;border:2px solid #1d4ed8;
          border-radius:8px;font-size:1rem;font-weight:700;cursor:pointer;margin-right:10px;
          text-decoration:none;display:inline-block}

/* ── print overrides ── */
@media print{
    body{background:#fff}
    .no-print{display:none!important}
    @page{
        size:A4;
        margin:15mm 12mm 15mm 12mm;
    }
    .paper-wrap{padding:0;margin:0}
    .paper{
        border:none;
        padding:0;
        box-shadow:none;
    }
    .section{
        border:0.5mm solid #999!important;
        background:#f9f9f9!important;
        -webkit-print-color-adjust:exact;
        print-color-adjust:exact;
        page-break-inside:avoid;
        margin-bottom:8px;
    }
    .scores{page-break-inside:avoid}
    .final-rec{
        -webkit-print-color-adjust:exact;
        print-color-adjust:exact;
    }
    .dec-badge{
        -webkit-print-color-adjust:exact;
        print-color-adjust:exact;
    }
    .sec-str h6,.sec-weak h6,.sec-sugg h6,.sec-rec h6,.sec-note h6{
        -webkit-print-color-adjust:exact;
        print-color-adjust:exact;
    }
    .score .sval{
        -webkit-print-color-adjust:exact;
        print-color-adjust:exact;
    }
}
</style>
</head>
<body>

<?php if (!$review): ?>
<!-- ════════════════ FORM ════════════════ -->
<div class="wrap">
  <div class="form-card">
    <div class="form-logo">Communeglobal</div>
    <h2>Check Your Review Feedback</h2>
    <p>Enter your manuscript tracking code and corresponding author email to view the editorial decision.</p>

    <?php if ($error): ?>
      <div class="error-box"><?= p($error) ?></div>
    <?php endif; ?>

    <form method="POST">
      <label>Tracking Code</label>
      <input type="text" name="code"
             placeholder="e.g. CIJSS-JS9452"
             value="<?= p($_POST['code'] ?? '') ?>"
             required>

      <label>Author Email</label>
      <input type="email" name="email"
             placeholder="your@email.com"
             value="<?= p($_POST['email'] ?? '') ?>"
             required>

      <button class="btn-check" type="submit">Check Now</button>
    </form>
  </div>
</div>

<?php else:
    [$decLabel, $decColor, $decBg] = decisionLabel($review['decision'] ?? '');
    $editorName = trim(($review['editor_first'] ?? '') . ' ' . ($review['editor_last'] ?? ''));
    $isOverdue  = !empty($review['due_date']) && strtotime($review['due_date']) < time();
?>
<!-- ════════════════ RESULT PAPER ════════════════ -->
<div class="paper-wrap">

  <!-- back + print buttons -->
  <div class="print-bar no-print" style="margin-bottom:18px;text-align:left">
    <a href="check_review.php" class="btn-back">← Check Another</a>
  </div>

  <div class="paper">
    <div class="journal-name">Communeglobal International Journal of Social Sciences</div>
    <div class="paper-title">Editorial Review Result</div>
    <hr class="divider">

    <div class="paper-meta"><span>Tracking Code:</span> <?= p($review['tracking_code']) ?></div>
    <div class="paper-meta"><span>Title:</span> <?= p($review['article_title']) ?></div>
    <?php if ($editorName): ?>
    <div class="paper-meta"><span>Reviewed by:</span> <?= p($editorName) ?></div>
    <?php endif; ?>
    <div class="paper-meta"><span>Decision Date:</span>
        <?= date('F j, Y', strtotime($review['created_at'])) ?></div>

    <div style="text-align:center;margin:14px 0">
      <span class="dec-badge"
            style="color:<?= $decColor ?>;background:<?= $decBg ?>;border-color:<?= $decColor ?>">
        <?= $decLabel ?>
      </span>
    </div>

    <hr class="divider">

    <!-- SCORES -->
    <?php if ($review['originality'] || $review['presentation'] || $review['applicability'] || $review['overall_status']): ?>
    <div class="scores">
      <div class="score sc-orig">
        Originality<br>
        <span class="sval"><?= p($review['originality'] ?: '—') ?></span>
      </div>
      <div class="score sc-pres">
        Presentation<br>
        <span class="sval"><?= p($review['presentation'] ?: '—') ?></span>
      </div>
      <div class="score sc-appl">
        Applicability<br>
        <span class="sval"><?= p($review['applicability'] ?: '—') ?></span>
      </div>
      <div class="score sc-over">
        Overall Status<br>
        <span class="sval"><?= p($review['overall_status'] ?: '—') ?></span>
      </div>
    </div>
    <hr class="divider">
    <?php endif; ?>

    <!-- STRENGTHS -->
    <?php if (trim((string)$review['strengths'])): ?>
    <div class="section sec-str">
      <h6>✅ Strengths</h6>
      <div class="sec-content"><?= p(trim($review['strengths'])) ?></div>
    </div>
    <?php endif; ?>

    <!-- WEAKNESSES -->
    <?php if (trim((string)$review['weaknesses'])): ?>
    <div class="section sec-weak">
      <h6>⚠️ Weaknesses</h6>
      <div class="sec-content"><?= p(trim($review['weaknesses'])) ?></div>
    </div>
    <?php endif; ?>

    <!-- SUGGESTIONS -->
    <?php if (trim((string)$review['suggestions'])): ?>
    <div class="section sec-sugg">
      <h6>💡 Suggestions</h6>
      <div class="sec-content"><?= p(trim($review['suggestions'])) ?></div>
    </div>
    <?php endif; ?>

    <!-- RECOMMENDATION -->
    <?php if (trim((string)$review['recommendation'])): ?>
    <div class="section sec-rec">
      <h6>📋 Recommendation</h6>
      <div class="sec-content"><?= p(trim($review['recommendation'])) ?></div>
    </div>
    <?php endif; ?>

    <!-- EDITOR NOTE -->
    <?php if (trim((string)$review['editor_comments'])): ?>
    <div class="section sec-note">
      <h6>✉️ Editor's Note to Author</h6>
      <div class="sec-content"><?= nl2br(p(trim($review['editor_comments']))) ?></div>
    </div>
    <?php endif; ?>

    <!-- FINAL DECISION PILL -->
    <div style="text-align:center;margin-top:20px">
      <div style="font-weight:700;font-size:11pt;margin-bottom:8px">Final Decision</div>
      <div class="final-rec"
           style="background:<?= $decColor ?>;display:inline-block;
                  min-width:260px;border-radius:50px">
        <?= $decLabel ?>
      </div>
    </div>

    <!-- REVISION DUE DATE -->
    <?php if (!empty($review['due_date'])): ?>
    <div class="due-row <?= $isOverdue ? 'overdue' : '' ?>">
      Revision due: <strong><?= date('F j, Y', strtotime($review['due_date'])) ?></strong>
      <?= $isOverdue ? ' ⚠ Overdue' : '' ?>
    </div>
    <?php endif; ?>

    <!-- SIGNATURE -->
    <div class="sig">
      <strong>Communeglobal</strong> – International Journal of Social Sciences<br>
      This document is auto-generated on <?= date('F j, Y') ?>. 
      For queries, contact the editorial office.
    </div>
  </div><!-- /.paper -->

  <div class="print-bar no-print">
    <a href="check_review.php" class="btn-back">← Check Another</a>
    <button class="btn-print" onclick="window.print()">🖨 Print / Save PDF</button>
  </div>

</div><!-- /.paper-wrap -->

<?php endif; ?>
</body>
</html>