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

$uid = (int)$u['id'];

function mj_offer_handle_action(array $u): void {
    $uid = (int)$u['id'];
    $action = trim((string)($_POST['action'] ?? ''));
    $offerId = (int)($_POST['offer_id'] ?? 0);
    if ($action === '' || $offerId <= 0) { return; }

    $offer = mj_offer_fetch($offerId);
    if (!$offer || !mj_offer_can_view($offer, $uid)) {
        flash('error','Offer not found or access denied.');
        redirect('my-offers.php');
    }

    $isBuyer = $uid === (int)$offer['buyer_id'];
    $isSeller = $uid === (int)$offer['seller_id'];
    $old = (string)($offer['status'] ?? 'pending');
    $redirect = 'offer-view.php?id='.$offerId;

    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,$offerId]);
            mj_offer_timeline_add($offerId,$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'], $redirect, '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,$offerId]);
            mj_offer_timeline_add($offerId,$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'], $redirect, '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,$offerId]);
            mj_offer_timeline_add($offerId,$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'], $redirect, '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, $offerId
            ]);
            mj_offer_timeline_add($offerId,$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'), $redirect, 'high');
            flash('success','Counter offer sent to buyer.');
        } 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,$offerId]);
            mj_offer_timeline_add($offerId,$uid,'accepted_counter','Buyer accepted the counter offer.',$old,'accepted');
            $offer['status']='accepted'; $offer['amount']=$offer['counter_amount']; $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'], $redirect, 'high');
            flash('success','Counter offer accepted. Enquiry record created and seller has been notified. 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,$offerId]);
            mj_offer_timeline_add($offerId,$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'], $redirect, 'normal');
            flash('success','Counter offer rejected.');
        } else {
            flash('warning','This action is not available for this offer.');
        }
    } catch(Throwable $e) {
        flash('error',$e->getMessage());
    }
    redirect($redirect);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') { mj_offer_handle_action($u); }

$tab = strtolower(trim((string)($_GET['tab'] ?? 'all')));
$status = strtolower(trim((string)($_GET['status'] ?? '')));
$qstr = trim((string)($_GET['q'] ?? ''));

$where = ['(o.buyer_id=? OR o.seller_id=?)'];
$params = [$uid,$uid];

if ($tab === 'sent') { $where[] = 'o.buyer_id=?'; $params[] = $uid; }
elseif ($tab === 'received') { $where[] = 'o.seller_id=?'; $params[] = $uid; }

if ($status !== '' && array_key_exists($status, mj_offer_statuses())) { $where[] = 'o.status=?'; $params[] = $status; }
if ($qstr !== '') {
    $where[] = '(l.title LIKE ? OR b.name LIKE ? OR s.name LIKE ? OR co.name LIKE ?)';
    $like = '%'.$qstr.'%';
    array_push($params,$like,$like,$like,$like);
}

