<?php
require_once __DIR__.'/../includes/functions.php';
$admin = require_admin();
$adminTitle = 'User Activity';

$id = (int)($_GET['id'] ?? 0);
$user = $id > 0 ? one('SELECT u.*, c.name country, c.flag_emoji FROM mj_users u LEFT JOIN mj_countries c ON c.id=u.country_id WHERE u.id=? LIMIT 1', [$id]) : null;
if (!$user || !admin_can_manage_user($admin, $user)) { flash('error', 'User not found or access denied.'); redirect('users.php'); }

if (!function_exists('mj_admin_v287_rows')) {
function mj_admin_v287_rows(string $sql, array $params = []): array { try { return all_rows($sql, $params); } catch (Throwable $e) { return []; } }
}
if (!function_exists('mj_admin_v287_count')) {
function mj_admin_v287_count(string $table, string $where, array $params = []): int {
    if (!table_exists($table)) { return 0; }
    try { return safe_count('SELECT COUNT(*) c FROM `'.$table.'` WHERE '.$where, $params); } catch (Throwable $e) { return 0; }
}
}
if (!function_exists('mj_admin_v287_amount')) {
function mj_admin_v287_amount(array $row, string $currency = 'SGD'): string {
    $amount = $row['total_amount'] ?? $row['amount'] ?? $row['charge_amount'] ?? 0;
    $cur = $row['currency_code'] ?? $row['payment_currency'] ?? $row['currency'] ?? $currency;
    return e((string)$cur).' '.number_format((float)$amount, 2);
}
}
if (!function_exists('mj_admin_v287_date')) {
function mj_admin_v287_date(array $row): string {
    foreach (['created_at','updated_at','requested_at','submitted_at','uploaded_at','reviewed_at','paid_at','last_message_at','start_at'] as $k) {
        if (!empty($row[$k])) { return (string)$row[$k]; }
    }
    return '';
}
}
if (!function_exists('mj_admin_v287_status')) {
function mj_admin_v287_status($status): string {
    $s = strtolower(trim((string)$status));
    if ($s === '') { return '<span class="badge badge-secondary">-</span>'; }
    $good = ['active','approved','verified','paid','completed','accepted','resolved','read','sent','success'];
    $bad = ['rejected','cancelled','failed','suspended','deleted','dismissed','expired','refunded'];
    $warn = ['pending','submitted','uploaded','pending_review','pending_payment','reviewing','open','draft','unpaid','overdue'];
    $cls = in_array($s, $good, true) ? 'success' : (in_array($s, $bad, true) ? 'danger' : (in_array($s, $warn, true) ? 'warning' : 'secondary'));
    return '<span class="badge badge-'.$cls.'">'.e($status).'</span>';
}
}
if (!function_exists('mj_admin_v287_file_url')) {
function mj_admin_v287_file_url($path): string {
    $path = trim((string)$path);
    if ($path === '') { return ''; }
    if (preg_match('#^https?://#i', $path) || str_starts_with($path, '/')) { return $path; }
    return base_url($path);
}
}
if (!function_exists('mj_admin_v287_add_event')) {
function mj_admin_v287_add_event(array &$events, string $date, string $type, string $title, string $description = '', string $status = '', string $url = '', string $icon = 'fa-circle') : void {
    if ($date === '') { $date = date('Y-m-d H:i:s'); }
    $events[] = ['date'=>$date, 'type'=>$type, 'title'=>$title, 'description'=>$description, 'status'=>$status, 'url'=>$url, 'icon'=>$icon];
}
}

$currency = (string)($user['preferred_currency'] ?? 'SGD');

$summary = [
    'listings' => mj_admin_v287_count('mj_listings', 'user_id=?', [$id]),
    'companies' => mj_admin_v287_count('mj_companies', 'user_id=?', [$id]),
    'orders' => mj_admin_v287_count('mj_orders', '(buyer_id=? OR seller_id=?)', [$id,$id]),
    'payments' => 0, // v2.9.15: legacy customer-to-seller mj_payments are hidden.
    'upgrade_proofs' => mj_admin_v287_count('mj_upgrade_payment_proofs', 'user_id=?', [$id]) + mj_admin_v287_count('mj_payment_batches', 'user_id=?', [$id]),
    'payment_requests' => mj_admin_v287_count('mj_payment_requests', 'user_id=?', [$id]),
    'invoices' => mj_admin_v287_count('mj_invoices', 'user_id=?', [$id]),
    'support' => mj_admin_v287_count('mj_support_tickets', 'user_id=?', [$id]),
    'activity_logs' => mj_admin_v287_count('mj_user_activity_logs', 'user_id=?', [$id]),
];
$summary['all_payments'] = $summary['payments'] + $summary['upgrade_proofs'] + $summary['payment_requests'] + $summary['invoices'];

