<?php
require_once __DIR__.'/includes/functions.php';
$u = require_user();
verify_csrf();
mj_ensure_listing_module_schema(true);
mj263_schema();
if (function_exists('mj_realtime_chat_ensure_schema')) { mj_realtime_chat_ensure_schema(); }
mj_listing_paid_upgrade_ensure_schema();
$upgradeSettings = mj_listing_upgrade_settings();
$canRenewListing = mj_user_feature_enabled('renew_listing', (int)$u['id']);
$canFeatureListing = mj_user_feature_enabled('featured_listing', (int)$u['id']);
$canSponsorListing = mj_user_feature_enabled('sponsored_listing', (int)$u['id']);

$pageTitle = 'My Listings';

if (isset($_POST['action'], $_POST['id'])) {
    $id = (int)$_POST['id'];
    $l = one('SELECT * FROM mj_listings WHERE id=? AND user_id=? LIMIT 1', [$id, $u['id']]);
    if (!$l) { flash('error','Listing not found or access denied.'); redirect('my-listings.php'); }

    $a = (string)$_POST['action'];
    if ($a === 'inactive') {
        q('UPDATE mj_listings SET status="inactive", inactive_at=NOW(), inactive_by=? WHERE id=? AND user_id=?', [$u['id'],$id,$u['id']]);
        mj_listing_log($id,'user_set_inactive',$l,[]);
        flash('success','Listing set inactive and hidden from public.');
    } elseif ($a === 'reactivate') {
        q('UPDATE mj_listings SET status="pending", reactivated_at=NOW() WHERE id=? AND user_id=?', [$id,$u['id']]);
        mj_listing_log($id,'user_reactivate_pending',$l,[]);
        flash('success','Listing sent for admin approval again.');
    } elseif ($a === 'sold') {
        q('UPDATE mj_listings SET status="sold" WHERE id=? AND user_id=?', [$id,$u['id']]);
        mj_listing_log($id,'user_mark_sold',$l,[]);
        flash('success','Listing marked as sold. Public offer button is disabled.');
    } elseif ($a === 'reserved') {
        q('UPDATE mj_listings SET status="reserved" WHERE id=? AND user_id=?', [$id,$u['id']]);
        mj_listing_log($id,'user_mark_reserved',$l,[]);
        flash('success','Listing marked as reserved. Public offer button is disabled.');
    } elseif ($a === 'delete') {
        q('UPDATE mj_listings SET status="deleted", is_deleted=1, deleted_at=NOW(), deleted_by=? WHERE id=? AND user_id=?', [$u['id'],$id,$u['id']]);
        mj_listing_log($id,'user_soft_delete',$l,[]);
        flash('success','Listing deleted from public view.');
    } elseif ($a === 'renew') {
        if (!$canRenewListing) { flash('error','Renew listing request is not enabled for your account. Please contact admin.'); redirect('my-listings.php'); }
        $pending = mj_listing_pending_upgrade($id, 'renew');
        if ($pending) {
            flash('warning','Renewal request is already waiting for admin approval.');
        } else {
            $charge = mj_listing_upgrade_charge('renew');
            $days = (int)$charge['days'];
            $cur = $l['expires_at'] ?? null;
            $new = date('Y-m-d H:i:s', strtotime('+'.$days.' days', max(time(), $cur ? strtotime($cur) : time())));
            $payRequired = (!empty($charge['enabled']) && (float)$charge['amount'] > 0) ? 1 : 0;
            q('INSERT INTO mj_listing_renewal_requests(listing_id,user_id,current_expires_at,requested_days,requested_expires_at,status,payment_required,payment_amount,payment_currency,payment_status,user_note,requested_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,NOW())', [
                $id,$u['id'],$cur,$days,$new,$payRequired?'pending_payment':'pending',$payRequired,(float)$charge['amount'],$charge['currency'],$payRequired?'payment_required':'not_required',trim((string)($_POST['user_note'] ?? ''))
            ]);
            mj_listing_log($id,'user_renew_requested',$l,['requested_days'=>$days,'charge_amount'=>$charge['amount'],'currency'=>$charge['currency']]);
            mj_create_admin_alert([
                'alert_key'=>'listing_renew_'.$id.'_'.date('YmdHi'),
                'alert_type'=>'listing_renewal',
                'module_name'=>'listings',
                'priority'=>'high',
                'title'=>'Listing renewal requested',
                'message'=>'User requested renewal for: '.($l['title'] ?? 'Listing').' | Charge: '.$charge['currency'].' '.number_format((float)$charge['amount'],2),
                'action_url'=>'listing-renewals.php',
                'action_label'=>'Review',
                'related_type'=>'listing',
                'related_id'=>$id
            ]);
            mj263_notify(null,1,'listing_renewal','Listing renewal requested','User requested renewal for: '.($l['title'] ?? 'Listing'),'admin/listing-renewals.php','high');
            flash('success','Renewal interest sent to admin. Admin will review and confirm any charges before approval.');
        }
    } elseif (in_array($a, ['feature_request','sponsor_request'], true)) {
        $type = $a === 'feature_request' ? 'feature' : 'sponsor';
        if ($type === 'feature' && !$canFeatureListing) { flash('error','Featured listing request is not enabled for your account. Please contact admin.'); redirect('my-listings.php'); }
        if ($type === 'sponsor' && !$canSponsorListing) { flash('error','Sponsored listing request is not enabled for your account. Please contact admin.'); redirect('my-listings.php'); }
        $pending = mj_listing_pending_upgrade($id, $type);
        if ($pending) {
            flash('warning', mj_listing_upgrade_type_label($type).' request is already waiting for admin approval.');
        } else {
            $charge = mj_listing_upgrade_charge($type);
            $days = (int)$charge['days'];
            $payRequired = (!empty($charge['enabled']) && (float)$charge['amount'] > 0) ? 1 : 0;
            q('INSERT INTO mj_listing_upgrade_requests(listing_id,user_id,upgrade_type,requested_days,charge_amount,currency_code,payment_required,payment_status,status,user_note,requested_at) VALUES(?,?,?,?,?,?,?,?,?,?,NOW())', [
                $id,$u['id'],$type,$days,(float)$charge['amount'],$charge['currency'],$payRequired,$payRequired?'payment_required':'not_required',$payRequired?'pending_payment':'pending',trim((string)($_POST['user_note'] ?? ''))
            ]);
            mj_listing_log($id,'user_'.$type.'_requested',$l,['requested_days'=>$days,'charge_amount'=>$charge['amount'],'currency'=>$charge['currency']]);
            mj_create_admin_alert([
                'alert_key'=>'listing_'.$type.'_'.$id.'_'.date('YmdHi'),
                'alert_type'=>'listing_'.$type,
                'module_name'=>'listings',
                'priority'=>'high',
                'title'=>mj_listing_upgrade_type_label($type).' requested',
                'message'=>'User requested '.mj_listing_upgrade_type_label($type).' for: '.($l['title'] ?? 'Listing').' | Charge: '.$charge['currency'].' '.number_format((float)$charge['amount'],2),
                'action_url'=>'listing-upgrade-requests.php',
                'action_label'=>'Review',
                'related_type'=>'listing',
                'related_id'=>$id
            ]);
            mj263_notify(null,1,'listing_upgrade','Listing upgrade requested','User requested '.mj_listing_upgrade_type_label($type).' for: '.($l['title'] ?? 'Listing'),'admin/listing-upgrade-requests.php','high');
            flash('success', mj_listing_upgrade_type_label($type).' interest sent to admin. Admin will review and confirm any charges before activation.');
        }
    }
    redirect('my-listings.php');
}

