<?php
require_once __DIR__.'/../includes/functions.php';
$admin = require_admin();
$adminTitle = 'Admin Dashboard';
$adminSubtitle = 'Clean control room for approvals, finance, service cart, listings, deals, SMTP and system health.';
if (function_exists('mj2919_cart_ensure_schema')) { mj2919_cart_ensure_schema(); }
if (function_exists('mj291_payment_ensure_schema')) { mj291_payment_ensure_schema(); }
if (function_exists('mj_deal_ensure_schema')) { mj_deal_ensure_schema(); }
if (function_exists('mj_update_review_ensure_schema')) { mj_update_review_ensure_schema(); }

function mj2919_dash_count(string $table, string $where='1=1', array $params=[]): int { try { return table_exists($table) ? safe_count('SELECT COUNT(*) c FROM '.$table.' WHERE '.$where, $params) : 0; } catch(Throwable $e) { return 0; } }
function mj2919_dash_sum(string $table, string $col, string $where='1=1', array $params=[]): float { try { if(!table_exists($table)) return 0.0; $r=one('SELECT COALESCE(SUM('.$col.'),0) v FROM '.$table.' WHERE '.$where,$params); return (float)($r['v']??0); } catch(Throwable $e) { return 0.0; } }
function mj2919_status_link(string $label, string $value, string $url, string $icon, string $tone='primary', string $sub=''): string {
    return '<div class="col-xl-3 col-md-6 mb-3"><a class="mj2919-card mj2919-'.$tone.'" href="'.e($url).'"><span><i class="'.$icon.'"></i></span><div><b>'.e($value).'</b><small>'.e($label).'</small>'.($sub!==''?'<em>'.e($sub).'</em>':'').'</div></a></div>';
}

$pendingPayments = mj2919_dash_count('mj_payment_batches', 'status IN ("pending_review","payment_uploaded")');
$walletTopups = 0;
try { if (table_exists('mj_payment_batch_items')) { $walletTopups = safe_count('SELECT COUNT(DISTINCT b.id) c FROM mj_payment_batches b INNER JOIN mj_payment_batch_items i ON i.batch_id=b.id WHERE i.item_type="wallet_topup" AND b.status IN ("pending_review","payment_uploaded")'); } } catch(Throwable $e) {}
$listingUpdates = mj2919_dash_count('mj_listing_revisions', 'status="pending"');
$companyUpdates = mj2919_dash_count('mj_company_revisions', 'status="pending"');
$dealUpdates = mj2919_dash_count('mj_deal_revisions', 'status="pending"');
$pendingListings = mj2919_dash_count('mj_listings', 'status IN ("pending","pending_review")');
$pendingCompanies = mj2919_dash_count('mj_companies', 'status IN ("pending","pending_review")');
$pendingDeals = mj2919_dash_count('mj_deals', 'status IN ("pending","pending_review")');
$dealEnquiriesToday = mj2919_dash_count('mj_deal_enquiries', 'DATE(created_at)=CURDATE()');
$activeListings = mj2919_dash_count('mj_listings', 'status IN ("active","approved","published")');
$activeDeals = mj2919_dash_count('mj_deals', 'status IN ("active","approved")');
$openInvoices = mj2919_dash_count('mj_payment_batches', 'status IN ("invoice_created","unpaid","draft")');
$paidAmount = mj2919_dash_sum('mj_receipts', 'amount', 'status IN ("paid","completed")');
$pendingAmount = mj2919_dash_sum('mj_payment_batches', 'total_amount', 'status IN ("pending_review","payment_uploaded")');
$emailFailed = mj2919_dash_count('mj_email_queue', 'status="failed"');
$emailPending = mj2919_dash_count('mj_email_queue', 'status IN ("pending","retry")');
$adminAlerts = function_exists('mj_admin_unread_alert_count') ? mj_admin_unread_alert_count() : 0;
$cartSummary = function_exists('mj2919_admin_cart_summary') ? mj2919_admin_cart_summary() : ['open_carts'=>0,'open_amount'=>0,'invoiced_today'=>0];
$financeMismatch = mj2919_dash_count('mj_admin_alerts', 'module_name IN ("finance","payments") AND is_read=0');
$healthWarnings = 0;
try { if(function_exists('mj_v289_admin_dashboard_metrics')) { $m=mj_v289_admin_dashboard_metrics(); $healthWarnings=(int)($m['errors_open']??0); } } catch(Throwable $e) {}

