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

$listingId = (int)($_GET['listing_id'] ?? $_POST['listing_id'] ?? 0);
$listing = one('SELECT l.*, u.name seller_name, co.name company_name,
    (SELECT li.image_path FROM mj_listing_images li WHERE li.listing_id=l.id ORDER BY li.sort_order,li.id LIMIT 1) listing_image
    FROM mj_listings l
    LEFT JOIN mj_users u ON u.id=l.user_id
    LEFT JOIN mj_companies co ON co.id=l.company_id
    WHERE l.id=? LIMIT 1', [$listingId]);

if (!$listing) {
    $pageTitle='Listing not found';
    include __DIR__.'/includes/header.php';
    echo '<section class="mj-section"><div class="container"><div class="mj-card p-5 text-center"><h1 class="fw-bold">Listing not found</h1><p class="text-muted">Please choose an active listing before making an offer.</p><a class="btn btn-primary" href="'.e(base_url('browse.php')).'">Browse Listings</a></div></div></section>';
    include __DIR__.'/includes/footer.php';
    exit;
}

if ((int)$listing['user_id'] === (int)$u['id']) {
    flash('warning', 'You cannot make an offer on your own listing.');
    redirect('listing.php?id='.(int)$listing['id']);
}

$listingStatus = strtolower((string)($listing['status'] ?? 'active'));
if (in_array($listingStatus, ['sold','deleted','rejected','suspended'], true)) {
    flash('warning', 'This listing is not available for offers.');
    redirect('listing.php?id='.(int)$listing['id']);
}

$duplicate = null;
try {
    $duplicate = one('SELECT * FROM mj_offers WHERE listing_id=? AND buyer_id=? AND status IN ("pending","countered") ORDER BY id DESC LIMIT 1', [(int)$listing['id'], (int)$u['id']]);
} catch (Throwable $e) {}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        if ($duplicate) { throw new Exception('You already have an active offer for this listing. Please review it before sending a new one.'); }
        $amount = (float)($_POST['amount'] ?? 0);
        $message = trim((string)($_POST['message'] ?? ''));
        if ($amount <= 0) { throw new Exception('Please enter a valid offer amount.'); }
        if ($amount > 999999999) { throw new Exception('Offer amount is too high. Please check the amount.'); }
        if (function_exists('mb_strlen') ? mb_strlen($message) > 1000 : strlen($message) > 1000) { throw new Exception('Message is too long. Please keep it under 1000 characters.'); }

        $currency = $listing['currency_code'] ?: 'SGD';
        q('INSERT INTO mj_offers(listing_id,buyer_id,seller_id,amount,currency_code,status,message,expires_at,last_action_by,last_action_at,created_at,updated_at) VALUES(?,?,?,?,?,"pending",?,DATE_ADD(NOW(), INTERVAL 3 DAY),?,NOW(),NOW(),NOW())', [
            (int)$listing['id'],
            (int)$u['id'],
            (int)$listing['user_id'],
            $amount,
            $currency,
            $message,
            (int)$u['id']
        ]);
        $offerId = (int)db()->lastInsertId();

        if (mj_column_exists('mj_listings','offer_count')) {
            try { q('UPDATE mj_listings SET offer_count=COALESCE(offer_count,0)+1, engagement_count=COALESCE(engagement_count,0)+1, last_engaged_at=NOW() WHERE id=?', [(int)$listing['id']]); } catch(Throwable $e) {}
        }

        mj_offer_timeline_add($offerId, (int)$u['id'], 'sent', 'Buyer sent an offer.', '', 'pending');

        $offer = mj_offer_fetch($offerId);
        if ($offer) {
            $event = 'Offer sent: '.money($amount, $currency).($message!=='' ? ' - '.$message : '');
            $offer['last_action_by'] = (int)$u['id'];
            mj_offer_create_or_open_chat($offer, $event);
        }

        mj_offer_safe_notify_user((int)$listing['user_id'], 'offer_received', 'New offer received', ($listing['title'] ?? 'Listing').' - '.money($amount,$currency), 'offer-view.php?id='.$offerId, 'high');

        flash('success','Offer sent successfully. You can track it in My Offers.');
        redirect('offer-view.php?id='.$offerId);
    } catch(Throwable $e) {
        flash('error', $e->getMessage());
    }
}

