<?php
require_once __DIR__.'/../includes/functions.php';
$admin = require_admin();
verify_csrf();
mj_user_limits_ensure_schema();
mj_upgrade_payment_ensure_schema();
$adminTitle = 'Extra Slot Requests';

if (isset($_POST['action'], $_POST['request_id'])) {
    $rid = (int)$_POST['request_id'];
    $req = one('SELECT * FROM mj_user_limit_upgrade_requests WHERE id=? LIMIT 1', [$rid]);
    if (!$req) { flash('error','Request not found.'); redirect('limit-upgrade-requests.php'); }
    $action = (string)$_POST['action'];
    $note = trim((string)($_POST['admin_note'] ?? ''));
    if ($action === 'approve') {
        $limits = mj_user_limits_get((int)$req['user_id']);
        $current = $req['request_type'] === 'listing' ? (int)$limits['max_listings'] : (int)$limits['max_companies'];
        $newLimit = $current <= 0 ? 0 : $current + (int)$req['requested_slots'];
        if ($req['request_type'] === 'listing') {
            q('INSERT INTO mj_user_limits(user_id,max_listings,max_companies,note,updated_by,updated_at) VALUES(?,?,?,?,?,NOW()) ON DUPLICATE KEY UPDATE max_listings=VALUES(max_listings), note=VALUES(note), updated_by=VALUES(updated_by), updated_at=NOW()', [
                (int)$req['user_id'], $newLimit, null, $note, (int)$admin['id']
            ]);
        } else {
            q('INSERT INTO mj_user_limits(user_id,max_listings,max_companies,note,updated_by,updated_at) VALUES(?,?,?,?,?,NOW()) ON DUPLICATE KEY UPDATE max_companies=VALUES(max_companies), note=VALUES(note), updated_by=VALUES(updated_by), updated_at=NOW()', [
                (int)$req['user_id'], null, $newLimit, $note, (int)$admin['id']
            ]);
        }
        q('UPDATE mj_user_limit_upgrade_requests SET status="approved", requested_limit=?, admin_note=?, reviewed_by=?, reviewed_at=NOW() WHERE id=?', [$newLimit,$note,(int)$admin['id'],$rid]);
        mj263_notify((int)$req['user_id'], null, 'limit_upgrade_approved', 'Extra slots approved', 'Your extra '.($req['request_type']).' slots were approved.', ($req['request_type']==='listing'?'post-listing.php':'add-company.php'), 'normal', true);
        flash('success','Extra slot request approved.');
    } elseif ($action === 'reject') {
        $reason = trim((string)($_POST['reject_reason'] ?? 'Rejected by admin'));
        q('UPDATE mj_user_limit_upgrade_requests SET status="rejected", reject_reason=?, admin_note=?, reviewed_by=?, reviewed_at=NOW() WHERE id=?', [$reason,$note,(int)$admin['id'],$rid]);
        mj263_notify((int)$req['user_id'], null, 'limit_upgrade_rejected', 'Extra slots rejected', 'Reason: '.$reason, 'my-payment-center.php?tab=review', 'normal', true);
        flash('success','Extra slot request rejected.');
    }
    redirect('limit-upgrade-requests.php');
}

$status = trim((string)($_GET['status'] ?? 'pending_payment'));
$where = [];
$params = [];
if ($status !== '') { $where[]='r.status=?'; $params[]=$status; }
$rows = all_rows('SELECT r.*, u.name user_name, u.email
    FROM mj_user_limit_upgrade_requests r
    LEFT JOIN mj_users u ON u.id=r.user_id
    '.($where?'WHERE '.implode(' AND ', $where):'').'
    ORDER BY r.id DESC LIMIT 500', $params);

include __DIR__.'/_header.php';
?>
<div class="card card-primary card-outline">
  <div class="card-header">
    <h3 class="card-title"><i class="fas fa-plus-circle mr-2"></i>Extra Slot Requests</h3>
    <div class="card-tools"><a href="user-limits.php" class="btn btn-sm btn-outline-primary">User Limits</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_payment'=>'Pending Payment','payment_uploaded'=>'Payment Uploaded','approved'=>'Approved','rejected'=>'Rejected','pending'=>'Pending',''=>'All'] as $k=>$v): ?>
          <option value="<?=e($k)?>" <?=$status===$k?'selected':''?>><?=e($v)?></option>
        <?php endforeach; ?>
      </select>
      <button class="btn btn-primary">Filter</button>
    </form>

    <div class="table-responsive">
      <table class="table table-hover">
        <thead><tr><th>ID</th><th>User</th><th>Request</th><th>Charge</th><th>Payment</th><th>Status</th><th>Action</th></tr></thead>
        <tbody>
          <?php foreach($rows as $r): ?>
            <tr>
              <td>#<?=e($r['id'])?></td>
              <td><b><?=e($r['user_name'])?></b><br><small><?=e($r['email'])?></small></td>
              <td><?=e(ucfirst($r['request_type']))?> slots<br><small>Extra: <?=e($r['requested_slots'])?> | Current: <?=e($r['current_limit'] ?: 'Unlimited')?> | Requested: <?=e($r['requested_limit'] ?: '-')?></small></td>
              <td><b><?=e($r['currency_code'])?> <?=e(number_format((float)$r['charge_amount'],2))?></b></td>
              <td><?=e($r['payment_status'] ?: '-')?></td>
              <td><span class="badge badge-<?=e($r['status']==='approved'?'success':($r['status']==='rejected'?'danger':'warning'))?>"><?=e($r['status'])?></span></td>
              <td style="min-width:340px">
                <?php if(in_array($r['status'],['pending','pending_payment','payment_uploaded'],true)): ?>
                  <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" 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"><?=e($r['admin_note'] ?: $r['reject_reason'])?><br><?=e($r['reviewed_at'])?></small>
                <?php endif; ?>
              </td>
            </tr>
          <?php endforeach; ?>
          <?php if(!$rows): ?><tr><td colspan="7" class="text-center text-muted py-4">No requests found.</td></tr><?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>
<?php include __DIR__.'/_footer.php'; ?>
