<?php
require_once __DIR__.'/includes/functions.php';
require_once __DIR__.'/includes/mj_deal_helpers.php';
$user=require_user(); mj_deal_ensure_schema(); verify_csrf();
$pageTitle='Create Deal';
$editId=(int)($_GET['id']??$_POST['id']??0);
$deal=$editId?one('SELECT * FROM mj_deals WHERE id=? AND user_id=? LIMIT 1',[$editId,(int)$user['id']]):null;
if($editId && !$deal){ flash('error','Deal not found.'); redirect('my-deals.php'); }
$pendingRevision = ($editId && function_exists('mj_review_pending')) ? mj_review_pending('deal', $editId) : null;
if($_SERVER['REQUEST_METHOD']==='POST'){
 try{
  $id=(int)($_POST['id']??0);
  $existing=$id?one('SELECT * FROM mj_deals WHERE id=? AND user_id=? LIMIT 1',[$id,(int)$user['id']]):null;
  if(!$id && function_exists('mj_v300_assert_can_create_deal')){ mj_v300_assert_can_create_deal((int)$user['id']); }
  $title=trim((string)($_POST['title']??'')); if($title==='') throw new RuntimeException('Deal title is required.');
  $orig=(float)($_POST['original_price']??0); $price=(float)($_POST['deal_price']??0); if($orig<0||$price<0) throw new RuntimeException('Price cannot be negative.'); if($orig>0&&$price>$orig) throw new RuntimeException('Deal price cannot be higher than original price.');
  $start=trim((string)($_POST['start_at']??''))?:null; $end=trim((string)($_POST['end_at']??''))?:null; if($start&&$end&&strtotime($end)<strtotime($start)) throw new RuntimeException('End date must be after start date.');
  $image=$existing['image_path']??''; if(!empty($_FILES['image']['name'])) $image=upload_image('image','deals');
  $status=(string)($_POST['save_type']??'draft'); if($status==='submit'){ $dl=function_exists('mj_v300_user_limits')?mj_v300_user_limits((int)$user['id']):[]; $auto=!empty($dl['deal_auto_approve']) || setting('deal_auto_approve','0')==='1'; $status=$auto?'active':'pending'; } else $status='draft';
  $data=['user_id'=>(int)$user['id'],'company_id'=>(int)($_POST['company_id']??0)?:null,'category_id'=>(int)($_POST['category_id']??0)?:null,'country_id'=>(int)($_POST['country_id']??0)?:null,'city_id'=>(int)($_POST['city_id']??0)?:null,'deal_type'=>trim((string)($_POST['deal_type']??'normal'))?:'normal','title'=>$title,'slug'=>$existing['slug']??mj_slug_unique('mj_deals',$title,$id),'short_description'=>trim((string)($_POST['short_description']??'')),'description'=>trim((string)($_POST['description']??'')),'image_path'=>$image,'original_price'=>$orig,'deal_price'=>$price,'discount_percent'=>mj_deal_discount_percent($orig,$price),'price_note'=>trim((string)($_POST['price_note']??'')),'currency_code'=>strtoupper(substr(preg_replace('/[^A-Z]/i','',(string)($_POST['currency_code']??$user['preferred_currency']??'SGD')),0,8))?:'SGD','start_at'=>$start?date('Y-m-d H:i:s',strtotime($start)):null,'end_at'=>$end?date('Y-m-d H:i:s',strtotime($end)):null,'status'=>$status,'contact_phone'=>trim((string)($_POST['contact_phone']??$user['mobile']??'')),'contact_whatsapp'=>trim((string)($_POST['contact_whatsapp']??'')),'contact_email'=>trim((string)($_POST['contact_email']??$user['email']??'')),'terms'=>trim((string)($_POST['terms']??''))];
  if($data['contact_email']!==''&&!filter_var($data['contact_email'],FILTER_VALIDATE_EMAIL)) throw new RuntimeException('Contact email is invalid.');
  $data['quality_score']=mj_deal_quality_score($data);
  if($id && $existing && function_exists('mj_review_live_update_required') && mj_review_live_update_required('deal', (string)($existing['status'] ?? ''))){
      $reviewData=$data;
      $reviewData['status']=(string)($existing['status'] ?? 'active');
      $reviewData=mj_deal_filter_existing_columns($reviewData);
      $rid=mj_review_submit('deal',$id,(int)$user['id'],$existing,$reviewData,[],[]);
      if(function_exists('mj_review_admin_alert')){ mj_review_admin_alert('deal',$id,'User submitted deal changes for: '.$title); }
      if(function_exists('mj263_notify')){ mj263_notify((int)$user['id'],null,'deal_revision_submitted','Deal update sent for review','Your current deal remains live until admin approves the changes.','my-deals.php','normal',true); }
      flash('success','Your deal changes were submitted for admin review. The current public deal remains live until approval.');
      redirect('my-deals.php');
  }
  $data=mj_deal_filter_existing_columns($data);
  if($id&&$existing){ $sets=[];$params=[];foreach($data as $k=>$v){$sets[]='`'.$k.'`=?';$params[]=$v;} $sets[]='updated_at=NOW()';$params[]=$id;$params[]=(int)$user['id']; q('UPDATE mj_deals SET '.implode(',',$sets).' WHERE id=? AND user_id=?',$params); flash('success',$status==='pending'?'Deal updated and sent for admin approval.':'Deal updated.'); }
  else { $cols=array_keys($data); q('INSERT INTO mj_deals(`'.implode('`,`',$cols).'`,created_at,updated_at) VALUES('.implode(',',array_fill(0,count($cols),'?')).',NOW(),NOW())',array_values($data)); flash('success',$status==='pending'?'Deal submitted for admin approval.':'Deal saved as draft.'); }
  redirect('my-deals.php');
 }catch(Throwable $e){ flash('error',$e->getMessage()); $deal=array_merge($deal?:[],$_POST); }
}
$d=array_merge(mj_deal_column_defaults(),$deal?:[]);
$companies=table_exists('mj_companies')?all_rows('SELECT id,name,country_id,city_id,email,phone,whatsapp FROM mj_companies WHERE user_id=? ORDER BY name',[(int)$user['id']]):[];
$categories=table_exists('mj_categories')?all_rows("SELECT id,name FROM mj_categories WHERE is_active=1 AND type IN ('marketplace','service','company') ORDER BY sort_order,name LIMIT 300"):[];
$countries=table_exists('mj_countries')?all_rows('SELECT id,name,currency_code FROM mj_countries WHERE is_active=1 ORDER BY sort_order,name LIMIT 300'):[];
$cities=table_exists('mj_cities')?all_rows('SELECT id,name,country_id FROM mj_cities WHERE is_active=1 ORDER BY name LIMIT 500'):[];
include __DIR__.'/includes/header.php';
?>
<section class="mj-section"><div class="container"><div class="mj-center-shell"><?php include __DIR__.'/includes/account-sidebar.php'; ?><div class="mj-center-main">
<div class="d-flex justify-content-between align-items-center mb-4"><div><span class="mj-badge mb-2"><i class="bi bi-fire"></i> Deal</span><h1 class="h2 fw-bold mb-1"><?=e($editId?'Edit Deal':'Create Deal')?></h1><p class="text-muted mb-0">Display and enquiry only. Customer payment is not collected by MJ Marketplace.</p></div><a class="btn btn-outline-primary rounded-pill" href="<?=base_url('my-deals.php')?>">Back</a></div>
<form method="post" enctype="multipart/form-data" class="mj-center-card"><div class="card-body"><?=csrf_input()?><input type="hidden" name="id" value="<?=(int)($d['id']??0)?>"><div class="alert alert-info rounded-4"><b>No checkout:</b> Customers will contact you by enquiry, WhatsApp, call or email. You handle final payment directly.</div><?php if($pendingRevision): ?><div class="alert alert-warning rounded-4"><b>Pending update review:</b> Your latest deal changes are waiting for admin approval. The current public deal remains live.</div><?php endif; ?>
<div class="row g-3"><div class="col-lg-8"><label class="form-label">Deal Title *</label><input class="form-control form-control-lg" name="title" required value="<?=e($d['title'])?>"><label class="form-label mt-3">Short Description</label><input class="form-control" name="short_description" maxlength="500" value="<?=e($d['short_description'])?>"><label class="form-label mt-3">Description</label><textarea class="form-control" name="description" rows="7"><?=e($d['description'])?></textarea></div><div class="col-lg-4"><label class="form-label">Deal Image</label><?php if($d['image_path']): ?><img class="img-fluid rounded mb-2" src="<?=e(base_url($d['image_path']))?>"><?php endif; ?><input type="file" name="image" class="form-control" accept="image/*"><small class="text-muted">Add clear image for better enquiries.</small></div></div>
<div class="row g-3 mt-1"><div class="col-md-3"><label class="form-label">Type</label><select class="form-select" name="deal_type"><?php foreach(['normal'=>'Normal','flash'=>'Flash','city'=>'City','service'=>'Service','product'=>'Product','consultation'=>'Free Consultation','quote'=>'Quote Required'] as $k=>$v): ?><option value="<?=e($k)?>" <?=$d['deal_type']===$k?'selected':''?>><?=e($v)?></option><?php endforeach; ?></select></div><div class="col-md-3"><label class="form-label">Original Price</label><input class="form-control" name="original_price" type="number" step="0.01" min="0" value="<?=e($d['original_price'])?>"></div><div class="col-md-3"><label class="form-label">Offer Price</label><input class="form-control" name="deal_price" type="number" step="0.01" min="0" value="<?=e($d['deal_price'])?>"></div><div class="col-md-3"><label class="form-label">Currency</label><input class="form-control" name="currency_code" value="<?=e($d['currency_code']?:($user['preferred_currency']??'SGD'))?>"></div><div class="col-md-12"><label class="form-label">Price Note</label><input class="form-control" name="price_note" value="<?=e($d['price_note'])?>" placeholder="Example: From SGD 99 / Contact for quote"></div></div>
<div class="row g-3 mt-1"><div class="col-md-6"><label class="form-label">Company</label><select class="form-select" name="company_id"><option value="0">Direct seller / no company</option><?php foreach($companies as $co): ?><option value="<?=(int)$co['id']?>" <?=(int)$d['company_id']===(int)$co['id']?'selected':''?>><?=e($co['name'])?></option><?php endforeach; ?></select></div><div class="col-md-6"><label class="form-label">Category</label><select class="form-select" name="category_id"><option value="0">Select category</option><?php foreach($categories as $cat): ?><option value="<?=(int)$cat['id']?>" <?=(int)$d['category_id']===(int)$cat['id']?'selected':''?>><?=e($cat['name'])?></option><?php endforeach; ?></select></div><div class="col-md-6"><label class="form-label">Country</label><select class="form-select" name="country_id"><option value="0">Select country</option><?php foreach($countries as $c): ?><option value="<?=(int)$c['id']?>" <?=(int)$d['country_id']===(int)$c['id']?'selected':''?>><?=e($c['name'])?></option><?php endforeach; ?></select></div><div class="col-md-6"><label class="form-label">City</label><select class="form-select" name="city_id"><option value="0">All cities / no city</option><?php foreach($cities as $ci): ?><option value="<?=(int)$ci['id']?>" <?=(int)$d['city_id']===(int)$ci['id']?'selected':''?>><?=e($ci['name'])?></option><?php endforeach; ?></select></div></div>
<div class="row g-3 mt-1"><div class="col-md-6"><label class="form-label">Start</label><input class="form-control" type="datetime-local" name="start_at" value="<?=e(!empty($d['start_at'])?date('Y-m-d\TH:i',strtotime($d['start_at'])):'')?>"></div><div class="col-md-6"><label class="form-label">End</label><input class="form-control" type="datetime-local" name="end_at" value="<?=e(!empty($d['end_at'])?date('Y-m-d\TH:i',strtotime($d['end_at'])):'')?>"></div><div class="col-md-4"><label class="form-label">Phone</label><input class="form-control" name="contact_phone" value="<?=e($d['contact_phone']?:($user['mobile']??''))?>"></div><div class="col-md-4"><label class="form-label">WhatsApp</label><input class="form-control" name="contact_whatsapp" value="<?=e($d['contact_whatsapp'])?>"></div><div class="col-md-4"><label class="form-label">Email</label><input class="form-control" type="email" name="contact_email" value="<?=e($d['contact_email']?:($user['email']??''))?>"></div><div class="col-12"><label class="form-label">Terms</label><textarea class="form-control" name="terms" rows="3"><?=e($d['terms']?:'Contact seller before visiting. Payment and final transaction are handled directly between customer and seller.')?></textarea></div></div>
<div class="d-flex gap-2 mt-4"><button name="save_type" value="draft" class="btn btn-outline-secondary rounded-pill px-4">Save Draft</button><button name="save_type" value="submit" class="btn btn-primary rounded-pill px-4">Submit Deal</button></div>
</div></form>
</div></div></div></section>
<?php include __DIR__.'/includes/footer.php'; ?>
