<?php
require_once __DIR__.'/../includes/functions.php';
$admin=require_admin(); verify_csrf(); mj_deal_ensure_schema(); mj_review_ensure_schema();
$adminTitle='Deal Update Reviews'; $adminSubtitle='Review seller deal changes before they replace the live deal page.';
if($_SERVER['REQUEST_METHOD']==='POST'){
    $rid=(int)($_POST['revision_id']??0); $action=(string)($_POST['action']??'');
    try{
        $rev=one('SELECT * FROM mj_deal_revisions WHERE id=? LIMIT 1',[$rid]);
        if(!$rev) throw new RuntimeException('Revision not found.');
        if($rev['status']!=='pending') throw new RuntimeException('This revision was already reviewed.');
        if($action==='approve'){
            mj_review_apply_deal($rev,(int)$admin['id'],trim((string)($_POST['admin_note']??'')));
            flash('success','Deal update approved and live deal updated.');
        } elseif($action==='reject'){
            $reason=trim((string)($_POST['reject_reason']??'')); if($reason==='') $reason='Please review and update the submitted deal information.';
            q('UPDATE mj_deal_revisions SET status="rejected", admin_id=?, reject_reason=?, admin_note=?, reviewed_at=NOW() WHERE id=?',[(int)$admin['id'],$reason,trim((string)($_POST['admin_note']??'')),$rid]);
            if(!empty($rev['user_id'])) mj263_notify((int)$rev['user_id'],null,'deal_revision_rejected','Deal update rejected','Reason: '.$reason,'my-deals.php','high',true);
            admin_log('deal_revision_rejected','mj_deal_revisions',$rid,['deal_id'=>(int)$rev['deal_id'],'reason'=>$reason]);
            flash('success','Deal update rejected.');
        }
    }catch(Throwable $e){ flash('error',$e->getMessage()); }
    redirect('deal-revisions.php');
}
$status=$_GET['status']??'pending';
$rows=[];
try{
    $rows=all_rows('SELECT r.*,d.title deal_title,u.name user_name,u.email user_email FROM mj_deal_revisions r LEFT JOIN mj_deals d ON d.id=r.deal_id LEFT JOIN mj_users u ON u.id=r.user_id WHERE r.status=? ORDER BY r.id DESC LIMIT 200',[$status]);
}catch(Throwable $e){}
include __DIR__.'/_header.php';
$fields=['title'=>'Title','short_description'=>'Short description','description'=>'Description','deal_type'=>'Type','original_price'=>'Original price','deal_price'=>'Offer price','currency_code'=>'Currency','price_note'=>'Price note','country_id'=>'Country','city_id'=>'City','category_id'=>'Category','company_id'=>'Company','start_at'=>'Start','end_at'=>'End','contact_phone'=>'Phone','contact_whatsapp'=>'WhatsApp','contact_email'=>'Email','terms'=>'Terms','image_path'=>'Image'];
?>
<div class="card card-warning card-outline">
  <div class="card-header"><h3 class="card-title"><i class="fas fa-fire mr-2"></i>Deal Update Reviews</h3><div class="card-tools"><a class="btn btn-sm btn-secondary" href="deals.php">Deals</a> <a class="btn btn-sm btn-info" href="action-queue.php">Action Queue</a></div></div>
  <div class="card-body">
    <div class="alert alert-info"><b>No checkout/payment:</b> Deals remain display and enquiry only. Approving only updates the public deal content.</div>
    <form class="mb-3"><select name="status" class="form-control" style="max-width:240px" onchange="this.form.submit()"><?php foreach(['pending','approved','rejected','cancelled'] as $s): ?><option value="<?=e($s)?>" <?=$status===$s?'selected':''?>><?=e(ucfirst($s))?></option><?php endforeach; ?></select></form>
    <?php if(!$rows): ?><div class="alert alert-light border text-center py-4">No deal update reviews found.</div><?php endif; ?>
    <?php foreach($rows as $r): $old=json_decode((string)$r['old_data_json'],true)?:[]; $new=json_decode((string)$r['new_data_json'],true)?:[]; ?>
      <div class="card mb-3 shadow-sm">
        <div class="card-header bg-light"><b>#<?=e($r['deal_id'])?> <?=e($r['deal_title'] ?: ($old['title'] ?? 'Deal'))?></b><span class="badge badge-warning ml-2"><?=e($r['status'])?></span><small class="float-right text-muted">Submitted by <?=e($r['user_name'] ?: 'User')?> • <?=e($r['submitted_at'])?></small></div>
        <div class="card-body">
          <div class="row">
            <div class="col-lg-6"><h6 class="font-weight-bold">Current Live Version</h6><?php if(!empty($old['image_path'])): ?><img src="../<?=e($old['image_path'])?>" class="rounded border mb-2" style="max-width:180px;max-height:110px;object-fit:cover"><?php endif; ?><table class="table table-sm table-bordered"><tbody><?php foreach($fields as $k=>$label): ?><tr><th style="width:140px"><?=e($label)?></th><td><?=e(mj_review_short($old[$k] ?? '', 220))?></td></tr><?php endforeach; ?></tbody></table></div>
            <div class="col-lg-6"><h6 class="font-weight-bold">Requested New Version</h6><?php if(!empty($new['image_path'])): ?><img src="../<?=e($new['image_path'])?>" class="rounded border mb-2" style="max-width:180px;max-height:110px;object-fit:cover"><?php endif; ?><table class="table table-sm table-bordered"><tbody><?php foreach($fields as $k=>$label): $changed=(string)($old[$k]??'') !== (string)($new[$k]??''); ?><tr class="<?=$changed?'table-warning':''?>"><th style="width:140px"><?=e($label)?></th><td><?=e(mj_review_short($new[$k] ?? '', 220))?></td></tr><?php endforeach; ?></tbody></table></div>
          </div>
          <?php if($status==='pending'): ?><form method="post" class="border-top pt-3 mt-2"><?=csrf_input()?><input type="hidden" name="revision_id" value="<?=e($r['id'])?>"><div class="form-row"><div class="col-md-4 mb-2"><input class="form-control" name="admin_note" placeholder="Admin note"></div><div class="col-md-4 mb-2"><input class="form-control" name="reject_reason" placeholder="Reject reason"></div><div class="col-md-4 mb-2"><button class="btn btn-success" name="action" value="approve" onclick="return confirm('Approve this deal update?')"><i class="fas fa-check mr-1"></i>Approve Update</button> <button class="btn btn-danger" name="action" value="reject" onclick="return confirm('Reject this deal update?')"><i class="fas fa-times mr-1"></i>Reject</button></div></div></form><?php endif; ?>
        </div>
      </div>
    <?php endforeach; ?>
  </div>
</div>
<?php include __DIR__.'/_footer.php'; ?>
