<?php
// author/editor_review.php
// URL: /author/editor_review.php?id=28
error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);
require_once __DIR__ . '/config/db.php';
startSession();
$user    = getCurrentUser();
$user_id = $user['user_id'];

// ── Get & validate submission_id from URL ──────────────────────────
$sid = (int)($_GET['id'] ?? 0);
if (!$sid) { header('Location: projects.php'); exit; }

// ── Security: make sure this submission belongs to the logged-in author ──
$q = db()->prepare(
    "SELECT s.submission_id, s.tracking_code, s.submission_status,
            s.created_at AS submitted_at,
            mi.article_title, mi.running_title, mi.abstract,
            sp.name      AS specialty_name,
            at.name      AS article_type_name,
            j.name       AS journal_name
     FROM submissions s
     LEFT JOIN manuscript_info mi ON mi.submission_id = s.submission_id
     LEFT JOIN specialties     sp ON sp.specialty_id  = s.specialty_id
     LEFT JOIN article_types   at ON at.article_type_id = s.article_type_id
     LEFT JOIN journals         j ON j.journal_id      = s.journal_id
     WHERE s.submission_id = ? AND s.user_id = ?
     LIMIT 1"
);
$q->execute([$sid, $user_id]);
$sub = $q->fetch(PDO::FETCH_ASSOC);
if (!$sub) { header('Location: projects.php'); exit; }

