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

$id = (int)($_GET['id'] ?? $_POST['offer_id'] ?? 0);
$offer = mj_offer_fetch($id);
if (!$offer || !mj_offer_can_view($offer, (int)$u['id'])) {
    $pageTitle='Offer 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">Offer not found</h1><p class="text-muted">This offer is not available or you do not have access.</p><a class="btn btn-primary" href="'.e(base_url('my-offers.php')).'">Back to Offers</a></div></div></section>';
    include __DIR__.'/includes/footer.php';
    exit;
}

$uid = (int)$u['id'];
$isBuyer = $uid === (int)$offer['buyer_id'];
$isSeller = $uid === (int)$offer['seller_id'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = trim((string)($_POST['action'] ?? ''));
    $old = (string)($offer['status'] ?? 'pending');
    try {
        if ($action === 'cancel' && $isBuyer && in_array($old, ['pending','countered'], true)) {
            q('UPDATE mj_offers SET status="cancelled", cancelled_at=NOW(), last_action_by=?, last_action_at=NOW(), updated_at=NOW() WHERE id=?', [$uid,$id]);
            mj_offer_timeline_add($id,$uid,'cancelled','Buyer cancelled the offer.',$old,'cancelled');
            $offer['status']='cancelled'; $offer['last_action_by']=$uid;
            mj_offer_create_or_open_chat($offer, 'Offer cancelled by buyer.');
            mj_offer_safe_notify_user((int)$offer['seller_id'], 'offer_cancelled', 'Offer cancelled', (string)$offer['listing_title'], 'offer-view.php?id='.$id, 'normal');
            flash('success','Offer cancelled.');
        } elseif ($action === 'accept' && $isSeller && in_array($old, ['pending','countered'], true)) {
            q('UPDATE mj_offers SET status="accepted", accepted_at=NOW(), last_action_by=?, last_action_at=NOW(), updated_at=NOW() WHERE id=?', [$uid,$id]);
            mj_offer_timeline_add($id,$uid,'accepted','Seller accepted the offer.',$old,'accepted');
            $offer['status']='accepted'; $offer['last_action_by']=$uid;
            $orderId = mj_order_create_from_offer($offer);
            mj_offer_create_or_open_chat($offer, 'Offer accepted by seller: '.money($offer['amount'],$offer['currency_code'] ?: 'SGD').($orderId ? ' | Enquiry record: MJ-ORD-'.date('Y').'-'.str_pad((string)$orderId,6,'0',STR_PAD_LEFT) : ''));
            mj_offer_safe_notify_user((int)$offer['buyer_id'], 'offer_accepted', 'Offer accepted', (string)$offer['listing_title'], 'offer-view.php?id='.$id, 'high');
            flash('success','Offer accepted. Enquiry record created and buyer has been notified. No payment is collected by MJ Marketplace.');
        } elseif ($action === 'reject' && $isSeller && in_array($old, ['pending','countered'], true)) {
            q('UPDATE mj_offers SET status="rejected", rejected_at=NOW(), last_action_by=?, last_action_at=NOW(), updated_at=NOW() WHERE id=?', [$uid,$id]);
            mj_offer_timeline_add($id,$uid,'rejected','Seller rejected the offer.',$old,'rejected');
            $offer['status']='rejected'; $offer['last_action_by']=$uid;
            mj_offer_create_or_open_chat($offer, 'Offer rejected by seller.');
            mj_offer_safe_notify_user((int)$offer['buyer_id'], 'offer_rejected', 'Offer rejected', (string)$offer['listing_title'], 'offer-view.php?id='.$id, 'normal');
            flash('success','Offer rejected.');
        } elseif ($action === 'counter' && $isSeller && in_array($old, ['pending','countered'], true)) {
            $counter = (float)($_POST['counter_amount'] ?? 0);
            $note = trim((string)($_POST['counter_note'] ?? ''));
            if ($counter <= 0) { throw new Exception('Please enter a valid counter offer amount.'); }
            q('UPDATE mj_offers SET status="countered", counter_amount=?, counter_by=?, message=CONCAT(COALESCE(message,""), ?), last_action_by=?, last_action_at=NOW(), updated_at=NOW() WHERE id=?', [
                $counter,$uid,$note!=='' ? "\n\nSeller counter note: ".$note : '',$uid,$id
            ]);
            mj_offer_timeline_add($id,$uid,'countered','Seller sent a counter offer: '.money($counter,$offer['currency_code'] ?: 'SGD'),$old,'countered');
            $offer['status']='countered'; $offer['counter_amount']=$counter; $offer['last_action_by']=$uid;
            mj_offer_create_or_open_chat($offer, 'Counter offer sent: '.money($counter,$offer['currency_code'] ?: 'SGD').($note!==''?' - '.$note:''));
            mj_offer_safe_notify_user((int)$offer['buyer_id'], 'offer_countered', 'Counter offer received', (string)$offer['listing_title'].' - '.money($counter,$offer['currency_code'] ?: 'SGD'), 'offer-view.php?id='.$id, 'high');
            flash('success','Counter offer sent.');
        } elseif ($action === 'accept_counter' && $isBuyer && $old === 'countered' && (float)($offer['counter_amount'] ?? 0) > 0) {
            q('UPDATE mj_offers SET amount=counter_amount, status="accepted", accepted_at=NOW(), last_action_by=?, last_action_at=NOW(), updated_at=NOW() WHERE id=?', [$uid,$id]);
            mj_offer_timeline_add($id,$uid,'accepted_counter','Buyer accepted the counter offer.',$old,'accepted');
            $offer['amount']=$offer['counter_amount']; $offer['status']='accepted'; $offer['last_action_by']=$uid;
            $orderId = mj_order_create_from_offer($offer);
            mj_offer_create_or_open_chat($offer, 'Buyer accepted counter offer: '.money($offer['amount'],$offer['currency_code'] ?: 'SGD').($orderId ? ' | Enquiry record: MJ-ORD-'.date('Y').'-'.str_pad((string)$orderId,6,'0',STR_PAD_LEFT) : ''));
            mj_offer_safe_notify_user((int)$offer['seller_id'], 'offer_accepted', 'Counter offer accepted', (string)$offer['listing_title'], 'offer-view.php?id='.$id, 'high');
            flash('success','Counter offer accepted. Enquiry record created. No payment is collected by MJ Marketplace.');
        } elseif ($action === 'reject_counter' && $isBuyer && $old === 'countered') {
            q('UPDATE mj_offers SET status="rejected", rejected_at=NOW(), last_action_by=?, last_action_at=NOW(), updated_at=NOW() WHERE id=?', [$uid,$id]);
            mj_offer_timeline_add($id,$uid,'rejected_counter','Buyer rejected the counter offer.',$old,'rejected');
            $offer['status']='rejected'; $offer['last_action_by']=$uid;
            mj_offer_create_or_open_chat($offer, 'Buyer rejected the counter offer.');
            mj_offer_safe_notify_user((int)$offer['seller_id'], 'offer_rejected', 'Counter offer rejected', (string)$offer['listing_title'], 'offer-view.php?id='.$id, 'normal');
            flash('success','Counter offer rejected.');
        } else {
            flash('warning','This action is not available.');
        }
    } catch(Throwable $e) {
        flash('error',$e->getMessage());
    }
    redirect('offer-view.php?id='.$id);
}