$rows = all_rows('SELECT o.*, l.title listing_title, l.price listing_price, l.status listing_status, l.company_id,
    (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,
    b.name buyer_name, s.name seller_name, co.name company_name, co.is_verified company_verified
    FROM mj_offers o
    LEFT JOIN mj_listings l ON l.id=o.listing_id
    LEFT JOIN mj_users b ON b.id=o.buyer_id
    LEFT JOIN mj_users s ON s.id=o.seller_id
    LEFT JOIN mj_companies co ON co.id=l.company_id
    WHERE '.implode(' AND ', $where).'
    ORDER BY COALESCE(o.last_action_at,o.updated_at,o.created_at) DESC, o.id DESC
    LIMIT 200', $params);

$counts = ['sent'=>0,'received'=>0,'pending'=>0,'countered'=>0,'accepted'=>0];
try {
    $r = one('SELECT COUNT(*) c FROM mj_offers WHERE buyer_id=?', [$uid]); $counts['sent']=(int)($r['c'] ?? 0);
    $r = one('SELECT COUNT(*) c FROM mj_offers WHERE seller_id=?', [$uid]); $counts['received']=(int)($r['c'] ?? 0);
    foreach(all_rows('SELECT status, COUNT(*) c FROM mj_offers WHERE buyer_id=? OR seller_id=? GROUP BY status', [$uid,$uid]) as $cr){ $counts[(string)$cr['status']] = (int)$cr['c']; }
} catch(Throwable $e) {}

$pageTitle='My Offers';
include __DIR__.'/includes/header.php';
?>
<div class="container py-5">
  <div class="sidebar-layout">
    <?php include __DIR__.'/includes/account-sidebar.php'; ?>
    <section>
      <div class="mj-page-hero rounded-4 mb-4">
        <div class="container-fluid">
          <span class="mj-badge mb-2"><i class="bi bi-cash-coin"></i> Marketplace Offers</span>
          <h1 class="fw-bold mb-1">My Offers</h1>
          <p class="text-muted mb-0">Track offers you sent, offers received on your listings, counter offers and accepted deals.</p>
        </div>
      </div>

      <?php show_flash(); ?>

      <div class="row g-3 mb-4">
        <div class="col-md-3"><div class="mj-quote-stat"><span>Sent</span><b><?=e($counts['sent'])?></b></div></div>
        <div class="col-md-3"><div class="mj-quote-stat"><span>Received</span><b><?=e($counts['received'])?></b></div></div>
        <div class="col-md-3"><div class="mj-quote-stat"><span>Pending</span><b><?=e($counts['pending'] ?? 0)?></b></div></div>
        <div class="col-md-3"><div class="mj-quote-stat"><span>Accepted</span><b><?=e($counts['accepted'] ?? 0)?></b></div></div>
      </div>

      <div class="mj-card p-3 mb-4">
        <div class="d-flex flex-wrap justify-content-between align-items-center gap-3">
          <div class="mj-chat-tabs">
            <?php foreach(['all'=>'All','sent'=>'Offers I Sent','received'=>'Offers I Received'] as $k=>$v): ?>
              <a class="btn btn-sm <?=$tab===$k?'btn-primary':'btn-outline-primary'?> rounded-pill" href="<?=e(base_url('my-offers.php?tab='.$k.($status!==''?'&status='.$status:'').($qstr!==''?'&q='.rawurlencode($qstr):'')))?>"><?=e($v)?></a>
            <?php endforeach; ?>
          </div>
          <form class="d-flex flex-wrap gap-2" method="get">
            <input type="hidden" name="tab" value="<?=e($tab)?>">
            <input class="form-control rounded-pill" name="q" value="<?=e($qstr)?>" placeholder="Search listing, seller or buyer">
            <select class="form-select rounded-pill" name="status">
              <option value="">All statuses</option>
              <?php foreach(mj_offer_statuses() as $k=>$v): ?><option value="<?=e($k)?>" <?=$status===$k?'selected':''?>><?=e($v)?></option><?php endforeach; ?>
            </select>
            <button class="btn btn-primary rounded-pill"><i class="bi bi-search me-1"></i>Filter</button>
          </form>
        </div>
      </div>

      <?php if(!$rows): ?>
        <div class="mj-card p-5 text-center">
          <div class="mj-icon-box mx-auto mb-3"><i class="bi bi-cash-coin"></i></div>
          <h3 class="fw-bold">No offers found</h3>
          <p class="text-muted">When you make an offer on a listing, or buyers offer on your listings, they will appear here.</p>
          <div class="d-flex flex-wrap justify-content-center gap-2">
            <a class="btn btn-primary rounded-pill" href="<?=e(base_url('browse.php'))?>">Browse Listings</a>
            <a class="btn btn-outline-primary rounded-pill" href="<?=e(base_url('my-listings.php'))?>">View My Listings</a>
          </div>
        </div>
      <?php else: ?>
        <div class="mj-offer-list">
          <?php foreach($rows as $r):
            $isSeller = $uid === (int)$r['seller_id'];
            $img = !empty($r['listing_image']) ? base_url($r['listing_image']) : asset('images/empty-state.svg');
            $displayAmount = ((string)$r['status']==='countered' && !empty($r['counter_amount'])) ? (float)$r['counter_amount'] : (float)$r['amount'];
          ?>
            <div class="mj-card p-3 mb-3 mj-offer-row">
              <div class="row g-3 align-items-center">
                <div class="col-lg-7">
                  <div class="d-flex gap-3">
                    <img src="<?=e($img)?>" class="mj-offer-thumb" alt="<?=e($r['listing_title'] ?: 'Listing')?>">
                    <div class="flex-grow-1">
                      <div class="d-flex flex-wrap gap-2 mb-2">
                        <span class="badge text-bg-<?=e(mj_offer_status_class((string)$r['status']))?> rounded-pill"><?=e(mj_offer_status_label((string)$r['status']))?></span>
                        <span class="mj-badge"><?= $isSeller ? 'Received' : 'Sent' ?></span>
                        <?php if(!empty($r['company_name'])): ?><span class="mj-badge"><i class="bi bi-building"></i><?=e($r['company_name'])?></span><?php endif; ?>
                      </div>
                      <h4 class="fw-bold mb-1"><a class="text-dark text-decoration-none" href="<?=e(base_url('offer-view.php?id='.(int)$r['id']))?>"><?=e($r['listing_title'] ?: 'Listing')?></a></h4>
                      <p class="text-muted small mb-1"><?= $isSeller ? 'Buyer: '.e($r['buyer_name'] ?: 'Buyer') : 'Seller: '.e($r['seller_name'] ?: 'Seller') ?></p>
                      <p class="small mb-0">Listing price: <b><?=money($r['listing_price'] ?? 0,$r['currency_code'] ?: 'SGD')?></b></p>
                    </div>
                  </div>
                </div>
                <div class="col-lg-2">
                  <span class="text-muted small d-block">Offer amount</span>
                  <b class="fs-5"><?=money($displayAmount,$r['currency_code'] ?: 'SGD')?></b>
                  <?php if((string)$r['status']==='countered' && !empty($r['counter_amount'])): ?><small class="d-block text-info fw-bold">Counter offer</small><?php endif; ?>
                </div>
                <div class="col-lg-3 text-lg-end">
                  <div class="small text-muted mb-2">Expires <?=e(!empty($r['expires_at']) ? date('d M Y', strtotime($r['expires_at'])) : '-')?></div>
                  <div class="d-flex flex-wrap justify-content-lg-end gap-2">
                    <a class="btn btn-sm btn-primary" href="<?=e(base_url('offer-view.php?id='.(int)$r['id']))?>">View</a>
                    <a class="btn btn-sm btn-outline-primary" href="<?=e(mj_offer_chat_url($r))?>"><i class="bi bi-chat-dots me-1"></i>Chat</a>
                    <?php if($isSeller && in_array((string)$r['status'],['pending','countered'],true)): ?>
                      <form method="post" class="d-inline"><?=csrf_input()?><input type="hidden" name="offer_id" value="<?=e($r['id'])?>"><button class="btn btn-sm btn-success" name="action" value="accept">Accept</button></form>
                      <form method="post" class="d-inline"><?=csrf_input()?><input type="hidden" name="offer_id" value="<?=e($r['id'])?>"><button class="btn btn-sm btn-outline-danger" name="action" value="reject">Reject</button></form>
                    <?php elseif(!$isSeller && in_array((string)$r['status'],['pending','countered'],true)): ?>
                      <form method="post" class="d-inline"><?=csrf_input()?><input type="hidden" name="offer_id" value="<?=e($r['id'])?>"><button class="btn btn-sm btn-outline-danger" name="action" value="cancel">Cancel</button></form>
                    <?php endif; ?>
                  </div>
                </div>
              </div>
            </div>
          <?php endforeach; ?>
        </div>
      <?php endif; ?>
    </section>
  </div>
</div>
<?php include __DIR__.'/includes/footer.php'; ?>