$listings = table_exists('mj_listings') ? mj_admin_v287_rows('SELECT * FROM mj_listings WHERE user_id=? ORDER BY id DESC LIMIT 100', [$id]) : [];
$companies = table_exists('mj_companies') ? mj_admin_v287_rows('SELECT * FROM mj_companies WHERE user_id=? ORDER BY id DESC LIMIT 100', [$id]) : [];
$paymentRows = [];
$invoiceRows = [];
$proofRows = [];
if (function_exists('mj291_payment_ensure_schema')) { mj291_payment_ensure_schema(); }
if (table_exists('mj_payment_batches')) {
    $rows = mj_admin_v287_rows('SELECT * FROM mj_payment_batches WHERE user_id=? ORDER BY id DESC LIMIT 100', [$id]);
    foreach ($rows as $r) { $proofRows[] = ['source'=>'Invoice Checkout','id'=>$r['id'],'title'=>($r['batch_no'] ?? 'Payment Batch').' / Invoice #'.($r['invoice_id'] ?? '-'),'amount'=>mj_admin_v287_amount(['amount'=>$r['total_amount']??0,'currency_code'=>$r['currency_code']??$currency],$currency),'method'=>$r['payment_method'] ?? '', 'ref'=>$r['reference_no'] ?? '', 'proof'=>$r['proof_path'] ?? '', 'status'=>$r['status'] ?? '', 'date'=>mj_admin_v287_date($r), 'raw'=>$r]; }
}
$orderRows = [];
$offerRows = [];
$quoteRows = [];
$supportRows = [];
$verificationRows = [];
$activityRows = [];
$events = [];

foreach ($listings as $r) {
    mj_admin_v287_add_event($events, mj_admin_v287_date($r), 'Listing', '#'.$r['id'].' '.$r['title'], 'Status: '.($r['status'] ?? '-').' • Price: '.mj_admin_v287_amount($r, $currency), (string)($r['status'] ?? ''), 'listing-edit.php?id='.(int)$r['id'], 'fa-tag');
}
foreach ($companies as $r) {
    mj_admin_v287_add_event($events, mj_admin_v287_date($r), 'Company', '#'.$r['id'].' '.$r['name'], 'Status: '.($r['status'] ?? '-').' • Verified: '.(!empty($r['is_verified']) ? 'Yes' : 'No'), (string)($r['status'] ?? ''), 'company-edit.php?id='.(int)$r['id'], 'fa-building');
}