$v3Charts=function_exists('mj_v300_admin_chart_data')?mj_v300_admin_chart_data():['pending'=>[],'dealStatus'=>[],'revenue'=>[]];
$recentRows = [];
try { if (table_exists('mj_admin_logs')) { $recentRows = all_rows('SELECT * FROM mj_admin_logs ORDER BY id DESC LIMIT 8'); } } catch(Throwable $e) {}
include __DIR__.'/_header.php';
?>
<style>
.mj2919-hero{background:linear-gradient(135deg,#081a3a,#2563eb 55%,#06b6d4);border-radius:22px;color:#fff;box-shadow:0 20px 50px rgba(37,99,235,.22);overflow:hidden}.mj2919-hero .card-body{padding:28px}.mj2919-hero .btn{border-radius:999px;font-weight:700}.mj2919-grid-title{font-weight:800;color:#0f172a;margin:0 0 12px}.mj2919-card{display:flex;align-items:center;gap:16px;min-height:112px;border-radius:20px;padding:18px;background:#fff;color:#0f172a;box-shadow:0 12px 34px rgba(15,23,42,.08);border:1px solid rgba(15,23,42,.06);transition:.18s;text-decoration:none!important}.mj2919-card:hover{transform:translateY(-2px);box-shadow:0 18px 44px rgba(15,23,42,.12)}.mj2919-card span{width:48px;height:48px;border-radius:16px;display:flex;align-items:center;justify-content:center;color:#fff}.mj2919-card b{display:block;font-size:28px;line-height:1}.mj2919-card small{display:block;font-weight:800;margin-top:7px}.mj2919-card em{display:block;font-style:normal;color:#64748b;font-size:12px;margin-top:2px}.mj2919-primary span{background:#2563eb}.mj2919-warning span{background:#f59e0b}.mj2919-success span{background:#10b981}.mj2919-danger span{background:#ef4444}.mj2919-info span{background:#06b6d4}.mj2919-dark span{background:#0f172a}.mj2919-purple span{background:#7c3aed}.mj2919-soft-panel{border:0;border-radius:20px;box-shadow:0 12px 34px rgba(15,23,42,.07)}.mj2919-action-list a{display:flex;align-items:center;justify-content:space-between;padding:13px 0;border-bottom:1px solid #edf2f7;color:#0f172a}.mj2919-action-list a:last-child{border-bottom:0}.mj2919-action-list b{font-size:14px}.mj2919-action-list .badge{border-radius:999px}.mj2919-quick a{display:flex;align-items:center;gap:10px;border:1px solid #e5e7eb;border-radius:16px;padding:14px;color:#0f172a;background:#fff;font-weight:700;text-decoration:none}.mj2919-quick a:hover{border-color:#2563eb;color:#2563eb}
</style>

<div class="card mj2919-hero mb-4">
  <div class="card-body">
    <div class="row align-items-center">
      <div class="col-lg-8">
        <span class="badge badge-light mb-2"><i class="fas fa-bolt mr-1"></i> v2.9.19 Clean Dashboard</span>
        <h2 class="font-weight-bold mb-2">Admin work made simple</h2>
        <p class="mb-3">Review only what needs attention: payments, wallet top-ups, listing/company/deal updates, deal enquiries, carts, failed emails and finance warnings.</p>
        <div class="d-flex flex-wrap" style="gap:10px">
          <a class="btn btn-light" href="action-queue.php"><i class="fas fa-clipboard-check mr-1"></i> Action Queue</a>
          <a class="btn btn-outline-light" href="payment-center.php?tab=review"><i class="fas fa-receipt mr-1"></i> Payment Review</a>
          <a class="btn btn-outline-light" href="cart-abandoned.php"><i class="fas fa-shopping-cart mr-1"></i> Service Carts</a>
          <a class="btn btn-outline-light" href="smtp-settings.php"><i class="fas fa-server mr-1"></i> SMTP Test</a>
        </div>
      </div>
      <div class="col-lg-4 mt-3 mt-lg-0">
        <div class="bg-white text-dark rounded p-3">
          <div class="d-flex justify-content-between"><span>Pending actions</span><b><?=e($pendingPayments+$listingUpdates+$companyUpdates+$dealUpdates+$pendingListings+$pendingCompanies+$pendingDeals)?></b></div>
          <div class="d-flex justify-content-between"><span>Open carts</span><b><?=e($cartSummary['open_carts'] ?? 0)?></b></div>
          <div class="d-flex justify-content-between"><span>Failed emails</span><b class="text-danger"><?=e($emailFailed)?></b></div>
          <small class="text-muted d-block mt-2">Customer-to-seller payment is disabled. Cart is user/seller-to-admin only.</small>
        </div>
      </div>
    </div>
  </div>
</div>

<div class="row mb-4"><div class="col-lg-4 mb-3"><div class="mj-v3-chart-card" data-chart-type="bar" data-mj-v3-chart="<?=mj_v300_chart_data_attr($v3Charts['pending']??[])?>"><h3>Pending actions</h3><p>What admin should handle first.</p></div></div><div class="col-lg-4 mb-3"><div class="mj-v3-chart-card" data-chart-type="bar" data-mj-v3-chart="<?=mj_v300_chart_data_attr($v3Charts['dealStatus']??[])?>"><h3>Deal status</h3><p>Active, pending, expired and promoted deals.</p></div></div><div class="col-lg-4 mb-3"><div class="mj-v3-chart-card" data-chart-type="line" data-mj-v3-chart="<?=mj_v300_chart_data_attr($v3Charts['revenue']??[])?>"><h3>Revenue trend</h3><p>Recent paid receipt trend.</p></div></div></div>
<h5 class="mj2919-grid-title">Today’s priority</h5>
<div class="row">
  <?=mj2919_status_link('Payment approvals',(string)$pendingPayments,'payment-center.php?tab=review','fas fa-credit-card','warning','Manual proof needs admin approval')?>
  <?=mj2919_status_link('Wallet top-ups',(string)$walletTopups,'payment-center.php?tab=wallet','fas fa-wallet','success','Top-up proof pending')?>
  <?=mj2919_status_link('Listing updates',(string)$listingUpdates,'listing-revisions.php','fas fa-code-branch','primary','User edits waiting review')?>
  <?=mj2919_status_link('Company updates',(string)$companyUpdates,'company-revisions.php','fas fa-building','info','Company edits waiting review')?>
  <?=mj2919_status_link('Deal updates',(string)$dealUpdates,'deal-revisions.php','fas fa-fire','purple','Deal edits waiting review')?>
  <?=mj2919_status_link('Pending deals',(string)$pendingDeals,'deals.php?status=pending','fas fa-clock','warning','New deals waiting approval')?>
  <?=mj2919_status_link('Deal enquiries today',(string)$dealEnquiriesToday,'deal-enquiries.php','fas fa-envelope-open-text','success','Lead follow-up')?>
  <?=mj2919_status_link('Open service carts',(string)($cartSummary['open_carts'] ?? 0),'cart-abandoned.php','fas fa-shopping-cart','dark',money((float)($cartSummary['open_amount']??0),'SGD'))?>
</div>

<div class="row">
  <div class="col-xl-8 mb-4">
    <div class="card mj2919-soft-panel h-100"><div class="card-header border-0"><h3 class="card-title font-weight-bold"><i class="fas fa-list-check mr-2"></i>One-click action queue</h3></div><div class="card-body mj2919-action-list">
      <a href="payment-center.php?tab=review"><b>Review manual payment proofs</b><span class="badge badge-warning"><?=e($pendingPayments)?></span></a>
      <a href="payment-center.php?tab=wallet"><b>Review wallet top-up payments</b><span class="badge badge-success"><?=e($walletTopups)?></span></a>
      <a href="update-reviews.php"><b>Review listing/company/deal updates</b><span class="badge badge-primary"><?=e($listingUpdates+$companyUpdates+$dealUpdates)?></span></a>
      <a href="deals.php?status=pending"><b>Approve pending deals</b><span class="badge badge-warning"><?=e($pendingDeals)?></span></a>
      <a href="deal-enquiries.php"><b>Follow up new deal enquiries</b><span class="badge badge-info"><?=e($dealEnquiriesToday)?></span></a>
      <a href="finance-reconciliation.php"><b>Check finance mismatches</b><span class="badge badge-danger"><?=e($financeMismatch)?></span></a>
      <a href="smtp-settings.php"><b>SMTP queue and failed emails</b><span class="badge badge-danger"><?=e($emailFailed)?></span></a>
    </div></div>
  </div>
  <div class="col-xl-4 mb-4">
    <div class="card mj2919-soft-panel h-100"><div class="card-header border-0"><h3 class="card-title font-weight-bold"><i class="fas fa-chart-pie mr-2"></i>Finance snapshot</h3></div><div class="card-body">
      <div class="d-flex justify-content-between mb-2"><span>Paid receipts</span><b><?=money($paidAmount,'SGD')?></b></div>
      <div class="d-flex justify-content-between mb-2"><span>Pending proof amount</span><b><?=money($pendingAmount,'SGD')?></b></div>
      <div class="d-flex justify-content-between mb-2"><span>Open invoices</span><b><?=e($openInvoices)?></b></div>
      <div class="d-flex justify-content-between mb-2"><span>Cart amount</span><b><?=money((float)($cartSummary['open_amount']??0),'SGD')?></b></div>
      <hr><a class="btn btn-primary btn-block rounded-pill" href="finance-summary.php">Open Finance Summary</a>
    </div></div>
  </div>
</div>

<div class="row">
  <div class="col-xl-8 mb-4">
    <div class="card mj2919-soft-panel"><div class="card-header border-0"><h3 class="card-title font-weight-bold"><i class="fas fa-bolt mr-2"></i>Quick shortcuts</h3></div><div class="card-body"><div class="row mj2919-quick">
      <div class="col-md-4 mb-3"><a href="users.php"><i class="fas fa-users"></i> Users</a></div>
      <div class="col-md-4 mb-3"><a href="listings.php"><i class="fas fa-tags"></i> Listings</a></div>
      <div class="col-md-4 mb-3"><a href="companies.php"><i class="fas fa-building"></i> Companies</a></div>
      <div class="col-md-4 mb-3"><a href="deals.php"><i class="fas fa-fire"></i> Deals</a></div>
      <div class="col-md-4 mb-3"><a href="deal-import.php"><i class="fas fa-file-import"></i> Import Deals</a></div>
      <div class="col-md-4 mb-3"><a href="reports.php"><i class="fas fa-chart-line"></i> Reports</a></div>
      <div class="col-md-4 mb-3"><a href="smtp-settings.php"><i class="fas fa-server"></i> SMTP Settings</a></div>
      <div class="col-md-4 mb-3"><a href="system-health.php"><i class="fas fa-heartbeat"></i> System Health</a></div>
      <div class="col-md-4 mb-3"><a href="migration-status.php"><i class="fas fa-code-branch"></i> Migration Status</a></div>
    </div></div></div>
  </div>
  <div class="col-xl-4 mb-4">
    <div class="card mj2919-soft-panel"><div class="card-header border-0"><h3 class="card-title font-weight-bold"><i class="fas fa-heartbeat mr-2"></i>System health</h3></div><div class="card-body">
      <div class="d-flex justify-content-between mb-2"><span>Unread admin alerts</span><b><?=e($adminAlerts)?></b></div>
      <div class="d-flex justify-content-between mb-2"><span>Email pending/retry</span><b><?=e($emailPending)?></b></div>
      <div class="d-flex justify-content-between mb-2"><span>Failed emails</span><b class="text-danger"><?=e($emailFailed)?></b></div>
      <div class="d-flex justify-content-between mb-2"><span>Open errors</span><b><?=e($healthWarnings)?></b></div>
      <hr><a class="btn btn-outline-primary btn-block rounded-pill" href="system-health.php">Open System Health</a>
    </div></div>
  </div>
</div>

<?php if($recentRows): ?>
<div class="card mj2919-soft-panel mb-4"><div class="card-header border-0"><h3 class="card-title font-weight-bold"><i class="fas fa-history mr-2"></i>Recent admin activity</h3></div><div class="card-body table-responsive p-0"><table class="table table-hover mb-0"><thead><tr><th>Time</th><th>Action</th><th>Table</th><th>Row</th></tr></thead><tbody><?php foreach($recentRows as $r): ?><tr><td><?=e($r['created_at']??'')?></td><td><b><?=e($r['action']??'')?></b></td><td><?=e($r['table_name']??'')?></td><td><?=e($r['row_id']??'')?></td></tr><?php endforeach; ?></tbody></table></div></div>
<?php endif; ?>

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