<?php
require_once __DIR__.'/../includes/functions.php';
$admin = require_admin();
$adminTitle = 'Admin Global Search';
$adminSubtitle = 'Search users, listings, companies, payment proofs, invoices and support tickets from one place.';
$qText = trim((string)($_GET['q'] ?? ''));
$like = '%'.$qText.'%';
$results = [];
if ($qText !== '') {
    try {
        if (table_exists('mj_users')) {
            $cols = [];
            foreach(['name','email','mobile','phone'] as $c){ if(mj_has_col('mj_users',$c)) $cols[] = "`{$c}` LIKE ?"; }
            if($cols){ foreach(all_rows('SELECT * FROM mj_users WHERE '.implode(' OR ',$cols).' ORDER BY id DESC LIMIT 20', array_fill(0,count($cols),$like)) as $r){ $results[]=['type'=>'User','title'=>($r['name']??'User').' #'.($r['id']??''),'desc'=>($r['email']??'').' '.($r['mobile']??''),'url'=>'user-edit.php?id='.(int)($r['id']??0),'icon'=>'fas fa-user']; } }
        }
    } catch(Throwable $e) {}
    try {
        if (table_exists('mj_listings')) {
            $cols=[]; foreach(['title','description','slug'] as $c){ if(mj_has_col('mj_listings',$c)) $cols[]="`{$c}` LIKE ?"; }
            if($cols){ foreach(all_rows('SELECT * FROM mj_listings WHERE '.implode(' OR ',$cols).' ORDER BY id DESC LIMIT 20', array_fill(0,count($cols),$like)) as $r){ $results[]=['type'=>'Listing','title'=>$r['title']??('Listing #'.($r['id']??'')),'desc'=>'Status: '.($r['status']??''),'url'=>'listing-edit.php?id='.(int)($r['id']??0),'icon'=>'fas fa-tags']; } }
        }
    } catch(Throwable $e) {}
    try {
        if (table_exists('mj_companies')) {
            $cols=[]; foreach(['name','email','phone','website','slug'] as $c){ if(mj_has_col('mj_companies',$c)) $cols[]="`{$c}` LIKE ?"; }
            if($cols){ foreach(all_rows('SELECT * FROM mj_companies WHERE '.implode(' OR ',$cols).' ORDER BY id DESC LIMIT 20', array_fill(0,count($cols),$like)) as $r){ $results[]=['type'=>'Company','title'=>$r['name']??('Company #'.($r['id']??'')),'desc'=>($r['email']??'').' '.($r['phone']??''),'url'=>'company-edit.php?id='.(int)($r['id']??0),'icon'=>'fas fa-building']; } }
        }
    } catch(Throwable $e) {}
    foreach(['mj_upgrade_payment_proofs'=>'Upgrade Proof','mj_payment_proofs'=>'Payment Proof'] as $table=>$label){
        try {
            if(table_exists($table)){
                $cols=[]; foreach(['reference_no','payment_method','note','original_name'] as $c){ if(mj_has_col($table,$c)) $cols[]="`{$c}` LIKE ?"; }
                if($cols){ foreach(all_rows('SELECT * FROM `'.preg_replace('/[^a-zA-Z0-9_]/','',$table).'` WHERE '.implode(' OR ',$cols).' ORDER BY id DESC LIMIT 10', array_fill(0,count($cols),$like)) as $r){ $results[]=['type'=>$label,'title'=>$label.' #'.($r['id']??''),'desc'=>'Amount: '.money($r['amount']??0,$r['currency_code']??'SGD').' Status: '.($r['status']??''),'url'=>'payment-center.php?tab=review','icon'=>'fas fa-receipt']; } }
            }
        } catch(Throwable $e) {}
    }
    try {
        if (table_exists('mj_support_tickets')) {
            $cols=[]; foreach(['subject','message','category'] as $c){ if(mj_has_col('mj_support_tickets',$c)) $cols[]="`{$c}` LIKE ?"; }
            if($cols){ foreach(all_rows('SELECT * FROM mj_support_tickets WHERE '.implode(' OR ',$cols).' ORDER BY id DESC LIMIT 20', array_fill(0,count($cols),$like)) as $r){ $results[]=['type'=>'Support','title'=>$r['subject']??('Ticket #'.($r['id']??'')),'desc'=>'Status: '.($r['status']??''),'url'=>'support.php','icon'=>'fas fa-headset']; } }
        }
    } catch(Throwable $e) {}
}
include __DIR__.'/_header.php';
?>

<div class="card card-primary card-outline">
  <div class="card-header"><h3 class="card-title"><i class="fas fa-search mr-2"></i>Global Admin Search</h3></div>
  <div class="card-body">
    <form method="get" class="mb-4">
      <div class="input-group input-group-lg">
        <input type="search" name="q" class="form-control" value="<?= e($qText) ?>" placeholder="Search name, email, listing title, company, payment reference...">
        <div class="input-group-append"><button class="btn btn-primary"><i class="fas fa-search mr-1"></i>Search</button></div>
      </div>
    </form>
    <?php if($qText===''): ?>
      <div class="text-center text-muted p-5"><i class="fas fa-search fa-3x mb-3"></i><h5>Search across admin records</h5><p>Enter keyword above to search users, listings, companies, payment proofs and tickets.</p></div>
    <?php elseif(!$results): ?>
      <div class="alert alert-warning">No result found for <b><?= e($qText) ?></b>.</div>
    <?php else: ?>
      <div class="list-group mj-search-results">
        <?php foreach($results as $r): ?>
          <a class="list-group-item list-group-item-action" href="<?= e($r['url']) ?>"><div class="d-flex align-items-center"><span class="mj-search-icon"><i class="<?= e($r['icon']) ?>"></i></span><div><b><?= e($r['title']) ?></b><br><small class="text-muted"><?= e($r['type']) ?> · <?= e(mb_strimwidth($r['desc'],0,160,'...')) ?></small></div></div></a>
        <?php endforeach; ?>
      </div>
    <?php endif; ?>
  </div>
</div>

<?php include __DIR__.'/_footer.php'; ?>
