<?php
require_once __DIR__.'/../includes/functions.php';
$admin = require_admin();
verify_csrf();
mj_listing_paid_upgrade_ensure_schema();
$adminTitle = 'Listing Upgrade Requests';

if (isset($_POST['action'], $_POST['request_id'])) {
    $rid = (int)$_POST['request_id'];
    $req = one('SELECT * FROM mj_listing_upgrade_requests WHERE id=? LIMIT 1', [$rid]);
    if (!$req) { flash('error','Request not found.'); redirect('listing-upgrade-requests.php'); }
    $listing = one('SELECT * FROM mj_listings WHERE id=? LIMIT 1', [(int)$req['listing_id']]);
    if (!$listing) { flash('error','Listing not found.'); redirect('listing-upgrade-requests.php'); }

    $action = (string)$_POST['action'];
    $type = (string)$req['upgrade_type'];
    $days = max(1, (int)($_POST['days'] ?? $req['requested_days'] ?? 30));
    $customUntil = trim((string)($_POST['custom_until'] ?? ''));
    $until = $customUntil ? date('Y-m-d H:i:s', strtotime($customUntil)) : date('Y-m-d H:i:s', strtotime('+'.$days.' days'));
    $adminNote = trim((string)($_POST['admin_note'] ?? ''));

    if ($action === 'approve') {
        if ($type === 'feature') {
            q('UPDATE mj_listings SET is_featured=1, featured_until=?, featured_priority=50, updated_at=NOW() WHERE id=?', [$until,(int)$req['listing_id']]);
        } elseif ($type === 'sponsor') {
            q('UPDATE mj_listings SET is_sponsored=1, sponsored_until=?, sponsored_priority=100, updated_at=NOW() WHERE id=?', [$until,(int)$req['listing_id']]);
        }
        q('UPDATE mj_listing_upgrade_requests SET status="approved", reviewed_by=?, admin_note=?, reviewed_at=NOW(), approved_until=? WHERE id=?', [(int)$admin['id'],$adminNote,$until,$rid]);
        mj_listing_log((int)$req['listing_id'], $type.'_request_approved', $listing ?: [], ['approved_until'=>$until,'charge_amount'=>$req['charge_amount'],'currency'=>$req['currency_code']]);
        mj263_notify((int)$req['user_id'], null, 'listing_upgrade_approved', mj_listing_upgrade_type_label($type).' approved', 'Your listing upgrade is active until '.$until, 'my-listings.php', 'normal', true);
        flash('success', mj_listing_upgrade_type_label($type).' approved.');
    } elseif ($action === 'reject') {
        $reason = trim((string)($_POST['reject_reason'] ?? 'Rejected by admin'));
        q('UPDATE mj_listing_upgrade_requests SET status="rejected", reviewed_by=?, reject_reason=?, admin_note=?, reviewed_at=NOW() WHERE id=?', [(int)$admin['id'],$reason,$adminNote,$rid]);
        mj_listing_log((int)$req['listing_id'], $type.'_request_rejected', $listing ?: [], ['reason'=>$reason]);
        mj263_notify((int)$req['user_id'], null, 'listing_upgrade_rejected', mj_listing_upgrade_type_label($type).' rejected', 'Reason: '.$reason, 'my-listings.php', 'normal', true);
        flash('success', mj_listing_upgrade_type_label($type).' rejected.');
    }
    redirect('listing-upgrade-requests.php');
}

$status = trim((string)($_GET['status'] ?? 'pending'));
$type = trim((string)($_GET['type'] ?? ''));
$where = ['1=1'];
$params = [];
if ($status !== '') { $where[]='r.status=?'; $params[]=$status; }
if (in_array($type, ['feature','sponsor'], true)) { $where[]='r.upgrade_type=?'; $params[]=$type; }