if (table_exists('mj_payment_requests')) {
    $rows = mj_admin_v287_rows('SELECT * FROM mj_payment_requests WHERE user_id=? ORDER BY id DESC LIMIT 100', [$id]);
    foreach ($rows as $r) { $paymentRows[] = ['source'=>'Payment Request','id'=>$r['id'],'title'=>$r['title'] ?? ($r['request_type'] ?? 'Payment request'),'amount'=>mj_admin_v287_amount($r,$currency),'method'=>'-','ref'=>$r['reference_type'] ?? '', 'proof'=>'','status'=>$r['status'] ?? '', 'date'=>mj_admin_v287_date($r), 'raw'=>$r]; mj_admin_v287_add_event($events, mj_admin_v287_date($r), 'Payment Request', '#'.$r['id'].' '.($r['title'] ?? 'Payment request'), mj_admin_v287_amount($r,$currency).' • '.($r['request_type'] ?? ''), (string)($r['status'] ?? ''), 'payment-center.php?tab=history', 'fa-file-invoice-dollar'); }
}
if (table_exists('mj_invoices')) {
    $rows = mj_admin_v287_rows('SELECT * FROM mj_invoices WHERE user_id=? ORDER BY id DESC LIMIT 100', [$id]);
    foreach ($rows as $r) { $invoiceRows[] = ['source'=>'Invoice','id'=>$r['id'],'title'=>$r['invoice_no'] ?? ($r['title'] ?? 'Invoice'),'amount'=>mj_admin_v287_amount($r,$currency),'method'=>'-','ref'=>$r['invoice_type'] ?? '', 'proof'=>'','status'=>$r['status'] ?? '', 'date'=>mj_admin_v287_date($r), 'raw'=>$r]; mj_admin_v287_add_event($events, mj_admin_v287_date($r), 'Invoice', '#'.$r['id'].' '.($r['invoice_no'] ?? 'Invoice'), mj_admin_v287_amount($r,$currency).' • '.($r['title'] ?? ''), (string)($r['status'] ?? ''), 'payment-center.php?tab=history', 'fa-file-invoice'); }
}
// v2.9.15: legacy customer-to-seller mj_payments are not shown. User-to-admin billing remains in invoices/proofs below.
if (table_exists('mj_upgrade_payment_proofs')) {
    $rows = mj_admin_v287_rows('SELECT * FROM mj_upgrade_payment_proofs WHERE user_id=? ORDER BY id DESC LIMIT 100', [$id]);
    foreach ($rows as $r) { $proofRows[] = ['source'=>'Upgrade Proof','id'=>$r['id'],'title'=>($r['request_type'] ?? 'Upgrade').' #'.($r['request_id'] ?? '-'),'amount'=>mj_admin_v287_amount($r,$currency),'method'=>$r['payment_method'] ?? '', 'ref'=>$r['reference_no'] ?? '', 'proof'=>$r['proof_path'] ?? '', 'status'=>$r['status'] ?? '', 'date'=>mj_admin_v287_date($r), 'raw'=>$r]; mj_admin_v287_add_event($events, mj_admin_v287_date($r), 'Payment Proof', '#'.$r['id'].' '.($r['request_type'] ?? 'Upgrade proof'), mj_admin_v287_amount($r,$currency).' • Ref: '.($r['reference_no'] ?? '-'), (string)($r['status'] ?? ''), 'payment-center.php?tab=review', 'fa-upload'); }
}
if (table_exists('mj_payment_proofs')) {
    $rows = mj_admin_v287_rows('SELECT * FROM mj_payment_proofs WHERE user_id=? ORDER BY id DESC LIMIT 100', [$id]);
    foreach ($rows as $r) { $proofRows[] = ['source'=>'Payment Proof','id'=>$r['id'],'title'=>($r['related_type'] ?? 'Proof').' #'.($r['related_id'] ?? '-'),'amount'=>mj_admin_v287_amount($r,$currency),'method'=>$r['payment_method'] ?? '', 'ref'=>'', 'proof'=>$r['proof_file'] ?? '', 'status'=>$r['status'] ?? '', 'date'=>mj_admin_v287_date($r), 'raw'=>$r]; mj_admin_v287_add_event($events, mj_admin_v287_date($r), 'Payment Proof', '#'.$r['id'].' '.($r['related_type'] ?? 'Proof'), mj_admin_v287_amount($r,$currency).' • Method: '.($r['payment_method'] ?? '-'), (string)($r['status'] ?? ''), 'payment-center.php?tab=review', 'fa-upload'); }
}
// v2.9.15: customer-to-seller order payment proofs are disabled and hidden from admin user activity.
if (table_exists('mj_orders')) {
    $orderRows = mj_admin_v287_rows('SELECT * FROM mj_orders WHERE buyer_id=? OR seller_id=? ORDER BY id DESC LIMIT 100', [$id,$id]);
    foreach ($orderRows as $r) { $role = ((int)($r['buyer_id'] ?? 0) === $id) ? 'Buyer' : 'Seller'; mj_admin_v287_add_event($events, mj_admin_v287_date($r), 'Order', '#'.$r['id'].' '.$role, mj_admin_v287_amount($r,$currency).' • Listing #'.($r['listing_id'] ?? '-'), (string)($r['status'] ?? ''), 'orders.php', 'fa-shopping-bag'); }
}
if (table_exists('mj_offers')) {
    $offerRows = mj_admin_v287_rows('SELECT * FROM mj_offers WHERE buyer_id=? OR seller_id=? ORDER BY id DESC LIMIT 100', [$id,$id]);
    foreach ($offerRows as $r) { $role = ((int)($r['buyer_id'] ?? 0) === $id) ? 'Buyer offer' : 'Seller received'; mj_admin_v287_add_event($events, mj_admin_v287_date($r), 'Offer', '#'.$r['id'].' '.$role, mj_admin_v287_amount($r,$currency).' • Listing #'.($r['listing_id'] ?? '-'), (string)($r['status'] ?? ''), 'offers.php', 'fa-handshake'); }
}
if (table_exists('mj_quotations')) { foreach (mj_admin_v287_rows('SELECT * FROM mj_quotations WHERE user_id=? ORDER BY id DESC LIMIT 100', [$id]) as $r) { $quoteRows[] = ['source'=>'Quotation','id'=>$r['id'],'title'=>$r['subject'] ?? 'Quotation','amount'=>mj_admin_v287_amount($r,$currency),'status'=>$r['status'] ?? '', 'date'=>mj_admin_v287_date($r)]; mj_admin_v287_add_event($events, mj_admin_v287_date($r), 'Quotation', '#'.$r['id'].' '.($r['subject'] ?? 'Quotation'), mj_admin_v287_amount($r,$currency), (string)($r['status'] ?? ''), 'quote-requests.php', 'fa-file-signature'); } }
if (table_exists('mj_rfq_requests')) { foreach (mj_admin_v287_rows('SELECT * FROM mj_rfq_requests WHERE user_id=? ORDER BY id DESC LIMIT 100', [$id]) as $r) { $quoteRows[] = ['source'=>'RFQ','id'=>$r['id'],'title'=>$r['title'] ?? 'RFQ','amount'=>mj_admin_v287_amount($r,$currency),'status'=>$r['status'] ?? '', 'date'=>mj_admin_v287_date($r)]; mj_admin_v287_add_event($events, mj_admin_v287_date($r), 'Quote Request', '#'.$r['id'].' '.($r['title'] ?? 'RFQ'), mj_admin_v287_amount($r,$currency), (string)($r['status'] ?? ''), 'quote-requests.php', 'fa-clipboard-list'); } }
if (table_exists('mj_quote_requests')) { foreach (mj_admin_v287_rows('SELECT * FROM mj_quote_requests WHERE user_id=? ORDER BY id DESC LIMIT 100', [$id]) as $r) { $quoteRows[] = ['source'=>'Quote Request','id'=>$r['id'],'title'=>$r['title'] ?? 'Quote request','amount'=>'-', 'status'=>$r['status'] ?? '', 'date'=>mj_admin_v287_date($r)]; mj_admin_v287_add_event($events, mj_admin_v287_date($r), 'Quote Request', '#'.$r['id'].' '.($r['title'] ?? 'Quote request'), $r['urgency'] ?? '', (string)($r['status'] ?? ''), 'quote-requests.php', 'fa-clipboard-list'); } }
if (table_exists('mj_support_tickets')) { $supportRows = mj_admin_v287_rows('SELECT * FROM mj_support_tickets WHERE user_id=? ORDER BY id DESC LIMIT 100', [$id]); foreach ($supportRows as $r) { mj_admin_v287_add_event($events, mj_admin_v287_date($r), 'Support', '#'.$r['id'].' '.($r['subject'] ?? 'Ticket'), ($r['category'] ?? '').' • '.substr((string)($r['message'] ?? ''),0,120), (string)($r['status'] ?? ''), 'support.php', 'fa-life-ring'); } }
if (table_exists('mj_verification_requests')) { $verificationRows = mj_admin_v287_rows('SELECT * FROM mj_verification_requests WHERE user_id=? ORDER BY id DESC LIMIT 100', [$id]); foreach ($verificationRows as $r) { mj_admin_v287_add_event($events, mj_admin_v287_date($r), 'Verification', '#'.$r['id'].' '.($r['verification_type'] ?? 'Verification'), $r['note'] ?? '', (string)($r['status'] ?? ''), 'users.php', 'fa-user-check'); } }
if (table_exists('mj_chats')) { foreach (mj_admin_v287_rows('SELECT * FROM mj_chats WHERE buyer_id=? OR seller_id=? ORDER BY COALESCE(last_message_at, created_at) DESC LIMIT 100', [$id,$id]) as $r) { mj_admin_v287_add_event($events, mj_admin_v287_date($r), 'Chat', '#'.$r['id'].' Listing #'.($r['listing_id'] ?? '-'), substr((string)($r['last_message'] ?? ''),0,140), (string)($r['status'] ?? ''), 'reports.php', 'fa-comments'); } }
if (table_exists('mj_reviews')) { foreach (mj_admin_v287_rows('SELECT * FROM mj_reviews WHERE reviewer_id=? OR target_user_id=? ORDER BY id DESC LIMIT 100', [$id,$id]) as $r) { mj_admin_v287_add_event($events, mj_admin_v287_date($r), 'Review', '#'.$r['id'].' Rating '.($r['rating'] ?? '-'), substr((string)($r['review_text'] ?? ''),0,140), (string)($r['status'] ?? ''), 'reviews.php', 'fa-star'); } }
if (table_exists('mj_reports')) { foreach (mj_admin_v287_rows('SELECT * FROM mj_reports WHERE reporter_id=? ORDER BY id DESC LIMIT 100', [$id]) as $r) { mj_admin_v287_add_event($events, mj_admin_v287_date($r), 'Report', '#'.$r['id'].' '.($r['target_type'] ?? 'Report'), ($r['reason'] ?? '').' • '.substr((string)($r['details'] ?? ''),0,120), (string)($r['status'] ?? ''), 'reported-listings.php', 'fa-flag'); } }
if (table_exists('mj_notifications')) { foreach (mj_admin_v287_rows('SELECT * FROM mj_notifications WHERE user_id=? ORDER BY id DESC LIMIT 100', [$id]) as $r) { mj_admin_v287_add_event($events, mj_admin_v287_date($r), 'Notification', '#'.$r['id'].' '.($r['title'] ?? ($r['type'] ?? 'Notification')), substr((string)($r['body'] ?? $r['message'] ?? ''),0,140), empty($r['is_read']) ? 'unread' : 'read', '', 'fa-bell'); } }
if (table_exists('mj_user_activity_logs')) { $activityRows = mj_admin_v287_rows('SELECT * FROM mj_user_activity_logs WHERE user_id=? ORDER BY id DESC LIMIT 150', [$id]); foreach ($activityRows as $r) { mj_admin_v287_add_event($events, mj_admin_v287_date($r), 'User Log', '#'.$r['id'].' '.($r['action'] ?? 'Activity'), $r['description'] ?? '', '', '', 'fa-history'); } }

