<?php
require_once __DIR__.'/../includes/functions.php'; $admin=require_admin(); verify_csrf(); mj263_schema(); mj_listing_paid_upgrade_ensure_schema(); $adminTitle='Listing Renewals';
if(isset($_POST['action'],$_POST['request_id'])){
  $rid=(int)$_POST['request_id']; $req=one('SELECT * FROM mj_listing_renewal_requests WHERE id=? LIMIT 1',[$rid]); if(!$req){flash('error','Request not found.'); redirect('listing-renewals.php');}
  $listing=one('SELECT * FROM mj_listings WHERE id=? LIMIT 1',[(int)$req['listing_id']]);
  if($_POST['action']==='approve'){
    $days=(int)($_POST['days']??$req['requested_days']??30); $custom=trim((string)($_POST['custom_expires_at']??'')); $newExp=$custom?date('Y-m-d H:i:s',strtotime($custom)):date('Y-m-d H:i:s',strtotime('+'.max(1,$days).' days', max(time(), !empty($listing['expires_at'])?strtotime($listing['expires_at']):time())));
    q('UPDATE mj_listings SET expires_at=?, expired_at=NULL, status="active", updated_at=NOW() WHERE id=?',[$newExp,(int)$req['listing_id']]);
    q('UPDATE mj_listing_renewal_requests SET status="approved", admin_id=?, admin_note=?, reviewed_at=NOW(), requested_expires_at=? WHERE id=?',[$admin['id'],$_POST['admin_note']??'',$newExp,$rid]);
    mj_listing_log((int)$req['listing_id'],'renewal_approved',$listing?:[],['expires_at'=>$newExp]); mj263_notify((int)$req['user_id'],null,'listing_renewal_approved','Listing renewal approved','Your listing was renewed until '.$newExp,'my-listings.php','normal',true); flash('success','Renewal approved.');
  } elseif($_POST['action']==='reject'){
    q('UPDATE mj_listing_renewal_requests 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)$req['listing_id'],'renewal_rejected',$listing?:[],['reason'=>$_POST['reject_reason']??'']); mj263_notify((int)$req['user_id'],null,'listing_renewal_rejected','Listing renewal rejected','Reason: '.($_POST['reject_reason']??'Rejected by admin'),'my-listings.php','normal',true); flash('success','Renewal rejected.');
  }
  redirect('listing-renewals.php');
}
$status=$_GET['status']??'pending'; $rows=all_rows('SELECT r.*,l.title,l.expires_at,u.name user_name,u.email FROM mj_listing_renewal_requests 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-primary card-outline"><div class="card-header"><h3 class="card-title"><i class="fas fa-redo mr-2"></i>Listing Renewal Requests</h3><div class="card-tools"><a href="listing-upgrade-settings.php" class="btn btn-sm btn-outline-primary">Charge Settings</a><a href="payment-center.php?tab=review" class="btn btn-sm btn-outline-success ml-1">Payment Proofs</a><a href="listing-upgrade-requests.php" class="btn btn-sm btn-outline-secondary ml-1">Feature/Sponsor Requests</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','pending_payment','payment_uploaded','approved','rejected','cancelled'] as $s): ?><option value="<?=$s?>" <?=$status===$s?'selected':''?>><?=ucfirst(str_replace('_',' ',$s))?></option><?php endforeach; ?></select></form><div class="table-responsive"><table class="table table-hover"><thead><tr><th>ID</th><th>Listing</th><th>User</th><th>Current Expiry</th><th>Requested</th><th>Payment</th><th>Action</th></tr></thead><tbody><?php foreach($rows as $r): ?><tr><td><?=e($r['id'])?></td><td>#<?=e($r['listing_id'])?> <?=e($r['title'])?></td><td><?=e(($r['user_name']??'').' '.$r['email'])?></td><td><?=e($r['current_expires_at'] ?: $r['expires_at'])?></td><td><?=e($r['requested_days'])?> days<br><?=e($r['requested_expires_at'])?></td><td>
  <?php if(!empty($r['payment_required'])): ?>
    <b><?=e($r['payment_currency'] ?: 'SGD')?> <?=e(number_format((float)$r['payment_amount'],2))?></b><br>
    <small><?=e($r['payment_status'] ?: 'payment_required')?></small>
  <?php else: ?>
    <span class="text-muted">Not required</span>
  <?php endif; ?>
</td><td><?php if($status==='pending'): ?><form method="post" class="d-flex flex-wrap gap-1"><?=csrf_input()?><input type="hidden" name="request_id" value="<?=e($r['id'])?>"><input class="form-control form-control-sm" style="width:80px" name="days" value="<?=e($r['requested_days'] ?: 30)?>"><input class="form-control form-control-sm" type="datetime-local" name="custom_expires_at"><input class="form-control form-control-sm" name="admin_note" placeholder="Note"><button class="btn btn-sm btn-success" name="action" value="approve">Approve</button><button class="btn btn-sm btn-danger" name="action" value="reject">Reject</button></form><?php else: ?><span class="badge badge-secondary"><?=e($r['status'])?></span><?php endif; ?></td></tr><?php endforeach; ?></tbody></table></div></div></div><?php include __DIR__.'/_footer.php'; ?>