$offer = mj_offer_fetch($id);
$timeline = [];
try { $timeline = all_rows('SELECT t.*, u.name actor_name FROM mj_offer_timeline t LEFT JOIN mj_users u ON u.id=t.actor_id WHERE t.offer_id=? ORDER BY t.id DESC', [$id]); } catch(Throwable $e) {}
$img = !empty($offer['listing_image']) ? base_url($offer['listing_image']) : asset('images/empty-state.svg');
$showAmount = ((string)$offer['status']==='countered' && !empty($offer['counter_amount'])) ? (float)$offer['counter_amount'] : (float)$offer['amount'];
$pageTitle='Offer #'.$id;
include __DIR__.'/includes/header.php';
?>
<section class="mj-page-hero">
  <div class="container">
    <nav class="small mb-3"><a href="<?=e(base_url('my-offers.php'))?>">Offers</a> / Offer #<?=e($id)?></nav>
    <span class="badge text-bg-<?=e(mj_offer_status_class((string)$offer['status']))?> rounded-pill mb-2"><?=e(mj_offer_status_label((string)$offer['status']))?></span>
    <h1 class="fw-bold display-5 mb-1"><?=e($offer['listing_title'] ?: 'Offer Details')?></h1>
    <p class="text-muted mb-0">Manage offer amount, status, chat and timeline in one place.</p>
  </div>
</section>

