<?php
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/mj_deal_helpers.php';
$admin = require_admin();
mj_deal_ensure_schema();
verify_csrf();
$editId = (int)($_GET['edit'] ?? $_POST['id'] ?? 0);
$deal = $editId ? one('SELECT * FROM mj_deals WHERE id=? LIMIT 1', [$editId]) : null;
$adminTitle = $deal ? 'Edit Deal' : 'Add Deal';
$adminSubtitle = 'Create clean display-only deals with enquiry/contact actions. No customer checkout or seller payment collection.';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $id = (int)($_POST['id'] ?? 0);
        $existing = $id > 0 ? one('SELECT * FROM mj_deals WHERE id=? LIMIT 1', [$id]) : null;
        $title = trim((string)($_POST['title'] ?? ''));
        if ($title === '') { throw new RuntimeException('Deal title is required.'); }
        if (mb_strlen($title) < 5) { throw new RuntimeException('Deal title is too short.'); }
        $original = (float)($_POST['original_price'] ?? 0);
        $price = (float)($_POST['deal_price'] ?? 0);
        if ($original < 0 || $price < 0) { throw new RuntimeException('Price cannot be negative.'); }
        if ($original > 0 && $price > $original) { throw new RuntimeException('Deal price cannot be greater than original price.'); }
        $startAt = trim((string)($_POST['start_at'] ?? '')) ?: null;
        $endAt = trim((string)($_POST['end_at'] ?? '')) ?: null;
        if ($startAt && $endAt && strtotime($endAt) < strtotime($startAt)) { throw new RuntimeException('End date must be after start date.'); }
        $image = $existing['image_path'] ?? '';
        if (!empty($_FILES['image']['name'])) { $image = upload_image('image', 'deals'); }
        $data = [
            'user_id' => (int)($_POST['user_id'] ?? 0) ?: null,
            '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' => $original,
            'deal_price' => $price,
            'discount_percent' => mj_deal_discount_percent($original, $price),
            'price_note' => trim((string)($_POST['price_note'] ?? '')),
            'currency_code' => strtoupper(substr(preg_replace('/[^A-Z]/i','', (string)($_POST['currency_code'] ?? 'SGD')),0,8)) ?: 'SGD',
            'start_at' => $startAt ? date('Y-m-d H:i:s', strtotime($startAt)) : null,
            'end_at' => $endAt ? date('Y-m-d H:i:s', strtotime($endAt)) : null,
            'status' => trim((string)($_POST['status'] ?? 'pending')),
            'is_featured' => isset($_POST['is_featured']) ? 1 : 0,
            'is_sponsored' => isset($_POST['is_sponsored']) ? 1 : 0,
            'featured_until' => trim((string)($_POST['featured_until'] ?? '')) ? date('Y-m-d H:i:s', strtotime((string)$_POST['featured_until'])) : null,
            'sponsored_until' => trim((string)($_POST['sponsored_until'] ?? '')) ? date('Y-m-d H:i:s', strtotime((string)$_POST['sponsored_until'])) : null,
            'contact_phone' => trim((string)($_POST['contact_phone'] ?? '')),
            'contact_whatsapp' => trim((string)($_POST['contact_whatsapp'] ?? '')),
            'contact_email' => trim((string)($_POST['contact_email'] ?? '')),
            'terms' => trim((string)($_POST['terms'] ?? '')),
            'admin_note' => trim((string)($_POST['admin_note'] ?? '')),
        ];
        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);
        $data = mj_deal_filter_existing_columns($data);
        if ($id > 0 && $existing) {
            $sets=[]; $params=[]; foreach($data as $k=>$v){ $sets[]='`'.$k.'`=?'; $params[]=$v; }
            $sets[]='updated_at=NOW()'; $params[]=$id;
            q('UPDATE mj_deals SET '.implode(',',$sets).' WHERE id=?', $params);
            admin_log('deal_updated','mj_deals',$id,['title'=>$title]);
            flash('success','Deal updated successfully.');
        } else {
            $cols=array_keys($data); $ph=array_fill(0,count($cols),'?');
            q('INSERT INTO mj_deals(`'.implode('`,`',$cols).'`,created_at,updated_at) VALUES('.implode(',',$ph).',NOW(),NOW())', array_values($data));
            $id=(int)db()->lastInsertId();
            admin_log('deal_created','mj_deals',$id,['title'=>$title]);
            flash('success','Deal created successfully.');
        }
        redirect('deals.php');
    } catch (Throwable $e) { flash('error',$e->getMessage()); $deal = array_merge($deal ?: [], $_POST); }
}