$rows = all_rows('SELECT r.*, l.title, l.is_featured, l.featured_until, l.is_sponsored, l.sponsored_until, u.name user_name, u.email
    FROM mj_listing_upgrade_requests r
    LEFT JOIN mj_listings l ON l.id=r.listing_id
    LEFT JOIN mj_users u ON u.id=r.user_id
    WHERE '.implode(' AND ', $where).'
    ORDER BY r.id DESC LIMIT 400', $params);

include __DIR__.'/_header.php';
?>
<div class="card card-primary card-outline">
  <div class="card-header">
    <h3 class="card-title"><i class="fas fa-star mr-2"></i>Listing Upgrade Requests</h3>
    <div class="card-tools">
      <a href="listing-upgrade-settings.php" class="btn btn-sm btn-outline-primary">Charge Settings</a><a href="payment-center.php?tab=review" class="btn btn-sm btn-outline-success ml-1">Payment Proofs</a>
      <a href="listing-renewals.php" class="btn btn-sm btn-outline-secondary">Renewal Requests</a>
    </div>
  </div>
  <div class="card-body">
    <?php show_flash(); ?>
    <form class="form-inline mb-3">
      <select name="status" class="form-control mr-2">
        <?php foreach(['pending'=>'Pending','approved'=>'Approved','rejected'=>'Rejected','pending_payment'=>'Pending Payment','payment_uploaded'=>'Payment Uploaded','cancelled'=>'Cancelled',''=>'All Status'] as $k=>$v): ?>
          <option value="<?=e($k)?>" <?=$status===$k?'selected':''?>><?=e($v)?></option>
        <?php endforeach; ?>
      </select>
      <select name="type" class="form-control mr-2">
        <option value="">All Types</option>
        <option value="feature" <?=$type==='feature'?'selected':''?>>Feature</option>
        <option value="sponsor" <?=$type==='sponsor'?'selected':''?>>Sponsor</option>
      </select>
      <button class="btn btn-primary">Filter</button>
    </form>

    <div class="table-responsive">
      <table class="table table-hover">
        <thead>
          <tr>
            <th>ID</th><th>Type</th><th>Listing</th><th>User</th><th>Charge</th><th>Days</th><th>Status</th><th>Action</th>
          </tr>
        </thead>
        <tbody>
          <?php if(!$rows): ?>
            <tr><td colspan="8" class="text-center text-muted py-4">No upgrade requests found.</td></tr>
          <?php endif; ?>
          <?php foreach($rows as $r): ?>
            <tr>
              <td>#<?=e($r['id'])?></td>
              <td><span class="badge badge-info"><?=e(mj_listing_upgrade_type_label($r['upgrade_type']))?></span></td>
              <td>
                <b>#<?=e($r['listing_id'])?> <?=e($r['title'])?></b><br>
                <small class="text-muted">
                  Featured until: <?=e($r['featured_until'] ?: '-')?> · Sponsored until: <?=e($r['sponsored_until'] ?: '-')?>
                </small>
              </td>
              <td><?=e(($r['user_name'] ?? '').' '.$r['email'])?></td>
              <td>
                <b><?=e($r['currency_code'])?> <?=e(number_format((float)$r['charge_amount'],2))?></b><br>
                <small><?=!empty($r['payment_required'])?'Payment required':'No charge'?> · <?=e($r['payment_status'] ?: '-')?></small>
              </td>
              <td><?=e($r['requested_days'])?></td>
              <td><span class="badge badge-<?=e(mj_listing_upgrade_status_badge((string)$r['status']))?>"><?=e($r['status'])?></span></td>
              <td style="min-width:360px">
                <?php if($r['status']==='pending'): ?>
                  <form method="post" class="d-flex flex-wrap gap-1">
                    <?=csrf_input()?>
                    <input type="hidden" name="request_id" value="<?=e($r['id'])?>">
                    <input class="form-control form-control-sm" style="width:72px" name="days" value="<?=e($r['requested_days'] ?: 30)?>">
                    <input class="form-control form-control-sm" type="datetime-local" name="custom_until">
                    <input class="form-control form-control-sm" name="admin_note" placeholder="Admin note">
                    <button class="btn btn-sm btn-success" name="action" value="approve">Approve</button>
                    <button class="btn btn-sm btn-danger" name="action" value="reject">Reject</button>
                    <input class="form-control form-control-sm w-100 mt-1" name="reject_reason" placeholder="Reject reason">
                  </form>
                <?php else: ?>
                  <small class="text-muted">Reviewed: <?=e($r['reviewed_at'] ?: '-')?><br><?=e($r['admin_note'] ?: $r['reject_reason'])?></small>
                <?php endif; ?>
              </td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>
<?php include __DIR__.'/_footer.php'; ?>
