<?php
require_once __DIR__.'/includes/functions.php';
$u = require_user();
verify_csrf();
mj_ensure_listing_module_schema(true);
mj_user_limits_ensure_schema();

$limitInfo = mj_user_can_add_listing((int)$u['id']);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $limitInfo = mj_user_can_add_listing((int)$u['id']);
        if (!$limitInfo['allowed']) {
            throw new Exception('Listing limit reached. '.$limitInfo['message'].' Please contact admin to increase your listing limit.');
        }

        $country = one('SELECT * FROM mj_countries WHERE id=?', [(int)$_POST['country_id']]);
        if (!$country) { throw new Exception('Country required.'); }

        $title = trim((string)($_POST['title'] ?? ''));
        if ($title === '') { throw new Exception('Title required.'); }

        $slug = slugify($title).'-'.time();
        $tz = trim((string)($_POST['timezone'] ?? '')) ?: ($country['timezone_default'] ?? 'UTC');
        $status = setting('listing_approval_required','1') === '1' ? 'pending' : 'active';
        $expiresAt = $status === 'active' ? mj_listing_default_expiry() : null;

        q('INSERT INTO mj_listings(user_id,category_id,country_id,state_id,city_id,timezone,listing_type,title,slug,description,price,currency_code,condition_label,status,expires_at,published_at,created_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,NOW(),NOW())', [
            (int)$u['id'],
            $_POST['category_id'] ?: null,
            (int)$country['id'],
            $_POST['state_id'] ?: null,
            $_POST['city_id'] ?: null,
            $tz,
            $_POST['listing_type'] ?? 'product',
            $title,
            $slug,
            $_POST['description'] ?? '',
            (float)($_POST['price'] ?? 0),
            $country['currency_code'] ?? 'SGD',
            $_POST['condition_label'] ?? 'Used',
            $status,
            $expiresAt
        ]);

        $id = (int)db()->lastInsertId();
        for ($i=1; $i<=5; $i++) {
            $path = upload_image('image'.$i, 'listings');
            if ($path) { q('INSERT INTO mj_listing_images(listing_id,image_path,sort_order) VALUES(?,?,?)', [$id,$path,$i]); }
        }

        flash('success','Listing submitted.');
        redirect('listing.php?id='.$id);
    } 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 type="marketplace" AND is_active=1 ORDER BY sort_order,name');
$pageTitle = 'Post Listing';
include __DIR__.'/includes/header.php';
?>
<section class="mj-page-hero">
  <div class="container">
    <span class="mj-badge mb-2"><i class="bi bi-plus-circle"></i>Post Listing</span>
    <h1 class="fw-bold display-5 mb-1">Post a new listing</h1>
    <p class="text-muted mb-0">Create a clear listing with photos, price and location so buyers can contact you easily.</p>
  </div>
</section>

<section class="mj-section">
  <div class="container">
    <?php show_flash(); ?>

    <div class="row g-4">
      <div class="col-lg-3">
        <?php include __DIR__.'/includes/account-sidebar.php'; ?>
      </div>
      <div class="col-lg-9">
        <div class="mj-card p-3 mb-4">
          <div class="d-flex flex-wrap justify-content-between align-items-center gap-3">
            <div>
              <h5 class="fw-bold mb-1"><i class="bi bi-speedometer2 me-1"></i>Your listing limit</h5>
              <p class="text-muted mb-0 small"><?=e($limitInfo['message'])?></p>
            </div>
            <?php if(!$limitInfo['allowed']): ?>
              <span class="mj-badge warn">Limit reached</span>
            <?php else: ?>
              <span class="mj-badge good">Available</span>
            <?php endif; ?>
          </div>
        </div>

        <?php if(!$limitInfo['allowed']): ?>
          <div class="mj-card p-5 text-center">
            <div class="mj-icon-box mx-auto mb-3"><i class="bi bi-lock"></i></div>
            <h3 class="fw-bold">Listing limit reached</h3>
            <p class="text-muted">You cannot post more listings right now. Please contact admin if you need more listing slots.</p>
            <?php if(mj_user_feature_enabled('extra_listing_slots',(int)$u['id'])): ?><a class="btn btn-primary rounded-pill" href="<?=e(base_url('request-more-slots.php?type=listing'))?>">Request More Listing Slots</a><?php else: ?><span class="btn btn-outline-secondary rounded-pill disabled">Extra Slots Disabled</span><?php endif; ?> <a class="btn btn-outline-primary rounded-pill" href="<?=e(base_url('my-listings.php'))?>">View My Listings</a>
          </div>
        <?php else: ?>
          <form method="post" enctype="multipart/form-data" class="mj-card p-4">
            <?=csrf_input()?>
            <h3 class="fw-bold mb-3">Listing details</h3>

            <label class="form-label fw-bold">Title <span class="text-danger">*</span></label>
            <input class="form-control mb-3" name="title" required placeholder="Example: Professional Hard Disk Data Recovery">

            <div class="row g-3">
              <div class="col-md-6">
                <label class="form-label fw-bold">Country <span class="text-danger">*</span></label>
                <select class="form-select" name="country_id" onchange="loadStates(this.value,'state_id')" required>
                  <option value="">Select</option>
                  <?php foreach($countries as $c): ?><option value="<?=e($c['id'])?>"><?=e($c['flag_emoji'].' '.$c['name'])?></option><?php endforeach; ?>
                </select>
              </div>
              <div class="col-md-6">
                <label class="form-label fw-bold">Category</label>
                <select class="form-select" name="category_id">
                  <?php foreach($cats as $cat): ?><option value="<?=e($cat['id'])?>"><?=e($cat['name'])?></option><?php endforeach; ?>
                </select>
              </div>
              <div class="col-md-6">
                <label class="form-label fw-bold">State</label>
                <select class="form-select" name="state_id" id="state_id" onchange="loadCities(this.value,'city_id')"><option value="">State</option></select>
              </div>
              <div class="col-md-6">
                <label class="form-label fw-bold">City</label>
                <select class="form-select" name="city_id" id="city_id"><option value="">City</option></select>
              </div>
              <div class="col-md-6">
                <label class="form-label fw-bold">Price</label>
                <input class="form-control" name="price" type="number" step="0.01" min="0" placeholder="0.00">
              </div>
              <div class="col-md-6">
                <label class="form-label fw-bold">Condition</label>
                <input class="form-control" name="condition_label" value="Used">
              </div>
            </div>

            <label class="form-label fw-bold mt-3">Timezone</label>
            <input class="form-control mb-3" name="timezone" placeholder="Auto from country/city if empty">

            <label class="form-label fw-bold">Description</label>
            <textarea class="form-control mb-3" name="description" rows="6" placeholder="Describe item/service details, condition, warranty, location or collection options."></textarea>

            <label class="form-label fw-bold">Photos</label>
            <?php for($i=1;$i<=5;$i++): ?>
              <input class="form-control mb-2" type="file" name="image<?=$i?>" accept="image/*">
            <?php endfor; ?>

            <button class="btn btn-primary btn-lg rounded-pill mt-3"><i class="bi bi-send me-1"></i>Submit Listing</button>
          </form>
        <?php endif; ?>
      </div>
    </div>
  </div>
</section>
<?php include __DIR__.'/includes/footer.php'; ?>
