<?php
require_once __DIR__.'/../includes/functions.php';
$admin=require_admin(); verify_csrf(); mj_ensure_listing_module_schema(true); $adminTitle='Edit Listing';
$id=(int)($_GET['id']??$_POST['id']??0);
mj263_schema();
if(isset($_POST['photo_action'], $_POST['image_id'])){ verify_csrf(); $imageId=(int)$_POST['image_id']; $listingId=(int)($_POST['listing_id']??0); if($listingId>0 && mj263_delete_listing_image($imageId,$listingId)){ mj_listing_log($listingId,'admin_deleted_photo',[],['image_id'=>$imageId]); flash('success','Photo deleted successfully.'); } else { flash('error','Photo could not be deleted.'); } redirect('listing-edit.php?id='.$listingId); }
$listing=$id?one('SELECT * FROM mj_listings WHERE id=? LIMIT 1',[$id]):null;
if($id && !$listing){ flash('error','Listing not found.'); redirect('listings.php'); }
$errors=[];
if($_SERVER['REQUEST_METHOD']==='POST'){
  try{
    $title=trim((string)($_POST['title']??'')); if($title==='') $errors[]='Title is required.';
    $price=(float)($_POST['price']??0); if($price<0) $errors[]='Price cannot be negative.';
    $countryId=(int)($_POST['country_id']??0); if($countryId<=0) $errors[]='Country is required.';
    $country=$countryId?one('SELECT * FROM mj_countries WHERE id=? LIMIT 1',[$countryId]):null; if(!$country) $errors[]='Valid country is required.';
    $status=(string)($_POST['status']??'active'); if(!in_array($status,['draft','pending','active','inactive','reserved','sold','expired','rejected','deleted'],true)) $status='active';
    $expires=trim((string)($_POST['expires_at']??'')); if($expires==='') $expires=mj_listing_default_expiry(); else $expires=date('Y-m-d H:i:s',strtotime($expires));
    if($errors) throw new Exception(implode(' ', $errors));
    $data=[
      'user_id'=>(int)($_POST['user_id']??0) ?: null,
      'category_id'=>(int)($_POST['category_id']??0) ?: null,
      'country_id'=>$countryId,
      'state_id'=>(int)($_POST['state_id']??0) ?: null,
      'city_id'=>(int)($_POST['city_id']??0) ?: null,
      'timezone'=>trim((string)($_POST['timezone']??'')) ?: ($country['timezone_default'] ?? 'UTC'),
      'listing_type'=>trim((string)($_POST['listing_type']??'product')) ?: 'product',
      'title'=>$title,
      'slug'=>trim((string)($_POST['slug']??'')) ?: mj_slug_unique('mj_listings',$title,$id),
      'description'=>trim((string)($_POST['description']??'')),
      'price'=>$price,
      'currency_code'=>trim((string)($_POST['currency_code']??'')) ?: ($country['currency_code'] ?? 'SGD'),
      'condition_label'=>trim((string)($_POST['condition_label']??'')) ?: 'Used',
      'status'=>$status,
      'expires_at'=>$expires,
      'is_featured'=>isset($_POST['is_featured'])?1:0,
      'featured_until'=>trim((string)($_POST['featured_until']??'')) ?: null,
      'featured_priority'=>(int)($_POST['featured_priority']??0),
      'is_sponsored'=>isset($_POST['is_sponsored'])?1:0,
      'sponsored_until'=>trim((string)($_POST['sponsored_until']??'')) ?: null,
      'sponsored_priority'=>(int)($_POST['sponsored_priority']??0),
      'sponsor_keywords'=>trim((string)($_POST['sponsor_keywords']??'')),
      'search_boost_keywords'=>trim((string)($_POST['search_boost_keywords']??'')),
      'sort_priority'=>(int)($_POST['sort_priority']??0),
      'seo_title'=>trim((string)($_POST['seo_title']??'')),
      'seo_description'=>trim((string)($_POST['seo_description']??'')),
      'admin_note'=>trim((string)($_POST['admin_note']??'')),
      'reject_reason'=>trim((string)($_POST['reject_reason']??'')),
    ];
    if($data['featured_until']) $data['featured_until']=date('Y-m-d H:i:s',strtotime($data['featured_until']));
    if($data['sponsored_until']) $data['sponsored_until']=date('Y-m-d H:i:s',strtotime($data['sponsored_until']));
    if($status==='active' && !$id){ $data['approved_at']=date('Y-m-d H:i:s'); $data['approved_by']=$admin['id']; $data['published_at']=date('Y-m-d H:i:s'); }
    if($status==='rejected'){ $data['rejected_at']=date('Y-m-d H:i:s'); $data['rejected_by']=$admin['id']; }
    if($status==='deleted'){ $data['is_deleted']=1; $data['deleted_at']=date('Y-m-d H:i:s'); $data['deleted_by']=$admin['id']; } else { $data['is_deleted']=0; }
    if($id){
      $old=$listing; $sets=[]; $params=[]; foreach($data 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) { throw new Exception('No editable listing columns found. Please run /install/migration_v2.6_listing_module_pro.sql then try again.'); }
      $params[]=$id; q('UPDATE mj_listings SET '.implode(',',$sets).' WHERE id=?',$params); mj_listing_log($id,'admin_edit',$old,$data);
    } else {
      $cols=[];$ph=[];$params=[]; foreach($data as $k=>$v){ if(mj_column_exists('mj_listings',$k)){ $cols[]="`$k`"; $ph[]='?'; $params[]=$v; } }
      if(mj_column_exists('mj_listings','created_at')){ $cols[]='created_at'; $ph[]='NOW()'; }
      if (!$cols) { throw new Exception('No insertable listing columns found. Please run /install/migration_v2.6_listing_module_pro.sql then try again.'); }
      q('INSERT INTO mj_listings('.implode(',',$cols).') VALUES('.implode(',',$ph).')',$params); $id=(int)db()->lastInsertId(); mj_listing_log($id,'admin_create',[],$data);
    }
    for($i=1;$i<=8;$i++){ $path=upload_image('image'.$i,'listings'); if($path && table_exists('mj_listing_images')) q('INSERT INTO mj_listing_images(listing_id,image_path,sort_order) VALUES(?,?,?)',[$id,$path,$i]); }
    flash('success','Listing saved successfully.'); redirect('listing-edit.php?id='.$id);
  } catch(Throwable $e){ flash('error',$e->getMessage()); }
}
$listing=$id?one('SELECT * FROM mj_listings WHERE id=? LIMIT 1',[$id]):['status'=>'active','listing_type'=>'product','condition_label'=>'Used','expires_at'=>mj_listing_default_expiry(),'currency_code'=>'SGD'];
$countries=all_rows('SELECT id,name,flag_emoji,currency_code,timezone_default FROM mj_countries WHERE is_active=1 ORDER BY name');
$cats=all_rows('SELECT id,name,type FROM mj_categories WHERE is_active=1 ORDER BY type,name');
$users=all_rows('SELECT id,name,email FROM mj_users ORDER BY id DESC LIMIT 500');
$images=$id&&table_exists('mj_listing_images')?all_rows('SELECT * FROM mj_listing_images WHERE listing_id=? ORDER BY sort_order,id',[$id]):[];
include __DIR__.'/_header.php';
?>
<div class="card card-primary card-outline"><div class="card-header"><h3 class="card-title"><i class="fas fa-edit mr-2"></i><?= $id?'Edit Listing #'.e($id):'Add Listing' ?></h3><div class="card-tools"><a class="btn btn-sm btn-secondary" href="listings.php">Back</a><?php if($id): ?><a class="btn btn-sm btn-info" target="_blank" href="../listing.php?id=<?=$id?>">Public View</a><?php endif; ?></div></div>
<form method="post" enctype="multipart/form-data"><?=csrf_input()?><input type="hidden" name="id" value="<?=e($id)?>"><div class="card-body">
<?php show_flash(); ?><div class="row"><div class="col-lg-8">
<div class="form-group"><label>Title <span class="text-danger">*</span></label><input class="form-control" name="title" value="<?=e($listing['title']??'') ?>" required maxlength="180"></div>
<div class="form-group"><label>Description</label><textarea class="form-control" name="description" rows="7" maxlength="8000"><?=e($listing['description']??'')?></textarea><small class="text-muted">Use clear details, condition, warranty, pickup/delivery and safety information.</small></div>
<div class="row"><div class="col-md-4"><div class="form-group"><label>Price</label><input class="form-control" type="number" step="0.01" min="0" name="price" value="<?=e($listing['price']??0)?>"></div></div><div class="col-md-4"><div class="form-group"><label>Currency</label><input class="form-control" name="currency_code" value="<?=e($listing['currency_code']??'SGD')?>"></div></div><div class="col-md-4"><div class="form-group"><label>Condition</label><input class="form-control" name="condition_label" value="<?=e($listing['condition_label']??'Used')?>"></div></div></div>
<div class="row"><div class="col-md-4"><div class="form-group"><label>Country *</label><select class="form-control" name="country_id" required><option value="">Select</option><?php foreach($countries as $c): ?><option value="<?=e($c['id'])?>" <?=(int)($listing['country_id']??0)==(int)$c['id']?'selected':''?>><?=e(($c['flag_emoji']??'').' '.$c['name'])?></option><?php endforeach; ?></select></div></div><div class="col-md-4"><div class="form-group"><label>State ID</label><input class="form-control" name="state_id" value="<?=e($listing['state_id']??'')?>" placeholder="Optional ID"></div></div><div class="col-md-4"><div class="form-group"><label>City ID</label><input class="form-control" name="city_id" value="<?=e($listing['city_id']??'')?>" placeholder="Optional ID"></div></div></div>
<div class="row"><div class="col-md-4"><div class="form-group"><label>Category</label><select class="form-control" name="category_id"><option value="">Select</option><?php foreach($cats as $c): ?><option value="<?=e($c['id'])?>" <?=(int)($listing['category_id']??0)==(int)$c['id']?'selected':''?>><?=e($c['type'].' - '.$c['name'])?></option><?php endforeach; ?></select></div></div><div class="col-md-4"><div class="form-group"><label>Type</label><select class="form-control" name="listing_type"><?php foreach(['product','service','wanted','rental','job','property','vehicle','course','event','wholesale','free'] as $t): ?><option value="<?=$t?>" <?=($listing['listing_type']??'product')===$t?'selected':''?>><?=ucfirst($t)?></option><?php endforeach; ?></select></div></div><div class="col-md-4"><div class="form-group"><label>Seller/User</label><select class="form-control" name="user_id"><option value="">Admin/No user</option><?php foreach($users as $u): ?><option value="<?=e($u['id'])?>" <?=(int)($listing['user_id']??0)==(int)$u['id']?'selected':''?>>#<?=e($u['id'])?> <?=e($u['name'].' '.$u['email'])?></option><?php endforeach; ?></select></div></div></div>
<div class="form-group"><label>Upload Images</label><div class="row"><?php for($i=1;$i<=8;$i++): ?><div class="col-md-6 mb-2"><input class="form-control" type="file" name="image<?=$i?>" accept="image/*"></div><?php endfor; ?></div><?php if($images): ?><div class="row mt-2 mj-photo-manage"><?php foreach($images as $im): ?><div class="col-6 col-md-3 mb-3"><div class="border rounded p-2 text-center"><img class="img-fluid rounded border mb-2" src="<?=e(base_url($im['image_path']))?>" data-gallery-src="<?=e(base_url($im['image_path']))?>"><form method="post" onsubmit="return confirm('Delete this photo?')"><?=csrf_input()?><input type="hidden" name="listing_id" value="<?=e($id)?>"><input type="hidden" name="image_id" value="<?=e($im['id'])?>"><button class="btn btn-xs btn-danger" name="photo_action" value="delete" type="submit"><i class="fas fa-trash"></i> Delete</button></form></div></div><?php endforeach; ?></div><?php endif; ?></div>
</div><div class="col-lg-4">
<div class="card bg-light"><div class="card-body"><h5 class="font-weight-bold">Status & Expiry</h5><div class="form-group"><label>Status</label><select class="form-control" name="status"><?php foreach(['draft','pending','active','inactive','reserved','sold','expired','rejected','deleted'] as $s): ?><option value="<?=$s?>" <?=($listing['status']??'active')===$s?'selected':''?>><?=ucfirst($s)?></option><?php endforeach; ?></select></div><div class="form-group"><label>Expires At</label><input class="form-control" type="datetime-local" name="expires_at" value="<?=!empty($listing['expires_at'])?e(date('Y-m-d\TH:i',strtotime($listing['expires_at']))):''?>"><small>Default is 30 days.</small></div><div class="form-group"><label>Timezone</label><input class="form-control" name="timezone" value="<?=e($listing['timezone']??'Asia/Singapore')?>"></div></div></div>
<div class="card"><div class="card-body"><h5 class="font-weight-bold">Featured / Sponsored</h5><div class="custom-control custom-switch"><input type="checkbox" class="custom-control-input" id="is_featured" name="is_featured" <?=!empty($listing['is_featured'])?'checked':''?>><label class="custom-control-label" for="is_featured">Featured Listing</label></div><label class="mt-2">Featured Until</label><input class="form-control" type="datetime-local" name="featured_until" value="<?=!empty($listing['featured_until'])?e(date('Y-m-d\TH:i',strtotime($listing['featured_until']))):''?>"><label class="mt-2">Featured Priority</label><input class="form-control" type="number" name="featured_priority" value="<?=e($listing['featured_priority']??0)?>"><hr><div class="custom-control custom-switch"><input type="checkbox" class="custom-control-input" id="is_sponsored" name="is_sponsored" <?=!empty($listing['is_sponsored'])?'checked':''?>><label class="custom-control-label" for="is_sponsored">Sponsored Listing</label></div><label class="mt-2">Sponsored Until</label><input class="form-control" type="datetime-local" name="sponsored_until" value="<?=!empty($listing['sponsored_until'])?e(date('Y-m-d\TH:i',strtotime($listing['sponsored_until']))):''?>"><label class="mt-2">Sponsored Priority</label><input class="form-control" type="number" name="sponsored_priority" value="<?=e($listing['sponsored_priority']??0)?>"><label class="mt-2">Sponsor Keywords</label><textarea class="form-control" name="sponsor_keywords" rows="2" placeholder="data recovery, iphone, cctv"><?=e($listing['sponsor_keywords']??'')?></textarea><label class="mt-2">Search Boost Keywords</label><textarea class="form-control" name="search_boost_keywords" rows="2"><?=e($listing['search_boost_keywords']??'')?></textarea><label class="mt-2">General Sort Priority</label><input class="form-control" type="number" name="sort_priority" value="<?=e($listing['sort_priority']??0)?>"></div></div>
<div class="card"><div class="card-body"><h5 class="font-weight-bold">SEO & Admin</h5><label>Slug</label><input class="form-control" name="slug" value="<?=e($listing['slug']??'')?>"><label class="mt-2">SEO Title</label><input class="form-control" name="seo_title" value="<?=e($listing['seo_title']??'')?>"><label class="mt-2">SEO Description</label><textarea class="form-control" rows="2" name="seo_description"><?=e($listing['seo_description']??'')?></textarea><label class="mt-2">Admin Note</label><textarea class="form-control" rows="2" name="admin_note"><?=e($listing['admin_note']??'')?></textarea><label class="mt-2">Reject Reason</label><textarea class="form-control" rows="2" name="reject_reason"><?=e($listing['reject_reason']??'')?></textarea></div></div>
</div></div></div><div class="card-footer"><button class="btn btn-primary btn-lg"><i class="fas fa-save mr-1"></i>Save Listing</button> <a href="listings.php" class="btn btn-secondary btn-lg">Cancel</a></div></form></div>
<?php include __DIR__.'/_footer.php'; ?>