usort($events, function($a, $b){ return strtotime((string)$b['date']) <=> strtotime((string)$a['date']); });
$events = array_slice($events, 0, 300);

include __DIR__.'/_header.php';
?>
<div class="row">
  <div class="col-12">
    <?php show_flash(); ?>
    <div class="card card-primary card-outline">
      <div class="card-header d-flex align-items-center">
        <h3 class="card-title mb-0"><i class="fas fa-history mr-2"></i>User Full Activity: <?=e($user['name'])?> (#<?=e($id)?>)</h3>
        <div class="ml-auto">
          <a class="btn btn-sm btn-outline-primary" href="user-edit.php?id=<?=e($id)?>"><i class="fas fa-edit mr-1"></i>Edit User</a>
          <a class="btn btn-sm btn-outline-secondary" href="users.php"><i class="fas fa-users mr-1"></i>Back to Users</a>
        </div>
      </div>
      <div class="card-body">
        <div class="row">
          <div class="col-md-4"><b>Email:</b> <?=e($user['email'] ?? '')?><br><b>Mobile:</b> <?=e($user['mobile'] ?? '')?></div>
          <div class="col-md-4"><b>Country:</b> <?=e(($user['flag_emoji'] ?? '').' '.($user['country'] ?? ''))?><br><b>Currency:</b> <?=e($currency)?></div>
          <div class="col-md-4"><b>Status:</b> <?=mj_admin_v287_status($user['is_active'] ? 'active' : 'suspended')?> <b>Email:</b> <?=mj_admin_v287_status($user['is_email_verified'] ? 'verified' : 'not verified')?> <b>Mobile:</b> <?=mj_admin_v287_status($user['is_mobile_verified'] ? 'verified' : 'not verified')?><br><b>Created:</b> <?=e($user['created_at'] ?? '')?></div>
        </div>
      </div>
    </div>
  </div>
</div>

<div class="row">
  <div class="col-lg-2 col-md-4 col-6"><div class="small-box bg-info"><div class="inner"><h3><?=number_format($summary['listings'])?></h3><p>Listings</p></div><div class="icon"><i class="fas fa-tags"></i></div></div></div>
  <div class="col-lg-2 col-md-4 col-6"><div class="small-box bg-primary"><div class="inner"><h3><?=number_format($summary['companies'])?></h3><p>Companies</p></div><div class="icon"><i class="fas fa-building"></i></div></div></div>
  <div class="col-lg-2 col-md-4 col-6"><div class="small-box bg-success"><div class="inner"><h3><?=number_format($summary['orders'])?></h3><p>Enquiries</p></div><div class="icon"><i class="fas fa-shopping-bag"></i></div></div></div>
  <div class="col-lg-2 col-md-4 col-6"><div class="small-box bg-warning"><div class="inner"><h3><?=number_format($summary['all_payments'])?></h3><p>Payments</p></div><div class="icon"><i class="fas fa-credit-card"></i></div></div></div>
  <div class="col-lg-2 col-md-4 col-6"><div class="small-box bg-danger"><div class="inner"><h3><?=number_format($summary['support'])?></h3><p>Support</p></div><div class="icon"><i class="fas fa-life-ring"></i></div></div></div>
  <div class="col-lg-2 col-md-4 col-6"><div class="small-box bg-secondary"><div class="inner"><h3><?=number_format(count($events))?></h3><p>Timeline</p></div><div class="icon"><i class="fas fa-stream"></i></div></div></div>
</div>

<div class="card card-outline card-secondary">
  <div class="card-header p-2">
    <ul class="nav nav-pills" id="ua-tabs">
      <li class="nav-item"><a class="nav-link active" href="#timeline" data-toggle="tab">Timeline</a></li>
      <li class="nav-item"><a class="nav-link" href="#listings" data-toggle="tab">Listings</a></li>
      <li class="nav-item"><a class="nav-link" href="#companies" data-toggle="tab">Companies</a></li>
      <li class="nav-item"><a class="nav-link" href="#payments" data-toggle="tab">Payments & Proofs</a></li>
      <li class="nav-item"><a class="nav-link" href="#orders" data-toggle="tab">Enquiries / Offers</a></li>
      <li class="nav-item"><a class="nav-link" href="#quotes" data-toggle="tab">Quotes / Support</a></li>
      <li class="nav-item"><a class="nav-link" href="#security" data-toggle="tab">Logs / Verification</a></li>
    </ul>
  </div>
  <div class="card-body">
    <div class="tab-content">
      <div class="tab-pane active" id="timeline">
        <div class="timeline timeline-inverse">
          <?php if(!$events): ?><div class="alert alert-info">No activity found for this user yet.</div><?php endif; ?>
          <?php $lastDate=''; foreach($events as $ev): $d = $ev['date'] ? date('Y-m-d', strtotime($ev['date'])) : ''; if($d !== $lastDate): $lastDate=$d; ?><div class="time-label"><span class="bg-primary"><?=e($d ?: 'No date')?></span></div><?php endif; ?>
          <div><i class="fas <?=e($ev['icon'])?> bg-info"></i><div class="timeline-item"><span class="time"><i class="far fa-clock"></i> <?=e($ev['date'])?></span><h3 class="timeline-header"><b><?=e($ev['type'])?></b> <?=e($ev['title'])?> <?=mj_admin_v287_status($ev['status'])?></h3><?php if($ev['description']): ?><div class="timeline-body"><?=e($ev['description'])?></div><?php endif; ?><?php if($ev['url']): ?><div class="timeline-footer"><a class="btn btn-sm btn-outline-primary" href="<?=e($ev['url'])?>">Open</a></div><?php endif; ?></div></div>
          <?php endforeach; ?><div><i class="far fa-clock bg-gray"></i></div>
        </div>
      </div>

      <div class="tab-pane" id="listings">
        <div class="table-responsive"><table class="table table-striped table-hover mj-data-table"><thead><tr><th>ID</th><th>Title</th><th>Price</th><th>Status</th><th>Featured</th><th>Sponsored</th><th>Views</th><th>Created</th><th>Action</th></tr></thead><tbody><?php foreach($listings as $r): ?><tr><td><?=e($r['id'])?></td><td><b><?=e($r['title'] ?? '')?></b><br><small><?=e($r['listing_type'] ?? '')?></small></td><td><?=mj_admin_v287_amount($r,$currency)?></td><td><?=mj_admin_v287_status($r['status'] ?? '')?></td><td><?=!empty($r['is_featured'])?'<span class="badge badge-success">Yes</span>':'<span class="badge badge-secondary">No</span>'?></td><td><?=!empty($r['is_sponsored'])?'<span class="badge badge-success">Yes</span>':'<span class="badge badge-secondary">No</span>'?></td><td><?=e($r['views'] ?? 0)?></td><td><?=e(mj_admin_v287_date($r))?></td><td><a class="btn btn-xs btn-outline-primary" href="listing-edit.php?id=<?=e($r['id'])?>">Open</a></td></tr><?php endforeach; ?></tbody></table></div>
      </div>

      <div class="tab-pane" id="companies">
        <div class="table-responsive"><table class="table table-striped table-hover mj-data-table"><thead><tr><th>ID</th><th>Company</th><th>Status</th><th>Verified</th><th>Featured</th><th>Sponsored</th><th>Views</th><th>Created</th><th>Action</th></tr></thead><tbody><?php foreach($companies as $r): ?><tr><td><?=e($r['id'])?></td><td><b><?=e($r['name'] ?? '')?></b><br><small><?=e($r['email'] ?? '')?> <?=e($r['phone'] ?? '')?></small></td><td><?=mj_admin_v287_status($r['status'] ?? '')?></td><td><?=!empty($r['is_verified'])?'<span class="badge badge-success">Verified</span>':'<span class="badge badge-secondary">No</span>'?></td><td><?=!empty($r['is_featured'])?'<span class="badge badge-success">Yes</span>':'<span class="badge badge-secondary">No</span>'?></td><td><?=!empty($r['is_sponsored'])?'<span class="badge badge-success">Yes</span>':'<span class="badge badge-secondary">No</span>'?></td><td><?=e($r['views'] ?? 0)?></td><td><?=e(mj_admin_v287_date($r))?></td><td><a class="btn btn-xs btn-outline-primary" href="company-edit.php?id=<?=e($r['id'])?>">Open</a></td></tr><?php endforeach; ?></tbody></table></div>
      </div>

      <div class="tab-pane" id="payments">
        <h5 class="font-weight-bold">Payment Proofs</h5>
        <div class="table-responsive mb-4"><table class="table table-striped table-hover mj-data-table"><thead><tr><th>Source</th><th>ID</th><th>Request</th><th>Amount</th><th>Method / Ref</th><th>Proof</th><th>Status</th><th>Date</th></tr></thead><tbody><?php foreach($proofRows as $p): $file=mj_admin_v287_file_url($p['proof']); ?><tr><td><?=e($p['source'])?></td><td><?=e($p['id'])?></td><td><?=e($p['title'])?></td><td><?=e($p['amount'])?></td><td><?=e(trim((string)$p['method'].' / '.(string)$p['ref'], ' /'))?></td><td><?php if($file): ?><a href="<?=e($file)?>" target="_blank" class="btn btn-xs btn-outline-primary">View Proof</a><?php else: ?>-<?php endif; ?></td><td><?=mj_admin_v287_status($p['status'])?></td><td><?=e($p['date'])?></td></tr><?php endforeach; ?></tbody></table></div>
        <h5 class="font-weight-bold">Payments / Requests / Invoices</h5>
        <div class="table-responsive"><table class="table table-striped table-hover mj-data-table"><thead><tr><th>Source</th><th>ID</th><th>Title</th><th>Amount</th><th>Method / Ref</th><th>Status</th><th>Date</th></tr></thead><tbody><?php foreach(array_merge($paymentRows,$invoiceRows) as $p): ?><tr><td><?=e($p['source'])?></td><td><?=e($p['id'])?></td><td><?=e($p['title'])?></td><td><?=e($p['amount'])?></td><td><?=e(trim((string)$p['method'].' / '.(string)$p['ref'], ' /'))?></td><td><?=mj_admin_v287_status($p['status'])?></td><td><?=e($p['date'])?></td></tr><?php endforeach; ?></tbody></table></div>
      </div>

      <div class="tab-pane" id="orders">
        <h5 class="font-weight-bold">Enquiry / Offer Records</h5>
        <div class="table-responsive mb-4"><table class="table table-striped table-hover mj-data-table"><thead><tr><th>ID</th><th>Role</th><th>Listing</th><th>Amount</th><th>Status</th><th>Payment Scope</th><th>Date</th></tr></thead><tbody><?php foreach($orderRows as $r): ?><tr><td><?=e($r['id'])?></td><td><?=((int)($r['buyer_id'] ?? 0)===$id)?'Buyer':'Seller'?></td><td><?=e($r['listing_id'] ?? '-')?></td><td><?=mj_admin_v287_amount($r,$currency)?></td><td><?=mj_admin_v287_status($r['status'] ?? '')?></td><td><span class="badge badge-secondary">No Customer Payment</span></td><td><?=e(mj_admin_v287_date($r))?></td></tr><?php endforeach; ?></tbody></table></div>
        <h5 class="font-weight-bold">Offers</h5>
        <div class="table-responsive"><table class="table table-striped table-hover mj-data-table"><thead><tr><th>ID</th><th>Role</th><th>Listing</th><th>Amount</th><th>Status</th><th>Expires</th><th>Date</th></tr></thead><tbody><?php foreach($offerRows as $r): ?><tr><td><?=e($r['id'])?></td><td><?=((int)($r['buyer_id'] ?? 0)===$id)?'Buyer':'Seller'?></td><td><?=e($r['listing_id'] ?? '-')?></td><td><?=mj_admin_v287_amount($r,$currency)?></td><td><?=mj_admin_v287_status($r['status'] ?? '')?></td><td><?=e($r['expires_at'] ?? '')?></td><td><?=e(mj_admin_v287_date($r))?></td></tr><?php endforeach; ?></tbody></table></div>
      </div>

      <div class="tab-pane" id="quotes">
        <h5 class="font-weight-bold">Quotes / RFQ</h5>
        <div class="table-responsive mb-4"><table class="table table-striped table-hover mj-data-table"><thead><tr><th>Source</th><th>ID</th><th>Title</th><th>Amount</th><th>Status</th><th>Date</th></tr></thead><tbody><?php foreach($quoteRows as $r): ?><tr><td><?=e($r['source'])?></td><td><?=e($r['id'])?></td><td><?=e($r['title'])?></td><td><?=e($r['amount'])?></td><td><?=mj_admin_v287_status($r['status'])?></td><td><?=e($r['date'])?></td></tr><?php endforeach; ?></tbody></table></div>
        <h5 class="font-weight-bold">Support Tickets</h5>
        <div class="table-responsive"><table class="table table-striped table-hover mj-data-table"><thead><tr><th>ID</th><th>Subject</th><th>Category</th><th>Status</th><th>Message</th><th>Date</th></tr></thead><tbody><?php foreach($supportRows as $r): ?><tr><td><?=e($r['id'])?></td><td><b><?=e($r['subject'] ?? '')?></b></td><td><?=e($r['category'] ?? '')?></td><td><?=mj_admin_v287_status($r['status'] ?? '')?></td><td><?=e(substr((string)($r['message'] ?? ''),0,140))?></td><td><?=e(mj_admin_v287_date($r))?></td></tr><?php endforeach; ?></tbody></table></div>
      </div>

      <div class="tab-pane" id="security">
        <h5 class="font-weight-bold">Verification Requests</h5>
        <div class="table-responsive mb-4"><table class="table table-striped table-hover mj-data-table"><thead><tr><th>ID</th><th>Type</th><th>Company</th><th>Document</th><th>Status</th><th>Note</th><th>Date</th></tr></thead><tbody><?php foreach($verificationRows as $r): $file=mj_admin_v287_file_url($r['document_path'] ?? ''); ?><tr><td><?=e($r['id'])?></td><td><?=e($r['verification_type'] ?? '')?></td><td><?=e($r['company_id'] ?? '')?></td><td><?php if($file): ?><a href="<?=e($file)?>" target="_blank" class="btn btn-xs btn-outline-primary">View</a><?php else: ?>-<?php endif; ?></td><td><?=mj_admin_v287_status($r['status'] ?? '')?></td><td><?=e(substr((string)($r['note'] ?? $r['admin_note'] ?? ''),0,140))?></td><td><?=e(mj_admin_v287_date($r))?></td></tr><?php endforeach; ?></tbody></table></div>
        <h5 class="font-weight-bold">User Activity Logs</h5>
        <div class="table-responsive"><table class="table table-striped table-hover mj-data-table"><thead><tr><th>ID</th><th>Action</th><th>Description</th><th>IP</th><th>User Agent</th><th>Date</th></tr></thead><tbody><?php foreach($activityRows as $r): ?><tr><td><?=e($r['id'])?></td><td><b><?=e($r['action'] ?? '')?></b></td><td><?=e($r['description'] ?? '')?></td><td><?=e($r['ip_address'] ?? '')?></td><td><small><?=e(substr((string)($r['user_agent'] ?? ''),0,120))?></small></td><td><?=e(mj_admin_v287_date($r))?></td></tr><?php endforeach; ?></tbody></table></div>
      </div>
    </div>
  </div>
</div>
<?php include __DIR__.'/_footer.php'; ?>