$tab = $_GET['status'] ?? '';
$where = 'l.user_id=?';
$params = [(int)$u['id']];
if ($tab !== '') { $where .= ' AND l.status=?'; $params[] = $tab; }

if (table_exists('mj_chats') && table_exists('mj_chat_messages')) {
    $sql = 'SELECT l.*,
        (SELECT COUNT(*) FROM mj_chats ch WHERE ch.listing_id=l.id AND (ch.buyer_id=? OR ch.seller_id=?)) chat_count,
        (SELECT COUNT(*) FROM mj_chat_messages m INNER JOIN mj_chats ch ON ch.id=m.chat_id WHERE ch.listing_id=l.id AND m.sender_id<>? AND IFNULL(m.is_read,0)=0 AND IFNULL(m.is_deleted,0)=0 AND (ch.buyer_id=? OR ch.seller_id=?)) unread_chat_count
        FROM mj_listings l WHERE '.$where.' ORDER BY l.id DESC';
    $rows = all_rows($sql, array_merge([(int)$u['id'],(int)$u['id'],(int)$u['id'],(int)$u['id'],(int)$u['id']], $params));
} else {
    $rows = all_rows('SELECT l.*, 0 chat_count, 0 unread_chat_count FROM mj_listings l WHERE '.$where.' ORDER BY l.id DESC', $params);
}