$defaults = mj_deal_column_defaults();
$d = array_merge($defaults, $deal ?: []);
$users = table_exists('mj_users') ? all_rows('SELECT id,name,email FROM mj_users WHERE is_active=1 ORDER BY name LIMIT 1000') : [];
$companies = table_exists('mj_companies') ? all_rows('SELECT id,name,user_id FROM mj_companies ORDER BY name LIMIT 1000') : [];
$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__ . '/_header.php';
?>
<form method="post" enctype="multipart/form-data">
<?= csrf_input() ?><input type="hidden" name="id" value="<?= (int)($d['id'] ?? 0) ?>">
<div class="row">
  <div class="col-lg-8">
    <div class="card card-primary card-outline">
      <div class="card-header"><h3 class="card-title"><i class="fas fa-fire mr-2"></i><?= e($adminTitle) ?></h3></div>
      <div class="card-body">
        <div class="alert alert-info"><b>Display only:</b> No customer checkout, voucher purchase, refund, payout, or customer-to-seller payment is available for deals.</div>
        <div class="form-group"><label>Deal Title <span class="text-danger">*</span></label><input class="form-control form-control-lg" name="title" required maxlength="255" value="<?= e($d['title']) ?>" placeholder="Example: 30% Off Data Recovery Diagnosis"></div>
        <div class="form-row">
          <div class="form-group col-md-4"><label>Deal Type</label><select class="form-control" name="deal_type"><?php foreach(['normal'=>'Normal Deal','flash'=>'Flash Deal','city'=>'City Deal','service'=>'Service Deal','product'=>'Product Promotion','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="form-group col-md-4"><label>Status</label><select class="form-control" name="status"><?php foreach(['draft','pending','active','paused','expired','rejected','hidden'] as $s): ?><option value="<?= e($s) ?>" <?= ($d['status']===$s?'selected':'') ?>><?= e(ucwords($s)) ?></option><?php endforeach; ?></select></div>
          <div class="form-group col-md-4"><label>Currency</label><input class="form-control" name="currency_code" maxlength="8" value="<?= e($d['currency_code']) ?>"></div>
        </div>
        <div class="form-group"><label>Short Description</label><input class="form-control" name="short_description" maxlength="500" value="<?= e($d['short_description']) ?>" placeholder="Short one-line highlight for deal cards"></div>
        <div class="form-group"><label>Full Description</label><textarea class="form-control" name="description" rows="6" placeholder="Describe the offer, included service/product, conditions and seller contact instructions."><?= e($d['description']) ?></textarea></div>
        <div class="form-row">
          <div class="form-group col-md-4"><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="form-group col-md-4"><label>Deal / 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="form-group col-md-4"><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="form-row">
          <div class="form-group col-md-6"><label>Start Date/Time</label><input class="form-control" name="start_at" type="datetime-local" value="<?= e(!empty($d['start_at']) ? date('Y-m-d\TH:i', strtotime($d['start_at'])) : '') ?>"></div>
          <div class="form-group col-md-6"><label>End Date/Time</label><input class="form-control" name="end_at" type="datetime-local" value="<?= e(!empty($d['end_at']) ? date('Y-m-d\TH:i', strtotime($d['end_at'])) : '') ?>"></div>
        </div>
        <div class="form-row">
          <div class="form-group col-md-4"><label>Seller User</label><select class="form-control" name="user_id"><option value="0">No specific user</option><?php foreach($users as $u): ?><option value="<?= (int)$u['id'] ?>" <?= (int)$d['user_id']===(int)$u['id']?'selected':'' ?>><?= e($u['name'].' - '.$u['email']) ?></option><?php endforeach; ?></select></div>
          <div class="form-group col-md-4"><label>Company / Merchant</label><select class="form-control" 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="form-group col-md-4"><label>Category</label><select class="form-control" name="category_id"><option value="0">No 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>
        <div class="form-row">
          <div class="form-group col-md-6"><label>Country</label><select class="form-control" 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="form-group col-md-6"><label>City</label><select class="form-control" name="city_id"><option value="0">No city / All cities</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="form-row">
          <div class="form-group col-md-4"><label>Contact Phone</label><input class="form-control" name="contact_phone" value="<?= e($d['contact_phone']) ?>"></div>
          <div class="form-group col-md-4"><label>WhatsApp</label><input class="form-control" name="contact_whatsapp" value="<?= e($d['contact_whatsapp']) ?>" placeholder="Include country code if possible"></div>
          <div class="form-group col-md-4"><label>Contact Email</label><input class="form-control" name="contact_email" type="email" value="<?= e($d['contact_email']) ?>"></div>
        </div>
        <div class="form-group"><label>Terms & Conditions</label><textarea class="form-control" name="terms" rows="4" placeholder="Example: Appointment required. Payment handled directly with seller. MJ Marketplace does not collect customer payment."><?= e($d['terms']) ?></textarea></div>
      </div>
    </div>
  </div>
  <div class="col-lg-4">
    <div class="card card-primary card-outline"><div class="card-header"><h3 class="card-title">Image & Promotion</h3></div><div class="card-body">
      <?php if(!empty($d['image_path'])): ?><img class="img-fluid rounded mb-3" src="../<?= e($d['image_path']) ?>" alt="Deal image"><?php endif; ?>
      <div class="form-group"><label>Deal Image</label><input type="file" name="image" class="form-control-file" accept="image/*"><small class="form-text text-muted">JPG, PNG, WEBP or GIF. Max 8MB.</small></div>
      <div class="custom-control custom-switch mb-2"><input type="checkbox" class="custom-control-input" id="is_featured" name="is_featured" <?= !empty($d['is_featured'])?'checked':'' ?>><label class="custom-control-label" for="is_featured">Featured deal</label></div>
      <div class="form-group"><label>Featured Until</label><input class="form-control" name="featured_until" type="datetime-local" value="<?= e(!empty($d['featured_until']) ? date('Y-m-d\TH:i', strtotime($d['featured_until'])) : '') ?>"></div>
      <div class="custom-control custom-switch mb-2"><input type="checkbox" class="custom-control-input" id="is_sponsored" name="is_sponsored" <?= !empty($d['is_sponsored'])?'checked':'' ?>><label class="custom-control-label" for="is_sponsored">Sponsored deal</label></div>
      <div class="form-group"><label>Sponsored Until</label><input class="form-control" name="sponsored_until" type="datetime-local" value="<?= e(!empty($d['sponsored_until']) ? date('Y-m-d\TH:i', strtotime($d['sponsored_until'])) : '') ?>"></div>
      <div class="form-group"><label>Admin Note</label><textarea class="form-control" name="admin_note" rows="3"><?= e($d['admin_note']) ?></textarea></div>
      <div class="alert alert-light border"><b>Quality score:</b> <?= (int)($d['quality_score'] ?? 0) ?>%<br><small class="text-muted">Add image, clear description, price, terms and contact to improve score.</small></div>
      <button class="btn btn-primary btn-block"><i class="fas fa-save mr-1"></i>Save Deal</button>
      <a class="btn btn-light btn-block" href="deals.php">Cancel</a>
    </div></div>
  </div>
</div>
</form>
<?php include __DIR__ . '/_footer.php'; ?>
