<?php
require_once __DIR__.'/../includes/functions.php';
$admin=require_admin(); verify_csrf(); mj_ensure_listing_module_schema(true); $adminTitle='Listings';
function mj_admin_listing_update(int $id, string $status=null, array $extra=[]): void {
    $old = one('SELECT * FROM mj_listings WHERE id=? LIMIT 1',[$id]); if(!$old){ flash('error','Listing not found.'); redirect('listings.php'); }
    $sets=[]; $params=[];
    if($status!==null){ $sets[]='status=?'; $params[]=$status; }
    foreach($extra as $k=>$v){ if(mj_column_exists('mj_listings',$k)){ $sets[]="`$k`=?"; $params[]=$v; } }
    if(mj_column_exists('mj_listings','updated_at')) $sets[]='updated_at=NOW()';
    if($sets){ $params[]=$id; q('UPDATE mj_listings SET '.implode(',',$sets).' WHERE id=?',$params); }
    $new = one('SELECT * FROM mj_listings WHERE id=? LIMIT 1',[$id]) ?: [];
    mj_listing_log($id,'admin_update_'.$status,$old,$new); admin_log('listing_update','mj_listings',$id,['status'=>$status,'extra'=>$extra]);
}
if(isset($_POST['bulk_action']) && !empty($_POST['ids']) && is_array($_POST['ids'])){
    $ids=array_map('intval',$_POST['ids']); $action=(string)$_POST['bulk_action'];
    foreach($ids as $id){
        if($action==='renew30') mj_admin_listing_update($id,null,['expires_at'=>date('Y-m-d H:i:s',strtotime('+30 days')),'expired_at'=>null,'status'=>'active']);
        elseif($action==='feature') mj_admin_listing_update($id,null,['is_featured'=>1,'featured_until'=>date('Y-m-d H:i:s',strtotime('+30 days')),'featured_priority'=>50]);
        elseif($action==='sponsor') mj_admin_listing_update($id,null,['is_sponsored'=>1,'sponsored_until'=>date('Y-m-d H:i:s',strtotime('+30 days')),'sponsored_priority'=>100]);
        elseif(in_array($action,['active','inactive','pending','rejected','sold','reserved','expired','deleted'],true)) mj_admin_listing_update($id,$action,$action==='deleted'?['is_deleted'=>1,'deleted_at'=>date('Y-m-d H:i:s'),'deleted_by'=>$admin['id']]:[]);
    }
    flash('success','Bulk action completed.'); redirect('listings.php');
}
if(isset($_POST['action'],$_POST['id'])){
    $id=(int)$_POST['id']; $action=(string)$_POST['action'];
    if($action==='active') mj_admin_listing_update($id,'active',['approved_at'=>date('Y-m-d H:i:s'),'approved_by'=>$admin['id'],'expires_at'=>mj_listing_default_expiry()]);
    elseif($action==='rejected') mj_admin_listing_update($id,'rejected',['rejected_at'=>date('Y-m-d H:i:s'),'rejected_by'=>$admin['id'],'reject_reason'=>$_POST['reject_reason']??'Rejected by admin']);
    elseif($action==='inactive') mj_admin_listing_update($id,'inactive',['inactive_at'=>date('Y-m-d H:i:s'),'inactive_by'=>$admin['id']]);
    elseif($action==='deleted') mj_admin_listing_update($id,'deleted',['is_deleted'=>1,'deleted_at'=>date('Y-m-d H:i:s'),'deleted_by'=>$admin['id']]);
    elseif($action==='renew30') mj_admin_listing_update($id,'active',['expires_at'=>date('Y-m-d H:i:s',strtotime('+30 days')),'expired_at'=>null]);
    elseif($action==='feature') mj_admin_listing_update($id,null,['is_featured'=>1,'featured_until'=>date('Y-m-d H:i:s',strtotime('+30 days')),'featured_priority'=>50]);
    elseif($action==='unfeature') mj_admin_listing_update($id,null,['is_featured'=>0,'featured_until'=>null,'featured_priority'=>0]);
    elseif($action==='sponsor') mj_admin_listing_update($id,null,['is_sponsored'=>1,'sponsored_until'=>date('Y-m-d H:i:s',strtotime('+30 days')),'sponsored_priority'=>100]);
    elseif($action==='unsponsor') mj_admin_listing_update($id,null,['is_sponsored'=>0,'sponsored_until'=>null,'sponsored_priority'=>0]);
    flash('success','Listing updated.'); redirect('listings.php');
}
$status=$_GET['status']??''; $country=(int)($_GET['country_id']??0); $q=trim((string)($_GET['q']??'')); $flag=trim((string)($_GET['flag']??''));
$where=['1=1']; $params=[];
if($status!==''){ $where[]='l.status=?'; $params[]=$status; }
if($country){ $where[]='l.country_id=?'; $params[]=$country; }
if($q!==''){ $where[]='(l.title LIKE ? OR l.description LIKE ?)'; $params[]='%'.$q.'%'; $params[]='%'.$q.'%'; }
if($flag==='featured') $where[]='l.is_featured=1';
if($flag==='sponsored') $where[]='l.is_sponsored=1';
if($flag==='expiring') $where[]="l.expires_at IS NOT NULL AND l.expires_at BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 7 DAY)";
if($flag==='expired') $where[]="l.expires_at IS NOT NULL AND l.expires_at<NOW()";
$rows=all_rows('SELECT l.*,u.name user_name,c.name country,cat.name category FROM mj_listings l LEFT JOIN mj_users u ON u.id=l.user_id LEFT JOIN mj_countries c ON c.id=l.country_id LEFT JOIN mj_categories cat ON cat.id=l.category_id WHERE '.implode(' AND ',$where).' ORDER BY l.id DESC LIMIT 800',$params);
$countries=all_rows('SELECT id,name,flag_emoji FROM mj_countries WHERE is_active=1 ORDER BY name');
include __DIR__.'/_header.php';
?>
<div class="card card-primary card-outline">
  <div class="card-header"><h3 class="card-title"><i class="fas fa-tags mr-2"></i>Manage Listings</h3><div class="card-tools"><a href="listing-edit.php" class="btn btn-sm btn-primary"><i class="fas fa-plus"></i> Add Listing</a> <a href="listing-revisions.php" class="btn btn-sm btn-warning"><i class="fas fa-code-branch"></i> Pending Edits</a></div></div>
  <div class="card-body">
    <form class="form-row mb-3" method="get">
      <div class="col-md-2"><input class="form-control" name="q" value="<?=e($q)?>" placeholder="Search title"></div>
      <div class="col-md-2"><select name="status" class="form-control"><option value="">All status</option><?php foreach(['draft','pending','active','inactive','reserved','sold','expired','rejected','deleted'] as $s): ?><option value="<?=$s?>" <?=$status===$s?'selected':''?>><?=ucfirst($s)?></option><?php endforeach; ?></select></div>
      <div class="col-md-3"><select name="country_id" class="form-control"><option value="">All countries</option><?php foreach($countries as $c): ?><option value="<?=e($c['id'])?>" <?=$country==$c['id']?'selected':''?>><?=e(($c['flag_emoji']??'').' '.$c['name'])?></option><?php endforeach; ?></select></div>
      <div class="col-md-2"><select name="flag" class="form-control"><option value="">All types</option><?php foreach(['featured'=>'Featured','sponsored'=>'Sponsored','expiring'=>'Expiring 7 days','expired'=>'Expired'] as $k=>$v): ?><option value="<?=$k?>" <?=$flag===$k?'selected':''?>><?=$v?></option><?php endforeach; ?></select></div>
      <div class="col-md-2"><button class="btn btn-info btn-block">Filter</button></div><div class="col-md-1 text-right"><span class="badge badge-light p-2"><?=count($rows)?></span></div>
    </form>
    <form method="post"><?=csrf_input()?><div class="mb-2 d-flex flex-wrap gap-2"><select name="bulk_action" class="form-control form-control-sm" style="max-width:230px"><option value="">Bulk action</option><option value="active">Approve / Active</option><option value="inactive">Set Inactive</option><option value="rejected">Reject</option><option value="expired">Mark Expired</option><option value="deleted">Soft Delete</option><option value="renew30">Renew 30 Days</option><option value="feature">Feature 30 Days</option><option value="sponsor">Sponsor 30 Days</option></select> <button class="btn btn-sm btn-secondary" onclick="return confirm('Apply bulk action?')">Apply</button></div>
    <div class="table-responsive"><table class="table table-striped table-hover mj-data-table"><thead><tr><th><input type="checkbox" onclick="document.querySelectorAll('.mj-check').forEach(c=>c.checked=this.checked)"></th><th>ID</th><th>Title</th><th>Seller</th><th>Country</th><th>Category</th><th>Price</th><th>Status</th><th>Expiry</th><th>Boost</th><th>Action</th></tr></thead><tbody><?php foreach($rows as $r): ?><tr>
      <td><input class="mj-check" type="checkbox" name="ids[]" value="<?=e($r['id'])?>"></td><td><?=e($r['id'])?></td>
      <td><a href="../listing.php?id=<?=e($r['id'])?>" target="_blank"><b><?=e($r['title'])?></b></a><br><small class="text-muted"><?=e($r['listing_type']??'')?> • <?=e(local_datetime($r['created_at']??'',$r['timezone']??'UTC'))?></small></td>
      <td><?=e($r['user_name'])?></td><td><?=e($r['country'])?></td><td><?=e($r['category'])?></td><td><?=money($r['price'],$r['currency_code']??'SGD')?></td>
      <td><span class="badge badge-<?=mj_listing_status_badge($r['status']??'active')?>"><?=e($r['status']?:'active')?></span></td>
      <td><?php if(!empty($r['expires_at'])): ?><span class="<?=strtotime($r['expires_at'])<time()?'text-danger':'text-muted'?>"><?=e(date('d M Y',strtotime($r['expires_at'])))?></span><?php else: ?><span class="text-muted">No expiry</span><?php endif; ?></td>
      <td><?php if(mj_listing_active_sponsored($r)): ?><span class="badge badge-danger">Sponsored #<?=e($r['sponsored_priority']??0)?></span><?php endif; ?> <?php if(mj_listing_active_featured($r)): ?><span class="badge badge-warning">Featured #<?=e($r['featured_priority']??0)?></span><?php endif; ?></td>
      <td><div class="btn-group btn-group-sm"><a class="btn btn-primary" href="listing-edit.php?id=<?=e($r['id'])?>">Edit</a><a class="btn btn-info" target="_blank" href="../listing.php?id=<?=e($r['id'])?>">View</a></div><div class="mt-1"><button class="btn btn-xs btn-success" name="action" value="active" formaction="?" formmethod="post" onclick="document.getElementById('row_action_id').value='<?=e($r['id'])?>'">Approve</button> <button class="btn btn-xs btn-warning" name="action" value="renew30" onclick="document.getElementById('row_action_id').value='<?=e($r['id'])?>'">Renew</button> <button class="btn btn-xs btn-danger" name="action" value="deleted" onclick="document.getElementById('row_action_id').value='<?=e($r['id'])?>';return confirm('Soft delete this listing?')">Delete</button></div></td>
    </tr><?php endforeach; ?></tbody></table></div><input type="hidden" name="id" id="row_action_id" value=""></form>
  </div>
</div>
<?php include __DIR__.'/_footer.php'; ?>
