<?php
/**
 * FILE: admin/reviewer_profile_approvals_detail.php
 * AJAX partial — loads inside the diff modal
 * Returns HTML fragment (no full page)
 */
ini_set('display_errors', 0);
session_start();
require_once __DIR__ . '/../../common/journal_config_new.php';

if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    echo '<div class="text-danger p-4">Unauthorized</div>'; exit;
}

$id = (int)($_GET['id'] ?? 0);
if (!$id) { echo '<div class="text-danger p-4">Invalid ID</div>'; exit; }

$stmt = $pdo->prepare("
    SELECT rpp.*,
           u.first_name, u.last_name, u.title AS user_title, u.institutional_email,
           u.personal_email, u.country AS user_country, u.created_at AS member_since,
           a.name AS affil_name, a.city AS affil_city, a.country AS affil_country,
           r.reviewer_rating, r.total_reviews_completed, r.is_available,
           GROUP_CONCAT(rt.title ORDER BY rt.title SEPARATOR ', ') AS research_areas
    FROM reviewer_public_profile rpp
    JOIN users u ON u.user_id = rpp.user_id
    JOIN reviewers r ON r.id = rpp.reviewer_id
    LEFT JOIN affiliations a ON a.affiliation_id = COALESCE(rpp.profile_affiliation_id, u.affiliation_id)
    LEFT JOIN user_research_interests uri ON uri.user_id = u.user_id
    LEFT JOIN research_topics rt ON rt.topic_id = uri.topic_id AND uri.source IN ('manual','auto_suggested')
    WHERE rpp.id = ?
    GROUP BY rpp.id
");
$stmt->execute([$id]);
$p = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$p) { echo '<div class="text-danger p-4">Profile not found</div>'; exit; }

$pending  = $p['pending_changes'] ? json_decode($p['pending_changes'], true) : null;
$isUpdate = !empty($pending);

// Helper: render field diff row
function diffRow(string $label, $live, $pend, bool $changed): string {
    $html = '<div class="diff-field px-4">';
    $html .= '<div class="diff-label">' . htmlspecialchars($label) . '</div>';
    if ($changed) {
        $html .= '<div class="row g-2"><div class="col-md-6">';
        $html .= '<div style="font-size:.7rem;font-weight:600;color:#991b1b;margin-bottom:3px;">CURRENT (Live)</div>';
        $html .= '<div class="diff-old">' . nl2br(htmlspecialchars((string)$live ?: '(empty)')) . '</div>';
        $html .= '</div><div class="col-md-6">';
        $html .= '<div style="font-size:.7rem;font-weight:600;color:#166534;margin-bottom:3px;">PENDING (New)</div>';
        $html .= '<div class="diff-new">' . nl2br(htmlspecialchars((string)$pend ?: '(empty)')) . '</div>';
        $html .= '</div></div>';
    } else {
        $html .= '<div class="diff-same">' . nl2br(htmlspecialchars((string)$live ?: '<em>—</em>')) . '</div>';
    }
    $html .= '</div>';
    return $html;
}