$pageTitle='Make Offer';
$img = !empty($listing['listing_image']) ? base_url($listing['listing_image']) : asset('images/empty-state.svg');
include __DIR__.'/includes/header.php';
?>
<section class="mj-page-hero">
  <div class="container">
    <span class="mj-badge mb-2"><i class="bi bi-cash-coin"></i> Make Offer</span>
    <h1 class="fw-bold display-5 mb-1">Send a price offer</h1>
    <p class="text-muted mb-0">Make a fair offer and continue safely through MJ Marketplace chat. No payment is collected by the website.</p>
  </div>
</section>

<section class="mj-section">
  <div class="container">
    <?php show_flash(); ?>
    <div class="row g-4">
      <div class="col-lg-5">
        <div class="mj-card p-4">
          <div class="d-flex gap-3">
            <img src="<?=e($img)?>" class="mj-offer-listing-img" alt="<?=e($listing['title'])?>">
            <div>
              <span class="mj-badge mb-2"><?=e($listing['company_name'] ?: 'Marketplace listing')?></span>
              <h3 class="fw-bold"><?=e($listing['title'])?></h3>
              <div class="mj-listing-price"><?=money($listing['price'],$listing['currency_code'] ?: 'SGD')?></div>
              <p class="text-muted mb-0">Seller: <?=e($listing['seller_name'] ?: 'Seller')?></p>
            </div>
          </div>
          <hr>
          <div class="alert alert-warning rounded-4 mb-0">
            <i class="bi bi-shield-check me-1"></i>
            MJ Marketplace does not collect customer-to-seller payments. Use this offer/chat only to discuss details. Never share OTP or bank login details.
          </div>
        </div>
      </div>

      <div class="col-lg-7">
        <div class="mj-card p-4">
          <?php if($duplicate): ?>
            <div class="alert alert-info rounded-4">
              <b>You already have an active offer.</b><br>
              Offer amount: <?=money($duplicate['amount'],$duplicate['currency_code'] ?: ($listing['currency_code'] ?: 'SGD'))?>.
              <a class="fw-bold" href="<?=e(base_url('offer-view.php?id='.(int)$duplicate['id']))?>">View active offer</a>
            </div>
          <?php endif; ?>

          <h3 class="fw-bold">Your offer details</h3>
          <form method="post">
            <?=csrf_input()?>
            <input type="hidden" name="listing_id" value="<?=e($listing['id'])?>">
            <div class="mb-3">
              <label class="form-label fw-bold">Offer amount <span class="text-danger">*</span></label>
              <div class="input-group">
                <span class="input-group-text"><?=e($listing['currency_code'] ?: 'SGD')?></span>
                <input class="form-control" type="number" step="0.01" min="0.01" name="amount" required placeholder="Enter your offer amount">
              </div>
              <small class="text-muted">Current listing price: <?=money($listing['price'],$listing['currency_code'] ?: 'SGD')?></small>
            </div>
            <div class="mb-3">
              <label class="form-label fw-bold">Message to seller</label>
              <textarea class="form-control" name="message" rows="5" maxlength="1000" placeholder="Example: Is this still available? I can collect today."></textarea>
            </div>
            <button class="btn btn-primary btn-lg rounded-pill" <?=$duplicate?'disabled':''?>><i class="bi bi-send me-1"></i>Send Offer</button>
            <a class="btn btn-outline-secondary btn-lg rounded-pill" href="<?=e(base_url('listing.php?id='.(int)$listing['id']))?>">Back to Listing</a>
          </form>
        </div>
      </div>
    </div>
  </div>
</section>
<?php include __DIR__.'/includes/footer.php'; ?>
