<?php
require_once __DIR__.'/includes/functions.php';
$u=require_user(); verify_csrf(); mj_ensure_listing_module_schema(true); mj263_schema(); $pageTitle='Edit Listing';
$id=(int)($_GET['id']??$_POST['id']??0);
$l=$id?one('SELECT * FROM mj_listings WHERE id=? AND user_id=? LIMIT 1',[$id,$u['id']]):null;
if(!$l){ flash('error','Listing not found or access denied.'); redirect('my-listings.php'); }
$pending=mj263_pending_revision($id);
if($_SERVER['REQUEST_METHOD']==='POST'){
  try{
    $title=trim((string)($_POST['title']??'')); if(mb_strlen($title)<3) throw new Exception('Title must be at least 3 characters.');
    $price=(float)($_POST['price']??0); if($price<0) throw new Exception('Price cannot be negative.');
    $countryId=(int)($_POST['country_id']??0); $country=$countryId?one('SELECT * FROM mj_countries WHERE id=? LIMIT 1',[$countryId]):null; if(!$country) throw new Exception('Country is required.');
    $new=[
      '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'=>mj_slug_unique('mj_listings',$title,$id),'description'=>trim((string)($_POST['description']??'')),'price'=>$price,'currency_code'=>$country['currency_code'] ?? ($l['currency_code'] ?? 'SGD'),
      'condition_label'=>trim((string)($_POST['condition_label']??'')) ?: 'Used','min_offer_price'=>(float)($_POST['min_offer_price']??0),'is_negotiable'=>!empty($_POST['is_negotiable'])?1:0,
      'delivery_options'=>trim((string)($_POST['delivery_options']??'')),'contact_options'=>trim((string)($_POST['contact_options']??'')),'availability_status'=>trim((string)($_POST['availability_status']??''))
    ];
    $deleteIds=array_values(array_filter(array_map('intval', $_POST['delete_image_ids'] ?? [])));
    $newImagePaths=[]; for($i=1;$i<=8;$i++){ $path=upload_image('image'.$i,'listings/pending'); if($path) $newImagePaths[]=$path; }
    $oldImages=mj263_listing_images($id); $oldPaths=mj263_image_paths($id);
    $status=strtolower((string)($l['status']??'pending'));
    if(in_array($status,['active','approved','published','sold','reserved'],true)){
      $revisionData=['old_data_json'=>mj_safe_json($l),'new_data_json'=>mj_safe_json($new),'old_images_json'=>mj_safe_json($oldPaths),'new_images_json'=>mj_safe_json($newImagePaths),'deleted_images_json'=>mj_safe_json($deleteIds),'status'=>'pending'];
      if($pending){
        q('UPDATE mj_listing_revisions SET old_data_json=?,new_data_json=?,old_images_json=?,new_images_json=?,deleted_images_json=?,submitted_at=NOW(),status="pending" WHERE id=?',[$revisionData['old_data_json'],$revisionData['new_data_json'],$revisionData['old_images_json'],$revisionData['new_images_json'],$revisionData['deleted_images_json'],(int)$pending['id']]);
      } else {
        q('INSERT INTO mj_listing_revisions(listing_id,user_id,old_data_json,new_data_json,old_images_json,new_images_json,deleted_images_json,status,submitted_at,created_at) VALUES(?,?,?,?,?,?,?,"pending",NOW(),NOW())',[$id,$u['id'],$revisionData['old_data_json'],$revisionData['new_data_json'],$revisionData['old_images_json'],$revisionData['new_images_json'],$revisionData['deleted_images_json']]);
      }
      mj_listing_log($id,'user_revision_submitted',$l,$new);
      mj263_notify(null,1,'listing_revision','Listing edit pending approval','User submitted changes for listing: '.$title,'admin/listing-revisions.php','high');
      mj_create_admin_alert(['alert_key'=>'listing_revision_'.$id.'_'.date('YmdHi'),'alert_type'=>'listing_revision','module_name'=>'listings','priority'=>'high','title'=>'Listing edit pending approval','message'=>'User edited listing: '.$title,'action_url'=>'listing-revisions.php','action_label'=>'Review','related_type'=>'listing','related_id'=>$id]);
      flash('success','Your changes were submitted for admin approval. Current public listing stays unchanged until approved.');
    } else {
      foreach($deleteIds as $imgId){ mj263_delete_listing_image($imgId,$id); }
      $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[]='pending'; }
      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[]=$id; q('UPDATE mj_listings SET '.implode(',',$sets).' WHERE id=?',$params);
      foreach($newImagePaths as $i=>$path){ if(table_exists('mj_listing_images')) q('INSERT INTO mj_listing_images(listing_id,image_path,sort_order) VALUES(?,?,?)',[$id,$path,50+$i]); }
      mj_listing_log($id,'user_edit_resubmit',$l,$new); flash('success','Listing updated and submitted for approval.');
    }
    redirect('my-listings.php');
  }catch(Throwable $e){ flash('error',$e->getMessage()); }
}
$countries=all_rows('SELECT * FROM mj_countries WHERE is_active=1 ORDER BY name'); $cats=all_rows('SELECT * FROM mj_categories WHERE is_active=1 ORDER BY type,name'); $images=mj263_listing_images($id); $quality=mj263_quality_details($l); $pending=mj263_pending_revision($id);
include __DIR__.'/includes/header.php';
?>
<section class="mj-page-hero"><div class="container"><h1 class="fw-bold">Edit Listing</h1><p class="text-muted mb-0">Active listing edits and photo changes require admin approval before becoming public.</p></div></section>
<section class="mj-section"><div class="container"><?php show_flash(); ?><?php if($pending): ?><div class="alert alert-warning rounded-4"><b>Pending edit review:</b> You already have changes waiting for admin approval. Saving again will update that pending request.</div><?php endif; ?><form method="post" enctype="multipart/form-data" class="mj-card p-4"><?=csrf_input()?><input type="hidden" name="id" value="<?=e($id)?>"><div class="row g-4"><div class="col-lg-8"><label class="label">Title *</label><input class="form-control" name="title" value="<?=e($l['title']??'') ?>" required maxlength="180"><label class="label mt-3">Description</label><textarea class="form-control" rows="7" name="description" maxlength="8000"><?=e($l['description']??'')?></textarea><div class="row g-3 mt-1"><div class="col-md-4"><label class="label">Price</label><input class="form-control" type="number" step="0.01" min="0" name="price" value="<?=e($l['price']??0)?>"></div><div class="col-md-4"><label class="label">Minimum Offer</label><input class="form-control" type="number" step="0.01" min="0" name="min_offer_price" value="<?=e($l['min_offer_price']??0)?>"></div><div class="col-md-4"><label class="label">Condition</label><input class="form-control" name="condition_label" value="<?=e($l['condition_label']??'Used')?>"></div></div><div class="form-check mt-3"><input class="form-check-input" type="checkbox" name="is_negotiable" id="neg" <?=!empty($l['is_negotiable'])?'checked':''?>><label class="form-check-label" for="neg">Price is negotiable</label></div><label class="label mt-3">Current Photos</label><div class="row g-3 mj-photo-manage"><?php foreach($images as $im): ?><div class="col-6 col-md-3"><div class="border rounded-4 p-2 text-center"><img src="<?=e(base_url($im['image_path']))?>" data-gallery-src="<?=e(base_url($im['image_path']))?>"><div class="form-check small mt-2"><input class="form-check-input" type="checkbox" name="delete_image_ids[]" value="<?=e($im['id'])?>" id="del<?=e($im['id'])?>"><label class="form-check-label text-danger" for="del<?=e($im['id'])?>">Delete photo</label></div></div></div><?php endforeach; ?></div><label class="label mt-3">Upload New Photos</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></div><div class="col-lg-4"><div class="mj-card p-3 bg-light"><h5 class="fw-bold">Listing quality: <?=e($quality['score'])?>%</h5><div class="progress mb-2"><div class="progress-bar" style="width:<?=e($quality['score'])?>%"></div></div><?php foreach($quality['tips'] as $tip): ?><div class="small text-muted">• <?=e($tip)?></div><?php endforeach; ?></div><label class="label mt-3">Country *</label><select class="form-select" name="country_id" required><?php foreach($countries as $c): ?><option value="<?=e($c['id'])?>" <?=(int)($l['country_id']??0)==(int)$c['id']?'selected':''?>><?=e(($c['flag_emoji']??'').' '.$c['name'])?></option><?php endforeach; ?></select><label class="label mt-3">State ID</label><input class="form-control" name="state_id" value="<?=e($l['state_id']??'')?>"><label class="label mt-3">City ID</label><input class="form-control" name="city_id" value="<?=e($l['city_id']??'')?>"><label class="label mt-3">Category</label><select class="form-select" name="category_id"><option value="">Select</option><?php foreach($cats as $c): ?><option value="<?=e($c['id'])?>" <?=(int)($l['category_id']??0)==(int)$c['id']?'selected':''?>><?=e($c['name'])?></option><?php endforeach; ?></select><label class="label mt-3">Type</label><select class="form-select" name="listing_type"><?php foreach(['product','service','wanted','rental','job','property','vehicle','course','event','wholesale','free'] as $t): ?><option value="<?=$t?>" <?=($l['listing_type']??'product')===$t?'selected':''?>><?=ucfirst($t)?></option><?php endforeach; ?></select><label class="label mt-3">Delivery / Meetup Options</label><textarea class="form-control" name="delivery_options" rows="2"><?=e($l['delivery_options']??'')?></textarea><label class="label mt-3">Contact Options</label><input class="form-control" name="contact_options" value="<?=e($l['contact_options']??'Chat only')?>"><label class="label mt-3">Availability</label><input class="form-control" name="availability_status" value="<?=e($l['availability_status']??'Available now')?>"><label class="label mt-3">Timezone</label><input class="form-control" name="timezone" value="<?=e($l['timezone']??'Asia/Singapore')?>"><div class="alert alert-info mt-3 rounded-4"><b>Status:</b> <?=e($l['status']??'pending')?><br><b>Expires:</b> <?=e($l['expires_at']??'Not set')?></div></div></div><div class="mt-4"><button class="btn btn-primary btn-lg"><i class="bi bi-send-check me-1"></i><?= in_array(strtolower((string)($l['status']??'')),['active','approved','published','sold','reserved'],true)?'Submit Changes for Approval':'Save & Submit' ?></button> <a class="btn btn-outline-secondary btn-lg" href="my-listings.php">Cancel</a></div></form></div></section>
<?php include __DIR__.'/includes/footer.php'; ?>