// ── Fetch ONLY the latest editorial decision ──────────────────────
$dq = db()->prepare(
    "SELECT ed.*,
            au.first_name AS editor_first,
            au.last_name  AS editor_last,
            au.role       AS editor_role
     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([$sid]);
$decision = $dq->fetch(PDO::FETCH_ASSOC);

// ── Helpers ───────────────────────────────────────────────────────
function decisionInfo($d) {
    $map = array(
        'accepted'              => array('Accepted',              '#0e7a4f', '#d1fae5', '&#10003;'),
        'accepted_with_changes' => array('Accepted with Changes', '#b45309', '#fef3c7', '&#9998;'),
        'resubmit'              => array('Resubmit',              '#6d28d9', '#ede9fe', '&#8635;'),
        'rejected'              => array('Rejected',              '#b91c1c', '#fee2e2', '&#10007;'),
    );
    return isset($map[$d]) ? $map[$d] : array('Under Review', '#1a56db', '#e8effe', '&hellip;');
}

function ratingBar($val) {
    $map = array('Very Poor'=>10,'Poor'=>25,'Fair'=>45,'Good'=>60,'Very Good'=>78,'Excellent'=>90,'Outstanding'=>100);
    $pct = isset($map[$val]) ? $map[$val] : 0;
    $colors = array(
        'Very Poor'=>'#ef4444','Poor'=>'#f97316','Fair'=>'#f59e0b',
        'Good'=>'#84cc16','Very Good'=>'#10b981','Excellent'=>'#0891b2','Outstanding'=>'#6366f1'
    );
    $col = isset($colors[$val]) ? $colors[$val] : '#cbd5e1';
    return "
        <div style='height:5px;background:#edf2f7;border-radius:3px;overflow:hidden;margin-top:4px'>
            <div style='height:100%;width:{$pct}%;background:{$col};border-radius:3px'></div>
        </div>
        <div style='font-size:.68rem;color:{$col};font-weight:700;margin-top:3px'>" . htmlspecialchars($val) . "</div>
    ";
}

function p($v) { return htmlspecialchars($v ?? '', ENT_QUOTES, 'UTF-8'); }

$pageTitle  = 'Editorial Review &mdash; ' . ($sub['tracking_code'] ?: "SUB-$sid");
$activePage = 'projects';
require_once __DIR__ . '/_layout.php';
?>

<style>
:root {
    --c-bg:        #f0f3f8;
    --c-surface:   #ffffff;
    --c-border:    #dce4ef;
    --c-ink:       #111827;
    --c-soft:      #4b5e7a;
    --c-faint:     #8298b4;
    --c-accent:    #1d4ed8;
    --c-accent-lt: #eff6ff;
    --c-green:     #0d7a4f;
    --c-green-lt:  #dcfce7;
    --c-amber:     #b45309;
    --c-amber-lt:  #fef3c7;
    --c-violet:    #6d28d9;
    --c-violet-lt: #ede9fe;
    --c-red:       #be123c;
    --c-red-lt:    #ffe4e6;
    --r:   10px;
    --r-lg: 16px;
    --sh:  0 2px 8px rgba(0,0,0,.06);
}
.er-wrap { color: var(--c-ink); max-width: 960px; padding-bottom: 80px; }

/* breadcrumb */
.er-nav { display:flex; align-items:center; gap:10px; margin-bottom:24px; font-size:.82rem; color:var(--c-faint); }
.er-nav a { color:var(--c-accent); text-decoration:none; font-weight:600; display:flex; align-items:center; gap:4px; }
.er-nav a:hover { text-decoration:underline; }
.er-nav .sep { color:var(--c-border); }
.er-nav .crumb { color:var(--c-soft); font-weight:600; }

/* hero */
.sub-hero { background:var(--c-surface); border:1px solid var(--c-border); border-radius:var(--r-lg); box-shadow:var(--sh); padding:22px 26px 18px; margin-bottom:20px; position:relative; overflow:hidden; }
.sub-hero::before { content:''; position:absolute; top:0; left:0; right:0; height:4px; background:linear-gradient(90deg,#1d4ed8,#7c3aed,#0891b2); }
.sub-hero-row { display:flex; align-items:flex-start; gap:16px; flex-wrap:wrap; margin-bottom:12px; }
.sub-hero-title { flex:1; min-width:0; }
.sub-hero-title h1 { font-size:1.2rem; font-weight:700; color:var(--c-ink); margin:0 0 8px; line-height:1.45; }
.sub-chips { display:flex; flex-wrap:wrap; gap:6px; }
.chip { font-size:.72rem; padding:3px 10px; border-radius:999px; font-weight:600; border:1px solid var(--c-border); background:var(--c-bg); color:var(--c-soft); white-space:nowrap; }
.sub-hero-meta { display:flex; gap:16px; flex-wrap:wrap; font-size:.78rem; color:var(--c-faint); padding-top:12px; border-top:1px solid var(--c-border); }
.sub-hero-meta strong { color:var(--c-soft); font-weight:600; }
.status-badge { display:inline-flex; align-items:center; gap:6px; padding:6px 14px; border-radius:999px; font-size:.8rem; font-weight:700; flex-shrink:0; white-space:nowrap; }
.status-badge::before { content:''; width:7px; height:7px; border-radius:50%; background:currentColor; opacity:.7; }

/* section heading */
.section-head { display:flex; align-items:center; gap:10px; margin-bottom:14px; }
.section-head h2 { font-size:1.05rem; font-weight:700; color:var(--c-ink); margin:0; }
.latest-pill { font-size:.72rem; font-weight:700; padding:2px 9px; border-radius:999px; background:var(--c-accent-lt); color:var(--c-accent); }

/* decision card */
.dec-card { background:var(--c-surface); border:1px solid var(--c-border); border-radius:var(--r-lg); box-shadow:var(--sh); margin-bottom:18px; overflow:hidden; }
.dec-card-header { display:flex; align-items:center; gap:14px; padding:16px 20px; flex-wrap:wrap; border-bottom:1px solid var(--c-border); }
.dec-icon { width:38px; height:38px; border-radius:10px; display:flex; align-items:center; justify-content:center; font-size:1.1rem; font-weight:700; flex-shrink:0; }
.dec-hd-text { flex:1; min-width:0; }
.dec-hd-text h3 { font-size:.95rem; font-weight:700; margin:0 0 4px; }
.dec-meta { display:flex; flex-wrap:wrap; gap:10px; font-size:.75rem; color:var(--c-faint); }
.dec-meta strong { color:var(--c-soft); font-weight:600; }
.dec-meta .overdue { color:var(--c-red); font-weight:700; }

/* scores row */
.scores-row { display:grid; grid-template-columns:repeat(4,1fr); gap:1px; background:var(--c-border); border-bottom:1px solid var(--c-border); }
@media(max-width:540px){ .scores-row { grid-template-columns:repeat(2,1fr); } }
.score-cell { background:var(--c-surface); padding:12px 14px; }
.score-cell .sc-lbl { font-size:.63rem; font-weight:700; text-transform:uppercase; letter-spacing:.5px; color:var(--c-faint); margin-bottom:5px; }

/* decision body */
.dec-body { padding:18px 20px; }
.dec-section { margin-bottom:14px; }
.dec-section:last-child { margin-bottom:0; }
.dec-section-lbl { font-size:.67rem; font-weight:800; text-transform:uppercase; letter-spacing:.7px; color:var(--c-faint); margin-bottom:6px; display:flex; align-items:center; gap:4px; }
.dec-section-text { font-size:.85rem; line-height:1.7; color:var(--c-soft); background:var(--c-bg); border-radius:8px; padding:11px 13px; white-space:pre-wrap; border-left:3px solid var(--c-border); }
.editor-note { background:var(--c-accent-lt); border:1px solid #bfdbfe; border-radius:10px; padding:13px 15px; margin-top:14px; }
.editor-note .en-lbl { font-size:.67rem; font-weight:800; text-transform:uppercase; letter-spacing:.7px; color:var(--c-accent); margin-bottom:6px; }
.editor-note p { font-size:.85rem; line-height:1.65; color:#1e3a8a; margin:0; }

/* empty */
.er-empty { background:var(--c-surface); border:1px dashed var(--c-border); border-radius:var(--r-lg); padding:44px 20px; text-align:center; color:var(--c-faint); margin-bottom:24px; }
.er-empty .ei { font-size:2.2rem; margin-bottom:10px; opacity:.3; }
.er-empty h4 { font-size:.95rem; color:var(--c-soft); margin:0 0 5px; }
.er-empty p  { font-size:.84rem; margin:0; }
</style>

<div class="er-wrap">

    <!-- Breadcrumb -->
    <div class="er-nav">
        <a href="projects.php">
            <svg width="13" height="13" viewBox="0 0 20 20" fill="currentColor">
                <path fill-rule="evenodd" d="M12.707 5.293a1 1 0 010 1.414L9.414 10l3.293 3.293a1 1 0 01-1.414 1.414l-4-4a1 1 0 010-1.414l4-4a1 1 0 011.414 0z" clip-rule="evenodd"/>
            </svg>
            My Projects
        </a>
        <span class="sep">/</span>
        <span><?= p($sub['tracking_code'] ?: "SUB-$sid") ?></span>
        <span class="sep">/</span>
        <span class="crumb">Editorial Review</span>
    </div>

    <!-- Submission hero -->
    <?php
    $statusStyles = array(
        'draft'        => array('Draft',        '#64748b', '#f1f5f9'),
        'submitted'    => array('Submitted',    '#1d4ed8', '#eff6ff'),
        'under_review' => array('Under Review', '#b45309', '#fef3c7'),
        'accepted'     => array('Accepted',     '#0d7a4f', '#dcfce7'),
        'rejected'     => array('Rejected',     '#be123c', '#ffe4e6'),
    );
    $st = isset($statusStyles[$sub['submission_status']]) ? $statusStyles[$sub['submission_status']] : array('Unknown','#64748b','#f1f5f9');
    list($stLabel, $stColor, $stBg) = $st;
    $title = $sub['article_title'] ?: ($sub['running_title'] ?: 'Untitled Submission');
    ?>
    <div class="sub-hero">
        <div class="sub-hero-row">
            <div class="sub-hero-title">
                <h1><?= p($title) ?></h1>
                <div class="sub-chips">
                    <?php if ($sub['journal_name']): ?>
                        <span class="chip">&#128240; <?= p($sub['journal_name']) ?></span>
                    <?php endif; ?>
                    <?php if ($sub['specialty_name']): ?>
                        <span class="chip">&#128300; <?= p($sub['specialty_name']) ?></span>
                    <?php endif; ?>
                    <?php if ($sub['article_type_name']): ?>
                        <span class="chip">&#128196; <?= p($sub['article_type_name']) ?></span>
                    <?php endif; ?>
                </div>
            </div>
            <div class="status-badge" style="color:<?= $stColor ?>;background:<?= $stBg ?>;border:1px solid <?= $stColor ?>33">
                <?= $stLabel ?>
            </div>
        </div>
        <div class="sub-hero-meta">
            <span>Tracking: <strong><?= p($sub['tracking_code'] ?: "SUB-$sid") ?></strong></span>
            <?php if ($sub['submitted_at']): ?>
                <span>Submitted: <strong><?= date('M j, Y', strtotime($sub['submitted_at'])) ?></strong></span>
            <?php endif; ?>
        </div>
    </div>

    <!-- ═══════════════════════════════════
         LATEST EDITORIAL DECISION
    ═══════════════════════════════════ -->
    <div class="section-head">
        <h2>Editorial Decision</h2>
        <?php if ($decision): ?>
            <span class="latest-pill">Latest</span>
        <?php endif; ?>
    </div>

    <?php if (empty($decision)): ?>
    <div class="er-empty">
        <div class="ei">&#9203;</div>
        <h4>No editorial decision yet</h4>
        <p>The editor has not yet issued a decision. It will appear here once available.</p>
    </div>

    <?php else:
        $di_info    = decisionInfo($decision['decision'] ?? '');
        $decLabel   = $di_info[0];
        $decColor   = $di_info[1];
        $decBg      = $di_info[2];
        $decIcon    = $di_info[3];
        $editorName = trim(($decision['editor_first'] ?? '') . ' ' . ($decision['editor_last'] ?? ''));
        $isOverdue  = !empty($decision['due_date']) && strtotime($decision['due_date']) < time();
        $hasScores  = $decision['originality'] || $decision['presentation'] || $decision['applicability'] || $decision['overall_status'];
    ?>
    <div class="dec-card">
        <div class="dec-card-header">
            <div class="dec-icon" style="background:<?= $decBg ?>;color:<?= $decColor ?>"><?= $decIcon ?></div>
            <div class="dec-hd-text">
                <h3 style="color:<?= $decColor ?>"><?= $decLabel ?></h3>
                <div class="dec-meta">
                    <?php if ($editorName): ?>
                        <span>By <strong><?= p($editorName) ?></strong>
                        <?php if ($decision['editor_role']): ?>
                            <span style="opacity:.65">(<?= p(ucfirst($decision['editor_role'])) ?>)</span>
                        <?php endif; ?></span>
                    <?php endif; ?>
                    <span>Issued: <strong><?= date('M j, Y', strtotime($decision['created_at'])) ?></strong></span>
                    <?php if ($decision['due_date']): ?>
                        <span class="<?= $isOverdue ? 'overdue' : '' ?>">
                            Revision due: <strong><?= date('M j, Y', strtotime($decision['due_date'])) ?></strong>
                            <?= $isOverdue ? ' &#9888; Overdue' : '' ?>
                        </span>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <?php if ($hasScores): ?>
        <div class="scores-row">
            <?php
            $scoreFields = array('Originality'=>$decision['originality'],'Presentation'=>$decision['presentation'],'Applicability'=>$decision['applicability'],'Overall'=>$decision['overall_status']);
            foreach ($scoreFields as $sl => $sv):
            ?>
            <div class="score-cell">
                <div class="sc-lbl"><?= $sl ?></div>
                <?php if ($sv): echo ratingBar($sv); else: ?>
                <div style="font-size:.7rem;color:var(--c-border);margin-top:4px">&mdash;</div>
                <?php endif; ?>
            </div>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>

        <div class="dec-body">
            <?php
            $sections = array(
                array('&#9989;',        'Strengths',      $decision['strengths']),
                array('&#9888;&#65039;','Weaknesses',     $decision['weaknesses']),
                array('&#128161;',      'Suggestions',    $decision['suggestions']),
                array('&#128203;',      'Recommendation', $decision['recommendation']),
            );
            foreach ($sections as $s):
                if (!trim((string)$s[2])) continue;
            ?>
            <div class="dec-section">
                <div class="dec-section-lbl"><span><?= $s[0] ?></span><?= $s[1] ?></div>
                <div class="dec-section-text"><?= p(trim($s[2])) ?></div>
            </div>
            <?php endforeach; ?>

            <?php if (trim((string)$decision['editor_comments'])): ?>
            <div class="editor-note">
                <div class="en-lbl">&#9993; Editor's Note to Author</div>
                <p><?= nl2br(p(trim($decision['editor_comments']))) ?></p>
            </div>
            <?php endif; ?>
        </div>
    </div>
    <?php endif; ?>

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

<?php layoutEnd(); ?>