<?php
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/mj_deal_helpers.php';
mj_deal_ensure_schema();
$id=(int)($_GET['id']??0);
$deal=$id>0?mj_deal_fetch($id,true):null;
if(!$deal){ $pageTitle='Deal Not Found'; include __DIR__.'/includes/header.php'; echo '<section class="container py-5"><div class="mj-card p-5 text-center"><h1 class="h3">Deal not found or expired</h1><p class="text-muted">This deal may be expired, hidden or waiting for approval.</p><a class="btn btn-primary" href="'.e(base_url('deals.php')).'">Browse Deals</a></div></section>'; include __DIR__.'/includes/footer.php'; exit; }
$contact=mj_deal_contact($deal);
$action=trim((string)($_GET['action']??''));
if($action!=='' && in_array($action,['whatsapp','call','email','share','qr'],true)){
    mj_deal_track_event((int)$deal['id'],$action);
    if($action==='whatsapp' && $contact['whatsapp_digits']){ redirect('https://wa.me/'.$contact['whatsapp_digits'].'?text='.rawurlencode('Hi, I am interested in this deal: '.$deal['title'].' '.mj_deal_public_url($deal))); }
    if($action==='call' && $contact['phone']){ redirect('tel:'.preg_replace('/[^0-9+]/','',$contact['phone'])); }
    if($action==='email' && filter_var($contact['email'],FILTER_VALIDATE_EMAIL)){ redirect('mailto:'.$contact['email'].'?subject='.rawurlencode('Deal enquiry: '.$deal['title']).'&body='.rawurlencode('Hi, I am interested in this deal: '.mj_deal_public_url($deal))); }
    redirect('deal.php?id='.(int)$deal['id'].'&tracked=1');
}
verify_csrf();
if($_SERVER['REQUEST_METHOD']==='POST'){
    $res=mj_deal_submit_enquiry($deal,$_POST);
    if(!empty($res['success'])){ flash('success','Your enquiry was sent. Seller will contact you directly.'); redirect('deal.php?id='.(int)$deal['id'].'#enquiry'); }
    flash('error',$res['error']??'Unable to send enquiry.');
}
mj_deal_track_event((int)$deal['id'],'view');
$pageTitle=$deal['title'];
$metaDescription=$deal['short_description'] ?: mb_strimwidth(strip_tags((string)$deal['description']),0,155,'...');
$img=$deal['image_path']?base_url($deal['image_path']):asset('images/no-image.png');
$disc=(float)($deal['discount_percent']??0);
$publicUrl=mj_deal_public_url($deal);
$qr=function_exists('mj263_qr_url')?mj263_qr_url($publicUrl,220):'';
include __DIR__.'/includes/header.php';
?>
<section class="container py-4 py-lg-5">
  <div class="row g-4">
    <div class="col-lg-7">
      <div class="mj-deal-detail-img mb-4"><img src="<?=e($img)?>" alt="<?=e($deal['title'])?>"><?php if($disc>0): ?><span><?=e((string)(int)$disc)?>% OFF</span><?php endif; ?></div>
      <div class="mj-card p-4 mb-4">
        <div class="d-flex flex-wrap gap-2 mb-3"><?php if(!empty($deal['is_sponsored'])): ?><span class="badge text-bg-success rounded-pill">Sponsored</span><?php endif; ?><?php if(!empty($deal['is_featured'])): ?><span class="badge text-bg-primary rounded-pill">Featured</span><?php endif; ?><span class="badge text-bg-light rounded-pill"><?=e($deal['category_name'] ?: 'Deal')?></span><span class="badge text-bg-light rounded-pill"><i class="bi bi-geo-alt me-1"></i><?=e(trim(($deal['city_name']?:'').' '.($deal['country_name']?:'')) ?: 'Contact seller')?></span></div>
        <h1 class="display-6 fw-bold mb-3"><?=e($deal['title'])?></h1>
        <p class="lead text-muted"><?=e($deal['short_description'] ?: '')?></p>
        <div class="mj-price-panel d-flex flex-wrap align-items-end gap-3 my-4">
          <?php if((float)$deal['deal_price']>0): ?><div><div class="h2 fw-bold text-primary mb-0"><?=money($deal['deal_price'],$deal['currency_code'])?></div><?php if((float)$deal['original_price']>0): ?><div class="text-muted"><s><?=money($deal['original_price'],$deal['currency_code'])?></s></div><?php endif; ?></div><?php else: ?><div class="h3 fw-bold text-primary mb-0"><?=e($deal['price_note'] ?: 'Contact seller for price')?></div><?php endif; ?>
          <?php if($deal['end_at']): ?><div class="ms-auto small text-muted"><i class="bi bi-clock me-1"></i>Ends <?=e(date('d M Y, H:i',strtotime($deal['end_at'])))?></div><?php endif; ?>
        </div>
        <div class="alert alert-info rounded-4"><i class="bi bi-shield-lock me-1"></i><b>No online payment here.</b> MJ Marketplace shows this deal for enquiry only. Customer and seller handle final transaction directly.</div>
        <h2 class="h5 fw-bold mt-4">Deal Details</h2>
        <div class="mj-richtext"><?=nl2br(e((string)$deal['description']))?></div>
        <?php if(!empty($deal['terms'])): ?><h2 class="h5 fw-bold mt-4">Terms & Conditions</h2><div class="mj-richtext"><?=nl2br(e((string)$deal['terms']))?></div><?php endif; ?>
      </div>
    </div>
    <div class="col-lg-5">
      <div class="mj-card p-4 mb-4 sticky-lg-top" style="top:95px">
        <h2 class="h5 fw-bold mb-3">Contact Seller</h2>
        <?php if(!empty($deal['company_name'])): ?><div class="mb-3"><b><?=e($deal['company_name'])?></b><br><span class="text-muted small"><?=e($deal['company_address'] ?? '')?></span></div><?php endif; ?>
        <div class="d-grid gap-2 mb-3">
          <?php if($contact['whatsapp_digits']): ?><a class="btn btn-success rounded-pill" href="<?=e(base_url('deal.php?id='.(int)$deal['id'].'&action=whatsapp'))?>"><i class="bi bi-whatsapp me-1"></i>WhatsApp Seller</a><?php endif; ?>
          <?php if($contact['phone']): ?><a class="btn btn-outline-primary rounded-pill" href="<?=e(base_url('deal.php?id='.(int)$deal['id'].'&action=call'))?>"><i class="bi bi-telephone me-1"></i>Call Seller</a><?php endif; ?>
          <?php if(filter_var($contact['email'],FILTER_VALIDATE_EMAIL)): ?><a class="btn btn-outline-primary rounded-pill" href="<?=e(base_url('deal.php?id='.(int)$deal['id'].'&action=email'))?>"><i class="bi bi-envelope me-1"></i>Email Seller</a><?php endif; ?>
        </div>
        <div class="small text-muted mb-3">Contact clicks are tracked for seller performance. Payment is not processed by this website.</div>
        <hr>
        <h3 id="enquiry" class="h5 fw-bold mb-3">Send Enquiry</h3>
        <form method="post" class="mj-clean-form"><?=csrf_input()?>
          <div class="mb-2"><label class="form-label">Name *</label><input class="form-control" name="name" required value="<?=e($user['name'] ?? '')?>"></div>
          <div class="row g-2"><div class="col-md-6 mb-2"><label class="form-label">Email</label><input class="form-control" type="email" name="email" value="<?=e($user['email'] ?? '')?>"></div><div class="col-md-6 mb-2"><label class="form-label">Phone</label><input class="form-control" name="phone" value="<?=e($user['mobile'] ?? '')?>"></div></div>
          <div class="mb-2"><label class="form-label">Preferred Date / Time</label><input class="form-control" name="preferred_datetime" placeholder="Optional"></div>
          <div class="mb-3"><label class="form-label">Message *</label><textarea class="form-control" name="message" rows="4" required>I am interested in this deal. Please contact me.</textarea></div>
          <button class="btn btn-primary w-100 rounded-pill"><i class="bi bi-send me-1"></i>Send Enquiry</button>
        </form>
      </div>
      <div class="mj-card p-4 text-center">
        <h3 class="h6 fw-bold">Share Deal</h3>
        <?php if($qr): ?><img src="<?=e($qr)?>" alt="QR" class="img-fluid rounded mb-3" style="max-width:180px"><?php endif; ?>
        <div class="d-flex gap-2 justify-content-center"><a class="btn btn-sm btn-outline-primary" href="https://wa.me/?text=<?=rawurlencode($deal['title'].' '.$publicUrl)?>" target="_blank" onclick="fetch('<?=e(base_url('deal.php?id='.(int)$deal['id'].'&action=share'))?>').catch(()=>{})"><i class="bi bi-share me-1"></i>Share</a><button class="btn btn-sm btn-outline-secondary" onclick="navigator.clipboard.writeText('<?=e($publicUrl)?>');this.innerText='Copied';">Copy Link</button></div>
      </div>
    </div>
  </div>
</section>
<?php include __DIR__.'/includes/footer.php'; ?>