$fields = [
    'bio'                   => 'Bio',
    'current_position'      => 'Current Position',
    'total_experience_yrs'  => 'Years of Experience',
    'h_index'               => 'H-Index',
    'total_citations'       => 'Total Citations',
    'orcid_id'              => 'ORCID ID',
    'website_url'           => 'Website URL',
    'reviewing_interests'   => 'Reviewing Interests',
];
?>
<style>
.diff-field { border-bottom:1px solid #e2e8f0; padding:10px 24px; }
.diff-field:last-child { border-bottom:none; }
.diff-label { font-size:.72rem; font-weight:600; text-transform:uppercase; letter-spacing:.06em; color:#64748b; margin-bottom:4px; }
.diff-old { background:#fef2f2; border-radius:6px; padding:6px 10px; font-size:.85rem; color:#991b1b; white-space:pre-wrap; }
.diff-new { background:#f0fdf4; border-radius:6px; padding:6px 10px; font-size:.85rem; color:#166534; white-space:pre-wrap; }
.diff-same { font-size:.85rem; color:#374151; padding:2px 0; }
</style>

<!-- Header -->
<div class="p-4 border-bottom d-flex justify-content-between align-items-start"
     style="background:#f8fafc;">
  <div>
    <h5 class="mb-1 fw-bold" style="color:#0d2137;">
      <?= htmlspecialchars(($p['user_title']?$p['user_title'].'. ':'').trim($p['first_name'].' '.$p['last_name'])) ?>
    </h5>
    <div style="font-size:.82rem;color:#64748b;">
      <?= htmlspecialchars($p['institutional_email'] ?? $p['personal_email'] ?? '') ?>
      <?php if ($p['affil_name']): ?>
      · <?= htmlspecialchars($p['affil_name']) ?>
      <?php endif; ?>
    </div>
    <div class="mt-1 d-flex gap-2 flex-wrap">
      <?php if ($p['slug']): ?>
      <a href="https://communeglobal.com/reviewer-profile3.php?slug=<?= urlencode($p['slug']) ?>"
         target="_blank" style="font-size:.78rem;" class="text-decoration-none text-primary">
        <i class="fas fa-external-link-alt me-1"></i>View Public Profile
      </a>
      <?php endif; ?>
      <?php if ($p['orcid_id']): ?>
      <a href="https://orcid.org/<?= htmlspecialchars($p['orcid_id']) ?>" target="_blank"
         style="font-size:.78rem;" class="text-decoration-none" style="color:#a6ce39;">
        <img src="https://orcid.org/sites/default/files/images/orcid_16x16.png" style="height:14px;"> <?= htmlspecialchars($p['orcid_id']) ?>
      </a>
      <?php endif; ?>
    </div>
  </div>
  <div class="text-end">
    <?php
    $sBadge = ['pending'=>['warning','fa-clock','Pending'],'approved'=>['success','fa-check-circle','Approved'],
               'rejected'=>['danger','fa-times-circle','Rejected'],'changes_requested'=>['info','fa-edit','Changes Requested']];
    [$sc,$si,$sl] = $sBadge[$p['approval_status']] ?? ['secondary','fa-question','Unknown'];
    ?>
    <span class="badge bg-<?= $sc ?>"><i class="fas <?= $si ?> me-1"></i><?= $sl ?></span>
    <div style="font-size:.72rem;color:#64748b;margin-top:4px;">
      v<?= $p['version'] ?> ·
      <?= $isUpdate ? 'Profile Update' : 'New Profile' ?>
    </div>
    <?php if ($p['submitted_at']): ?>
    <div style="font-size:.72rem;color:#64748b;">
      Submitted: <?= date('d M Y H:i', strtotime($p['submitted_at'])) ?>
    </div>
    <?php endif; ?>
  </div>
</div>

<!-- Stats strip -->
<div class="d-flex gap-4 px-4 py-3 border-bottom" style="background:#fff;">
  <div class="text-center">
    <div style="font-size:1.2rem;font-weight:700;color:#0d2137;"><?= (int)$p['total_reviews_completed'] ?></div>
    <div style="font-size:.72rem;color:#64748b;">Reviews</div>
  </div>
  <div class="text-center">
    <div style="font-size:1.2rem;font-weight:700;color:#2563eb;"><?= number_format((float)$p['reviewer_rating'],1) ?></div>
    <div style="font-size:.72rem;color:#64748b;">Rating</div>
  </div>
  <div class="text-center">
    <div style="font-size:1.2rem;font-weight:700;color:#059669;"><?= (int)$p['h_index'] ?></div>
    <div style="font-size:.72rem;color:#64748b;">H-Index</div>
  </div>
  <div class="text-center">
    <div style="font-size:1.2rem;font-weight:700;color:#7c3aed;"><?= (int)$p['total_citations'] ?></div>
    <div style="font-size:.72rem;color:#64748b;">Citations</div>
  </div>
  <?php if ($p['research_areas']): ?>
  <div class="flex-grow-1">
    <div style="font-size:.72rem;color:#64748b;margin-bottom:4px;">Research Areas</div>
    <div style="font-size:.8rem;"><?= htmlspecialchars($p['research_areas']) ?></div>
  </div>
  <?php endif; ?>
</div>

<?php if ($isUpdate): ?>
<!-- Diff legend -->
<div class="px-4 py-2 border-bottom d-flex gap-3" style="background:#fffbeb;font-size:.78rem;">
  <span><i class="fas fa-info-circle text-warning me-1"></i>
    <strong>Update submission</strong> — highlighted rows show what changed.</span>
  <span class="ms-auto">
    <span style="background:#fef2f2;color:#991b1b;padding:2px 6px;border-radius:4px;">Red = Current live value</span>
    <span style="background:#f0fdf4;color:#166534;padding:2px 6px;border-radius:4px;margin-left:6px;">Green = Proposed new value</span>
  </span>
</div>
<?php endif; ?>

<!-- Fields -->
<?php foreach ($fields as $fk => $flabel):
  $live     = $p[$fk] ?? '';
  $pend_val = $pending[$fk] ?? null;
  $changed  = $isUpdate && array_key_exists($fk, $pending) && $pend_val !== $live;
  if (!$live && !$changed) continue;
  echo diffRow($flabel, $live, $pend_val, $changed);
endforeach; ?>

<!-- Education (JSON) -->
<?php
$edu_live  = $p['education'] ? json_decode($p['education'],true) : [];
$edu_pend  = ($pending && isset($pending['education'])) ? json_decode($pending['education'],true) : null;
$edu_changed = $edu_pend !== null && json_encode($edu_pend) !== json_encode($edu_live);
if ($edu_live || $edu_changed):
?>
<div class="diff-field px-4">
  <div class="diff-label">Education</div>
  <?php if ($edu_changed): ?>
  <div class="row g-2">
    <div class="col-md-6">
      <div style="font-size:.7rem;font-weight:600;color:#991b1b;margin-bottom:3px;">CURRENT</div>
      <?php foreach ((array)$edu_live as $e): ?>
      <div class="diff-old mb-1"><?= htmlspecialchars($e['degree']??'') ?> — <?= htmlspecialchars($e['institution']??'') ?> (<?= htmlspecialchars($e['year']??'') ?>)</div>
      <?php endforeach; ?>
    </div>
    <div class="col-md-6">
      <div style="font-size:.7rem;font-weight:600;color:#166534;margin-bottom:3px;">PENDING</div>
      <?php foreach ((array)$edu_pend as $e): ?>
      <div class="diff-new mb-1"><?= htmlspecialchars($e['degree']??'') ?> — <?= htmlspecialchars($e['institution']??'') ?> (<?= htmlspecialchars($e['year']??'') ?>)</div>
      <?php endforeach; ?>
    </div>
  </div>
  <?php else: ?>
  <?php foreach ((array)$edu_live as $e): ?>
  <div class="diff-same"><?= htmlspecialchars($e['degree']??'') ?> — <?= htmlspecialchars($e['institution']??'') ?> (<?= htmlspecialchars($e['year']??'') ?>)</div>
  <?php endforeach; ?>
  <?php endif; ?>
</div>
<?php endif; ?>

<!-- Publications (JSON) -->
<?php
$pub_live  = $p['publications'] ? json_decode($p['publications'],true) : [];
$pub_pend  = ($pending && isset($pending['publications'])) ? json_decode($pending['publications'],true) : null;
$pub_changed = $pub_pend !== null && json_encode($pub_pend) !== json_encode($pub_live);
if ($pub_live || $pub_changed):
?>
<div class="diff-field px-4">
  <div class="diff-label">Publications (<?= count($pub_changed?$pub_pend:$pub_live) ?>)</div>
  <?php
  $pubs_to_show = $pub_changed ? $pub_pend : $pub_live;
  foreach ((array)$pubs_to_show as $pub):
  ?>
  <div class="<?= $pub_changed?'diff-new':'diff-same' ?> mb-1">
    <?= htmlspecialchars($pub['title']??'Untitled') ?>
    <?php if (!empty($pub['doi'])): ?>
    — <a href="https://doi.org/<?= htmlspecialchars($pub['doi']) ?>" target="_blank" style="font-size:.78rem;"><?= htmlspecialchars($pub['doi']) ?></a>
    <?php endif; ?>
    <?php if (!empty($pub['year'])): ?>(<?= htmlspecialchars($pub['year']) ?>)<?php endif; ?>
  </div>
  <?php endforeach; ?>
</div>
<?php endif; ?>

<!-- Admin note if any -->
<?php if ($p['admin_note']): ?>
<div class="px-4 py-3 border-top" style="background:#fffbeb;">
  <div class="diff-label">Previous Admin Note</div>
  <div style="font-size:.85rem;color:#92400e;"><?= nl2br(htmlspecialchars($p['admin_note'])) ?></div>
</div>
<?php endif; ?>