<?php
require_once __DIR__ . '/../includes/mj_v304_bootstrap.php';
require_once __DIR__ . '/../includes/mj_v304_review_helper.php';
mjv304_require_admin();
$adminId = mjv304_current_user_id();
$message='';$error='';
try {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $reviewId=(int)($_POST['review_id'] ?? 0);
        if (isset($_POST['approve'])) { mjv304_apply_review($reviewId, $adminId); $message='Review approved and live item updated.'; }
        if (isset($_POST['reject'])) { mjv304_reject_review($reviewId, $adminId, trim((string)($_POST['reject_reason'] ?? ''))); $message='Review rejected. User notified.'; }
    }
} catch(Throwable $e) { $error=$e->getMessage(); }
$status = trim((string)($_GET['status'] ?? 'pending'));
$type = trim((string)($_GET['type'] ?? ''));
$reviewId = (int)($_GET['review_id'] ?? 0);
$page=max(1,(int)($_GET['page'] ?? 1));$limit=25;$offset=($page-1)*$limit;
$where=['1=1'];$params=[];
if ($status !== '') { $where[]='status=?'; $params[]=$status; }
if ($type !== '') { $where[]='item_type=?'; $params[]=$type; }
if ($reviewId>0) { $where[]='id=?'; $params[]=$reviewId; }
$whereSql=implode(' AND ',$where);
$total=(int)mjv304_fetch_value("SELECT COUNT(*) FROM mj_admin_review_queue WHERE $whereSql", $params);
$rows=mjv304_fetch_all("SELECT * FROM mj_admin_review_queue WHERE $whereSql ORDER BY submitted_at DESC,id DESC LIMIT $limit OFFSET $offset", $params);
$counts=mjv304_fetch_all("SELECT status,COUNT(*) total FROM mj_admin_review_queue GROUP BY status");
$countMap=['pending'=>0,'approved'=>0,'rejected'=>0];foreach($counts as $c){$countMap[$c['status']] = (int)$c['total'];}
?>
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Admin Review Queue</title><link rel="stylesheet" href="../assets/css/mj-v304.css?v=304"></head><body>
<div class="mj-v304-wrap">
  <div class="mj-page-head"><div><h1>Admin Review Queue</h1><p>Approve active listing, company, and deal edits. Old live version stays active until approval.</p></div><div><?php include __DIR__ . '/../includes/mj_v304_notification_widget.php'; ?></div></div>
  <?php if($message): ?><div class="mj-card" style="border-color:#bbf7d0;background:#f0fdf4;margin-bottom:12px;"><?php echo mjv304_e($message); ?></div><?php endif; ?>
  <?php if($error): ?><div class="mj-card" style="border-color:#fecaca;background:#fef2f2;margin-bottom:12px;"><?php echo mjv304_e($error); ?></div><?php endif; ?>
  <div class="mj-grid mj-grid-3" style="margin-bottom:14px;">
    <div class="mj-card"><h3>Pending</h3><div class="num"><?php echo $countMap['pending']; ?></div></div>
    <div class="mj-card"><h3>Approved</h3><div class="num"><?php echo $countMap['approved']; ?></div></div>
    <div class="mj-card"><h3>Rejected</h3><div class="num"><?php echo $countMap['rejected']; ?></div></div>
  </div>
  <form class="mj-card mj-filter" method="get" style="grid-template-columns:1fr 1fr 1fr auto auto;">
    <div><label>Status</label><select name="status"><option value="">All</option><?php foreach(['pending'=>'Pending','approved'=>'Approved','rejected'=>'Rejected'] as $k=>$v): ?><option value="<?php echo $k; ?>" <?php echo $status===$k?'selected':''; ?>><?php echo $v; ?></option><?php endforeach; ?></select></div>
    <div><label>Type</label><select name="type"><option value="">All</option><?php foreach(['listing'=>'Listing','company'=>'Company','deal'=>'Deal'] as $k=>$v): ?><option value="<?php echo $k; ?>" <?php echo $type===$k?'selected':''; ?>><?php echo $v; ?></option><?php endforeach; ?></select></div>
    <div><label>Review ID</label><input name="review_id" value="<?php echo $reviewId ?: ''; ?>"></div>
    <div><label>&nbsp;</label><button class="mj-btn mj-btn-primary">Filter</button></div>
    <div><label>&nbsp;</label><a class="mj-btn" href="review-queue.php">Reset</a></div>
  </form>
  <?php if(!$rows): ?><div class="mj-card mj-empty">No review items found.</div><?php endif; ?>
  <?php foreach($rows as $r): $old=mjv304_decode_json($r['old_data_json']); $new=mjv304_decode_json($r['new_data_json']); $diff=mjv304_diff_rows($old,$new); ?>
    <div class="mj-card" style="margin-bottom:14px;">
      <div class="mj-page-head" style="margin-bottom:8px;"><div><h3><?php echo mjv304_e(ucfirst($r['item_type'])); ?> #<?php echo (int)$r['item_id']; ?> <span class="mj-badge <?php echo mjv304_badge_class($r['status']); ?>"><?php echo mjv304_e($r['status']); ?></span></h3><p>User #<?php echo (int)$r['user_id']; ?> submitted <?php echo mjv304_e(date('d M Y H:i', strtotime($r['submitted_at']))); ?></p></div></div>
      <div class="mj-table-wrap"><table class="mj-table" style="min-width:720px;"><thead><tr><th>Field</th><th>Old Live</th><th>New Submitted</th></tr></thead><tbody>
        <?php if(!$diff): ?><tr><td colspan="3"><div class="mj-empty">No visible difference.</div></td></tr><?php endif; ?>
        <?php foreach($diff as $d): ?><tr><td><b><?php echo mjv304_e($d['field']); ?></b></td><td class="mj-diff-old"><?php echo nl2br(mjv304_e(is_scalar($d['old'])?$d['old']:mjv304_json($d['old']))); ?></td><td class="mj-diff-new"><?php echo nl2br(mjv304_e(is_scalar($d['new'])?$d['new']:mjv304_json($d['new']))); ?></td></tr><?php endforeach; ?>
      </tbody></table></div>
      <?php if($r['status']==='pending'): ?><form method="post" class="mj-actions" style="margin-top:12px;align-items:center;"><input type="hidden" name="review_id" value="<?php echo (int)$r['id']; ?>"><button class="mj-btn mj-btn-success" name="approve" value="1" onclick="return confirm('Approve and publish these changes?')">Approve Changes</button><input name="reject_reason" placeholder="Reject reason" style="min-width:260px;padding:10px;border:1px solid #e8edf5;border-radius:12px;"><button class="mj-btn mj-btn-danger" name="reject" value="1" onclick="return confirm('Reject these changes?')">Reject</button></form><?php endif; ?>
      <?php if($r['reject_reason']): ?><div class="mj-note-box"><b>Reject reason:</b> <?php echo nl2br(mjv304_e($r['reject_reason'])); ?></div><?php endif; ?>
    </div>
  <?php endforeach; ?>
</div>
</body></html>