<section class="mj-section">
  <div class="container">
    <?php show_flash(); ?>
    <div class="row g-4">
      <div class="col-lg-8">
        <div class="mj-card p-4 mb-4">
          <div class="d-flex gap-3 flex-wrap">
            <img src="<?=e($img)?>" class="mj-offer-listing-img" alt="<?=e($offer['listing_title'])?>">
            <div class="flex-grow-1">
              <h3 class="fw-bold"><?=e($offer['listing_title'] ?: 'Listing')?></h3>
              <p class="text-muted mb-2"><?= $isSeller ? 'Offer from '.e($offer['buyer_name'] ?: 'Buyer') : 'Offer to '.e($offer['seller_name'] ?: 'Seller') ?><?=!empty($offer['company_name'])?' • '.e($offer['company_name']):''?></p>
              <div class="row g-3">
                <div class="col-md-4"><div class="mj-offer-kpi"><span>Listing price</span><b><?=money($offer['listing_price'] ?? 0,$offer['currency_code'] ?: 'SGD')?></b></div></div>
                <div class="col-md-4"><div class="mj-offer-kpi"><span><?=((string)$offer['status']==='countered')?'Counter amount':'Offer amount'?></span><b><?=money($showAmount,$offer['currency_code'] ?: 'SGD')?></b></div></div>
                <div class="col-md-4"><div class="mj-offer-kpi"><span>Expires</span><b><?=e(!empty($offer['expires_at']) ? date('d M Y', strtotime($offer['expires_at'])) : '-')?></b></div></div>
              </div>
            </div>
          </div>
          <?php if(!empty($offer['message'])): ?>
            <hr><h5 class="fw-bold">Message</h5><p class="mb-0"><?=nl2br(e($offer['message']))?></p>
          <?php endif; ?>
        </div>

        <div class="mj-card p-4">
          <h4 class="fw-bold mb-3">Offer Timeline</h4>
          <?php if(!$timeline): ?>
            <p class="text-muted mb-0">No timeline yet.</p>
          <?php else: ?>
            <?php foreach($timeline as $t): ?>
              <div class="mj-timeline-item">
                <b><?=e(ucwords(str_replace('_',' ', $t['action'])))?></b>
                <p class="text-muted mb-1"><?=e($t['note'] ?? '')?></p>
                <small><?=e($t['created_at'])?><?=!empty($t['actor_name'])?' • '.e($t['actor_name']):''?></small>
              </div>
            <?php endforeach; ?>
          <?php endif; ?>
        </div>
      </div>

      <div class="col-lg-4">
        <div class="mj-card p-4 mb-4">
          <h4 class="fw-bold">Actions</h4>
          <div class="d-grid gap-2">
            <a class="btn btn-outline-primary" href="<?=e(base_url('listing.php?id='.(int)$offer['listing_id']))?>"><i class="bi bi-box-arrow-up-right me-1"></i>View Listing</a>
            <a class="btn btn-outline-primary" href="<?=e(mj_offer_chat_url($offer))?>"><i class="bi bi-chat-dots me-1"></i>Open Chat</a>
          </div>

          <?php if($isSeller && in_array((string)$offer['status'], ['pending','countered'], true)): ?>
            <hr>
            <form method="post" class="d-grid gap-2">
              <?=csrf_input()?><input type="hidden" name="offer_id" value="<?=e($id)?>">
              <button class="btn btn-success" name="action" value="accept"><i class="bi bi-check-circle me-1"></i>Accept Offer</button>
              <button class="btn btn-outline-danger" name="action" value="reject"><i class="bi bi-x-circle me-1"></i>Reject Offer</button>
            </form>
            <hr>
            <form method="post">
              <?=csrf_input()?><input type="hidden" name="offer_id" value="<?=e($id)?>">
              <label class="form-label fw-bold">Counter offer</label>
              <div class="input-group mb-2"><span class="input-group-text"><?=e($offer['currency_code'] ?: 'SGD')?></span><input class="form-control" name="counter_amount" type="number" step="0.01" min="0.01" required></div>
              <textarea class="form-control mb-2" name="counter_note" rows="3" placeholder="Optional note"></textarea>
              <button class="btn btn-primary w-100" name="action" value="counter">Send Counter Offer</button>
            </form>
          <?php endif; ?>

          <?php if($isBuyer && (string)$offer['status']==='countered'): ?>
            <hr>
            <form method="post" class="d-grid gap-2">
              <?=csrf_input()?><input type="hidden" name="offer_id" value="<?=e($id)?>">
              <button class="btn btn-success" name="action" value="accept_counter"><i class="bi bi-check-circle me-1"></i>Accept Counter Offer</button>
              <button class="btn btn-outline-danger" name="action" value="reject_counter"><i class="bi bi-x-circle me-1"></i>Reject Counter Offer</button>
            </form>
          <?php elseif($isBuyer && in_array((string)$offer['status'], ['pending'], true)): ?>
            <hr>
            <form method="post">
              <?=csrf_input()?><input type="hidden" name="offer_id" value="<?=e($id)?>">
              <button class="btn btn-outline-danger w-100" name="action" value="cancel"><i class="bi bi-x-circle me-1"></i>Cancel Offer</button>
            </form>
          <?php endif; ?>
        </div>

        <div class="alert alert-warning rounded-4">
          <b><i class="bi bi-shield-check me-1"></i>Safety reminder</b><br>
          Confirm item/service details carefully. MJ Marketplace does not collect customer-to-seller payments; use chat/enquiry only.
        </div>
      </div>
    </div>
  </div>
</section>
<?php include __DIR__.'/includes/footer.php'; ?>