include __DIR__.'/includes/header.php';
?>
<section class="mj-page-hero">
  <div class="container">
    <h1 class="fw-bold">My Listings</h1>
    <p class="text-muted mb-0">Edit, renew request, inactive, sold/reserved, QR share or delete your own listings.</p>
  </div>
</section>

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

    <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-stars me-1"></i>Promote or renew your listing</h5>
          <p class="text-muted mb-0 small">Interested in renewing, featuring or sponsoring a listing? Submit a request here. Admin will review and confirm the charge before activation.</p>
        </div>
        <div class="text-lg-end">
          <div class="small text-muted mb-2">
            <b><?=e($upgradeSettings['currency'])?></b>
            Renew <?=e(number_format((float)$upgradeSettings['renew_amount'],2))?> ·
            Feature <?=e(number_format((float)$upgradeSettings['feature_amount'],2))?> ·
            Sponsor <?=e(number_format((float)$upgradeSettings['sponsor_amount'],2))?>
          </div>
          <?php if(mj_user_feature_enabled('billing_payments', (int)$u['id'])): ?><a class="btn btn-sm btn-outline-primary rounded-pill" href="<?=e(base_url('my-upgrade-payments.php'))?>"><i class="bi bi-credit-card me-1"></i>Upgrade Payments</a><?php endif; ?>
        </div>
      </div>
    </div>

    <div class="d-flex flex-wrap gap-2 mb-3">
      <?php foreach([''=>'All','active'=>'Active','pending'=>'Pending','inactive'=>'Inactive','rejected'=>'Rejected','expired'=>'Expired','sold'=>'Sold','reserved'=>'Reserved','deleted'=>'Deleted'] as $k=>$v): ?>
        <a class="btn btn-sm <?=$tab===$k?'btn-primary':'btn-outline-primary'?>" href="?status=<?=e($k)?>"><?=e($v)?></a>
      <?php endforeach; ?>
      <a class="btn btn-sm btn-success ms-auto" href="post-listing.php"><i class="bi bi-plus-circle"></i> Post Listing</a>
    </div>

    <?php if(!$rows): ?>
      <div class="mj-card p-5 text-center">
        <h3>No listings yet</h3>
        <p class="text-muted">Post your first listing and start receiving chats/offers.</p>
      </div>
    <?php else: ?>
      <div class="row g-4">
        <?php foreach($rows as $r):
          $status = strtolower($r['status'] ?? 'active');
          $pendingEdit = mj263_pending_revision((int)$r['id']);
          $pendingRenew = mj_listing_pending_upgrade((int)$r['id'], 'renew');
          $pendingFeature = mj_listing_pending_upgrade((int)$r['id'], 'feature');
          $pendingSponsor = mj_listing_pending_upgrade((int)$r['id'], 'sponsor');
          $quality = mj263_quality_details($r);
          $chatCount = (int)($r['chat_count'] ?? 0);
          $unreadChat = (int)($r['unread_chat_count'] ?? 0);
          $im = '';
          try {
              $img = one('SELECT image_path FROM mj_listing_images WHERE listing_id=? ORDER BY sort_order,id LIMIT 1', [(int)$r['id']]);
              $im = $img['image_path'] ?? '';
          } catch(Throwable $e) {}
          $imgUrl = $im ? base_url($im) : asset('images/empty-state.svg');
        ?>
          <div class="col-lg-6">
            <div class="mj-card p-3 h-100">
              <div class="d-flex gap-3">
                <div style="width:110px;height:90px;border-radius:16px;background:#eef2ff;overflow:hidden">
                  <img src="<?=e($imgUrl)?>" style="width:100%;height:100%;object-fit:cover" data-gallery-src="<?=e($imgUrl)?>" alt="<?=e($r['title'] ?? 'Listing')?>">
                </div>
                <div class="flex-grow-1">
                  <h5 class="fw-bold mb-1"><?=e($r['title'])?></h5>
                  <div class="small text-muted mb-2">
                    <?=money($r['price'],$r['currency_code']??'SGD')?> •
                    👁 <?=e($r['views']??0)?> •
                    🔥 <?=e($r['engagement_count']??0)?> •
                    💰 <?=e($r['offer_count']??0)?>
                    <?php if($chatCount>0): ?> • 💬 <?=e($chatCount)?> chat<?=$chatCount===1?'':'s'?><?php endif; ?>
                  </div>

                  <?php if($unreadChat>0): ?>
                    <div class="mj-listing-unread-chat mt-2 mb-2">
                      <i class="bi bi-chat-dots-fill me-1"></i><?=e($unreadChat)?> unread message<?=$unreadChat===1?'':'s'?> for this listing
                    </div>
                  <?php endif; ?>

                  <span class="mj-badge <?=in_array($status,['active','approved','published'],true)?'good':($status==='sold'?'dark':'warn')?>"><?=e($status?:'active')?></span>
                  <?php if($pendingEdit): ?><span class="mj-badge warn">Pending Edit Review</span><?php endif; ?>
                  <?php if($pendingRenew): ?><span class="mj-badge warn">Renew Pending</span><?php endif; ?>
                  <?php if($pendingFeature): ?><span class="mj-badge warn">Feature Pending</span><?php endif; ?>
                  <?php if($pendingSponsor): ?><span class="mj-badge warn">Sponsor Pending</span><?php endif; ?>
                  <?php if(!empty($r['expires_at'])): ?><span class="mj-badge">Expires <?=e(date('d M Y',strtotime($r['expires_at'])))?></span><?php endif; ?>

                  <div class="small mt-2">Quality <?=e($quality['score'])?>%</div>
                  <div class="progress" style="height:6px"><div class="progress-bar" style="width:<?=e($quality['score'])?>%"></div></div>
                </div>
              </div>

              <hr>

              <form method="post" class="d-flex flex-wrap gap-2">
                <?=csrf_input()?>
                <input type="hidden" name="id" value="<?=e($r['id'])?>">
                <a class="btn btn-sm btn-primary" href="edit-listing.php?id=<?=e($r['id'])?>">Edit</a>
                <a class="btn btn-sm btn-outline-info" target="_blank" href="listing.php?id=<?=e($r['id'])?>">Preview</a>
                <?php if($chatCount>0): ?>
                  <a class="btn btn-sm <?=$unreadChat>0?'btn-warning':'btn-outline-primary'?>" href="messages.php?listing_id=<?=e($r['id'])?>">
                    <i class="bi bi-chat-dots me-1"></i>Messages<?=$unreadChat>0?' ('.e($unreadChat).')':''?>
                  </a>
                <?php endif; ?>
                <a class="btn btn-sm btn-outline-dark" target="_blank" href="listing-qr-poster.php?id=<?=e($r['id'])?>">QR</a>
                <?php if($status==='inactive'): ?>
                  <button class="btn btn-sm btn-success" name="action" value="reactivate">Reactivate</button>
                <?php else: ?>
                  <button class="btn btn-sm btn-warning" name="action" value="inactive">Set Inactive</button>
                <?php endif; ?>
                <button class="btn btn-sm btn-secondary" name="action" value="reserved">Reserved</button>
                <button class="btn btn-sm btn-info" name="action" value="sold">Sold</button>
                <?php if($canRenewListing): ?><button class="btn btn-sm btn-outline-primary" name="action" value="renew" <?=$pendingRenew?'disabled':''?>><i class="bi bi-arrow-clockwise me-1"></i>Renew <?=e($upgradeSettings['currency'])?> <?=e(number_format((float)$upgradeSettings['renew_amount'],2))?></button><?php endif; ?>
                <?php if($canFeatureListing): ?><button class="btn btn-sm btn-outline-warning" name="action" value="feature_request" <?=$pendingFeature?'disabled':''?>><i class="bi bi-star me-1"></i>Feature <?=e($upgradeSettings['currency'])?> <?=e(number_format((float)$upgradeSettings['feature_amount'],2))?></button><?php endif; ?>
                <?php if($canSponsorListing): ?><button class="btn btn-sm btn-outline-success" name="action" value="sponsor_request" <?=$pendingSponsor?'disabled':''?>><i class="bi bi-megaphone me-1"></i>Sponsor <?=e($upgradeSettings['currency'])?> <?=e(number_format((float)$upgradeSettings['sponsor_amount'],2))?></button><?php endif; ?>
                <button class="btn btn-sm btn-danger" name="action" value="delete" onclick="return confirm('Delete this listing from public view?')">Delete</button>
              </form>
            </div>
          </div>
        <?php endforeach; ?>
      </div>
    <?php endif; ?>
  </div>
</section>
<?php include __DIR__.'/includes/footer.php'; ?>
