<?php
require_once __DIR__.'/../includes/functions.php'; $admin=require_admin(); verify_csrf(); mj_ensure_listing_module_schema(true); mj263_schema(); $adminTitle='Listing Revisions';
if(isset($_POST['action'],$_POST['revision_id'])){
  $rid=(int)$_POST['revision_id']; $rev=one('SELECT * FROM mj_listing_revisions WHERE id=? LIMIT 1',[$rid]);
  if(!$rev){ flash('error','Revision not found.'); redirect('listing-revisions.php'); }
  $listing=one('SELECT * FROM mj_listings WHERE id=? LIMIT 1',[(int)$rev['listing_id']]);
  $new=json_decode((string)$rev['new_data_json'],true) ?: []; $newImages=json_decode((string)($rev['new_images_json']??'[]'),true) ?: []; $delImages=json_decode((string)($rev['deleted_images_json']??'[]'),true) ?: [];
  if($_POST['action']==='approve'){
    $sets=[];$params=[]; foreach($new as $k=>$v){ if(mj_column_exists('mj_listings',$k)){ $sets[]="`$k`=?"; $params[]=$v; } }
    if(mj_column_exists('mj_listings','status')){ $sets[]='status=?'; $params[]='active'; }
    if(mj_column_exists('mj_listings','approved_at')){ $sets[]='approved_at=NOW()'; }
    if(mj_column_exists('mj_listings','approved_by')){ $sets[]='approved_by=?'; $params[]=$admin['id']; }
    if(mj_column_exists('mj_listings','updated_at')) $sets[]='updated_at=NOW()';
    if (!$sets) throw new Exception('No editable listing columns found. Please run latest migration.');
    $params[]=(int)$rev['listing_id']; q('UPDATE mj_listings SET '.implode(',',$sets).' WHERE id=?',$params);
    foreach($delImages as $imageId){ mj263_delete_listing_image((int)$imageId,(int)$rev['listing_id']); }
    foreach($newImages as $i=>$path){ if($path && table_exists('mj_listing_images')) q('INSERT INTO mj_listing_images(listing_id,image_path,sort_order) VALUES(?,?,?)',[(int)$rev['listing_id'],$path,100+$i]); }
    q('UPDATE mj_listing_revisions SET status="approved",admin_id=?,admin_note=?,reviewed_at=NOW() WHERE id=?',[$admin['id'],$_POST['admin_note']??'',$rid]);
    mj_listing_log((int)$rev['listing_id'],'revision_approved',$listing ?: [],$new); if(!empty($rev['user_id'])) mj263_notify((int)$rev['user_id'],null,'listing_revision_approved','Listing edit approved','Your listing edit has been approved: '.($new['title']??($listing['title']??'')),'my-listings.php','normal',true); flash('success','Revision approved and public listing updated.');
  } elseif($_POST['action']==='reject') {
    q('UPDATE mj_listing_revisions SET status="rejected",admin_id=?,reject_reason=?,admin_note=?,reviewed_at=NOW() WHERE id=?',[$admin['id'],$_POST['reject_reason']??'Rejected by admin',$_POST['admin_note']??'',$rid]);
    mj_listing_log((int)$rev['listing_id'],'revision_rejected',$listing ?: [],['reject_reason'=>$_POST['reject_reason']??'']); if(!empty($rev['user_id'])) mj263_notify((int)$rev['user_id'],null,'listing_revision_rejected','Listing edit rejected','Reason: '.($_POST['reject_reason']??'Rejected by admin'),'my-listings.php','normal',true); flash('success','Revision rejected.');
  }
  redirect('listing-revisions.php');
}
$status=$_GET['status']??'pending'; $rows=all_rows('SELECT r.*,l.title,u.name user_name FROM mj_listing_revisions r LEFT JOIN mj_listings l ON l.id=r.listing_id LEFT JOIN mj_users u ON u.id=r.user_id WHERE r.status=? ORDER BY r.id DESC LIMIT 300',[$status]);
include __DIR__.'/_header.php';
?>
<div class="card card-warning card-outline"><div class="card-header"><h3 class="card-title"><i class="fas fa-code-branch mr-2"></i>Listing Edit Approvals</h3><div class="card-tools"><a class="btn btn-sm btn-secondary" href="listings.php">Listings</a></div></div><div class="card-body"><?php show_flash(); ?><form class="mb-3"><select name="status" class="form-control" style="max-width:220px" onchange="this.form.submit()"><?php foreach(['pending','approved','rejected','cancelled'] as $s): ?><option value="<?=$s?>" <?=$status===$s?'selected':''?>><?=ucfirst($s)?></option><?php endforeach; ?></select></form><?php if(!$rows): ?><div class="alert alert-info">No revisions found.</div><?php else: foreach($rows as $r): $old=json_decode((string)$r['old_data_json'],true)?:[]; $new=json_decode((string)$r['new_data_json'],true)?:[]; $oldImgs=json_decode((string)($r['old_images_json']??'[]'),true)?:[]; $newImgs=json_decode((string)($r['new_images_json']??'[]'),true)?:[]; $delImgs=json_decode((string)($r['deleted_images_json']??'[]'),true)?:[]; ?><div class="card mb-3"><div class="card-header"><b>#<?=e($r['listing_id'])?> <?=e($r['title']??'Listing')?></b><span class="badge badge-warning ml-2"><?=e($r['status'])?></span><small class="text-muted float-right">Submitted by <?=e($r['user_name']??'User')?> • <?=e($r['submitted_at'])?></small></div><div class="card-body"><div class="row"><div class="col-md-6"><h6>Current Public Version</h6><table class="table table-sm"><?php foreach(['title','price','description','category_id','country_id','city_id','condition_label'] as $k): ?><tr><th><?=e($k)?></th><td><?=e(mb_strimwidth((string)($old[$k]??''),0,160,'...'))?></td></tr><?php endforeach; ?></table><h6>Current Photos</h6><div class="d-flex flex-wrap"><?php foreach($oldImgs as $src): ?><img src="<?=e(base_url($src))?>" class="mr-2 mb-2 rounded border" style="width:90px;height:70px;object-fit:cover;<?=in_array($src,$delImgs,true)?'opacity:.35':''?>"><?php endforeach; ?></div></div><div class="col-md-6"><h6>Requested New Version</h6><table class="table table-sm"><?php foreach(['title','price','description','category_id','country_id','city_id','condition_label'] as $k): ?><tr class="<?=($old[$k]??null)!==($new[$k]??null)?'table-warning':''?>"><th><?=e($k)?></th><td><?=e(mb_strimwidth((string)($new[$k]??''),0,160,'...'))?></td></tr><?php endforeach; ?></table><h6>New Photos Pending</h6><div class="d-flex flex-wrap"><?php foreach($newImgs as $src): ?><img src="<?=e(base_url($src))?>" class="mr-2 mb-2 rounded border" style="width:90px;height:70px;object-fit:cover"><?php endforeach; ?></div><?php if($delImgs): ?><div class="alert alert-warning py-2">User requested delete for <?=count($delImgs)?> photo(s).</div><?php endif; ?></div></div><?php if($status==='pending'): ?><form method="post" class="mt-2"><?=csrf_input()?><input type="hidden" name="revision_id" value="<?=e($r['id'])?>"><div class="form-row"><div class="col-md-5"><input class="form-control" name="admin_note" placeholder="Admin note"></div><div class="col-md-4"><input class="form-control" name="reject_reason" placeholder="Reject reason"></div><div class="col-md-3"><button class="btn btn-success" name="action" value="approve">Approve</button> <button class="btn btn-danger" name="action" value="reject">Reject</button></div></div></form><?php endif; ?></div></div><?php endforeach; endif; ?></div></div>
<?php include __DIR__.'/_footer.php'; ?>
