<?php
/* ============================================================================
   WBMCZ ADMIN — DASHBOARD

   What the office needs to know before it starts work: what came in, what went
   out, what is waiting, and who is on the books.

   Two things are deliberately NOT here:

     · the grid of module links that used to sit at the bottom. Every one of
       those tiles was a second copy of a sidebar entry, so the page opened with
       a menu inside a menu.
     · any figure the person looking at it is not allowed to see. Each block is
       behind its own key (dashboard.col.earning, .orders, .users …), so an
       employee who was given orders but not money sees the order block and no
       empty money row where the numbers used to be.

   Every figure says underneath it exactly what was counted, because "income"
   means four different things depending on who is asking.
   ============================================================================ */

require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/Language.php';
require_once __DIR__ . '/../includes/acl.php';

if (!isLoggedIn() || !isAdmin()) { redirect('login.php'); }

acl_ensure_schema($db);
acl_guard('dashboard.view');

$lang         = new Language($db);
$current_lang = $lang->getCurrentLanguage();
$user_id      = (int)$_SESSION['user_id'];

$user_data = $db->select("SELECT * FROM users WHERE id = ?", [$user_id]);
$user      = !empty($user_data) ? $user_data[0] : null;
if (!$user) { session_destroy(); redirect('login.php'); }

/* which blocks this account may see */
$see = [
    'waiting' => acl_col('dashboard', 'waiting'),
    'earning' => acl_col('dashboard', 'earning'),
    'orders'  => acl_col('dashboard', 'orders'),
    'users'   => acl_col('dashboard', 'users'),
    'wallet'  => acl_col('dashboard', 'wallet'),
    'charts'  => acl_col('dashboard', 'charts'),
    'recent'  => acl_col('dashboard', 'recent'),
];

/* ---------------------------------------------------------------------------
   READING THE FIGURES

   Every query is wrapped, because a database that has not had every migration
   run should show a dashboard with a gap in it, not a white page.
   --------------------------------------------------------------------------- */
function d1($db, $sql, $p = [], $col = 'v', $default = 0) {
    try { $r = $db->select($sql, $p); return !empty($r) ? $r[0][$col] : $default; }
    catch (\Throwable $e) { return $default; }
}
function dall($db, $sql, $p = []) {
    try { return $db->select($sql, $p); } catch (\Throwable $e) { return []; }
}
function rs($n) { return '₹' . number_format((float)$n, 2); }
function nz($n) { return number_format((int)$n); }

/* soft delete is not on every copy of the database yet */
$has_del = false;
try {
    $__r = $db->getConnection()->query("SHOW COLUMNS FROM users LIKE 'deleted_at'");
    $has_del = ($__r && $__r->num_rows > 0);
} catch (\Throwable $e) {}
$alive = $has_del ? " AND deleted_at IS NULL" : "";

/* ---- people ---- */
$P = ['members' => 0, 'pro' => 0, 'free' => 0, 'sellers' => 0, 'sellers_live' => 0,
      'staff' => 0, 'blocked' => 0, 'new_month' => 0, 'referred' => 0, 'referrers' => 0];
if ($see['users']) {
    $r = dall($db, "SELECT user_type,
                           COUNT(*) c,
                           SUM(COALESCE(status,1) = 1) live,
                           SUM(COALESCE(is_subscribed,0) = 1) pro,
                           SUM(MONTH(created_at) = MONTH(CURRENT_DATE()) AND YEAR(created_at) = YEAR(CURRENT_DATE())) fresh
                      FROM users WHERE 1 $alive GROUP BY user_type");
    foreach ($r as $row) {
        $t = (string)$row['user_type'];
        if ($t === 'customer') {
            $P['members']   = (int)$row['c'];
            $P['pro']       = (int)$row['pro'];
            $P['free']      = $P['members'] - $P['pro'];
            $P['blocked']   = (int)$row['c'] - (int)$row['live'];
            $P['new_month'] = (int)$row['fresh'];
        } elseif ($t === 'seller') {
            $P['sellers']      = (int)$row['c'];
            $P['sellers_live'] = (int)$row['live'];
            $P['new_month']   += (int)$row['fresh'];
        } elseif ($t === 'admin') {
            $P['staff'] = (int)$row['c'];
        }
    }
    $P['referred']  = (int)d1($db, "SELECT COUNT(*) v FROM users WHERE referred_by IS NOT NULL AND referred_by <> 0 $alive");
    $P['referrers'] = (int)d1($db, "SELECT COUNT(DISTINCT referred_by) v FROM users WHERE referred_by IS NOT NULL AND referred_by <> 0 $alive");
}

/* ---- orders ---- */
$O = ['total' => 0, 'done' => 0, 'moving' => 0, 'lost' => 0, 'month' => 0, 'today' => 0];
if ($see['orders']) {
    foreach (dall($db, "SELECT LOWER(COALESCE(status,'')) s, COUNT(*) c FROM orders GROUP BY 1") as $row) {
        $c = (int)$row['c'];
        $O['total'] += $c;
        if ($row['s'] === 'completed')                              { $O['done']   += $c; }
        elseif (in_array($row['s'], ['cancelled', 'failed'], true)) { $O['lost']   += $c; }
        else                                                        { $O['moving'] += $c; }
    }
    $O['month'] = (int)d1($db, "SELECT COUNT(*) v FROM orders WHERE MONTH(created_at)=MONTH(CURRENT_DATE()) AND YEAR(created_at)=YEAR(CURRENT_DATE())");
    $O['today'] = (int)d1($db, "SELECT COUNT(*) v FROM orders WHERE DATE(created_at) = CURDATE()");
}

/* ---- money ----
   Turnover is what customers were charged on orders that completed.
   Expenses are what leaves the company again: the seller's cut, the referral,
   the staff share. Two places record those — the share ledger, and the payout
   column on the order itself — so both are read and the breakdown is printed
   under the tile, where a double count would be obvious rather than hidden.
   Company income is what is left. */
$M = ['turnover' => 0.0, 'month' => 0.0, 'last_month' => 0.0, 'orders_done' => 0,
      'seller' => 0.0, 'referral' => 0.0, 'staff' => 0.0, 'discount' => 0.0,
      'seller_orders' => 0.0, 'expenses' => 0.0, 'company' => 0.0,
      'subs' => 0.0, 'subs_n' => 0, 'due' => 0.0, 'advance' => 0.0];
if ($see['earning']) {
    $M['turnover']    = (float)d1($db, "SELECT COALESCE(SUM(amount),0) v FROM orders WHERE LOWER(COALESCE(status,'')) = 'completed'");
    $M['orders_done'] = (int)  d1($db, "SELECT COUNT(*) v FROM orders WHERE LOWER(COALESCE(status,'')) = 'completed'");
    $M['month']       = (float)d1($db, "SELECT COALESCE(SUM(amount),0) v FROM orders WHERE LOWER(COALESCE(status,''))='completed' AND MONTH(created_at)=MONTH(CURRENT_DATE()) AND YEAR(created_at)=YEAR(CURRENT_DATE())");
    $M['last_month']  = (float)d1($db, "SELECT COALESCE(SUM(amount),0) v FROM orders WHERE LOWER(COALESCE(status,''))='completed' AND created_at >= DATE_FORMAT(CURRENT_DATE() - INTERVAL 1 MONTH, '%Y-%m-01') AND created_at < DATE_FORMAT(CURRENT_DATE(), '%Y-%m-01')");

    foreach (dall($db, "SELECT share_type t, COALESCE(SUM(amount),0) a FROM product_share_ledger GROUP BY share_type") as $row) {
        switch ((string)$row['t']) {
            case 'seller':                $M['seller']   = (float)$row['a']; break;
            case 'referral':              $M['referral'] = (float)$row['a']; break;
            case 'staff':                 $M['staff']    = (float)$row['a']; break;
            case 'subscription_discount': $M['discount'] = (float)$row['a']; break;
        }
    }
    $M['seller_orders'] = (float)d1($db, "SELECT COALESCE(SUM(seller_payout),0) v FROM orders WHERE LOWER(COALESCE(stage,'')) <> 'cancelled'");
    $M['due']           = (float)d1($db, "SELECT COALESCE(SUM(due_amount),0) v FROM orders WHERE LOWER(COALESCE(stage,'')) <> 'cancelled'");
    $M['advance']       = (float)d1($db, "SELECT COALESCE(SUM(paid_amount),0) v FROM orders WHERE LOWER(COALESCE(payment_mode,''))='advance' AND LOWER(COALESCE(stage,''))<>'cancelled'");

    $M['expenses'] = $M['seller'] + $M['referral'] + $M['staff'] + $M['seller_orders'];
    $M['company']  = $M['turnover'] - $M['expenses'];

    $M['subs']   = (float)d1($db, "SELECT COALESCE(SUM(amount),0) v FROM user_subscriptions WHERE LOWER(COALESCE(status,'')) <> 'cancelled'");
    $M['subs_n'] = (int)  d1($db, "SELECT COUNT(*) v FROM user_subscriptions WHERE LOWER(COALESCE(status,'')) <> 'cancelled'");
}

/* ---- money sitting still ---- */
$W = ['wallets' => 0.0, 'bonus' => 0.0, 'seller_cash' => 0.0, 'seller_owed' => 0.0];
if ($see['wallet']) {
    $W['wallets']     = (float)d1($db, "SELECT COALESCE(SUM(wallet_balance),0) v FROM users WHERE 1 $alive");
    $W['bonus']       = (float)d1($db, "SELECT COALESCE(SUM(bonus_wallet),0) v FROM users WHERE 1 $alive");
    $W['seller_cash'] = (float)d1($db, "SELECT COALESCE(SUM(amount),0) v FROM seller_collections WHERE LOWER(status)='approved'");
    $W['seller_owed'] = $W['seller_cash'] - (float)d1($db, "SELECT COALESCE(SUM(amount),0) v FROM seller_settlements WHERE direction='in'");
    if ($W['seller_owed'] < 0) { $W['seller_owed'] = 0.0; }
}

/* ---- what is waiting for somebody ----
   Each of these is a desk on the Activity & Task board, so each one links
   straight to the desk rather than to a screen that only shows the number. */
$Q = [];
$__q = function ($label, $icon, $tone, $n, $url) use (&$Q, $see) {
    if (!$see['waiting']) { return; }
    $Q[] = ['label' => $label, 'icon' => $icon, 'tone' => $tone, 'n' => (int)$n, 'url' => $url];
};
if (acl_can(['kyc.view', 'tasks.view'])) {
    $__q('KYC to check', 'fa-id-card-clip', 'amber',
        d1($db, "SELECT COUNT(*) v FROM kyc_details WHERE LOWER(COALESCE(status,'')) IN ('pending','submitted','')"),
        'activity_task.php?role=user&tab=kyc_pending');
}
if (acl_can(['sellers.view', 'tasks.view'])) {
    $__q('Seller requests', 'fa-store', 'emerald',
        d1($db, "SELECT COUNT(*) v FROM seller_upgrade_requests WHERE LOWER(COALESCE(status,''))='pending'"),
        'activity_task.php?role=seller&tab=seller_request');
}
if (acl_can(['products.view', 'tasks.view'])) {
    $__q('Product requests', 'fa-box-open', 'sky',
        d1($db, "SELECT COUNT(*) v FROM seller_services WHERE COALESCE(status,0) = 0"),
        'activity_task.php?role=seller&tab=product_request');
}
if (acl_can(['orders.view', 'tasks.view'])) {
    $__q('Visits to make', 'fa-person-walking', 'orange',
        d1($db, "SELECT COUNT(*) v FROM orders WHERE fulfilment <> 'online'
                  AND LOWER(COALESCE(visit_status,'none')) NOT IN ('done','completed','cancelled')
                  AND LOWER(COALESCE(status,'')) NOT IN ('cancelled','refunded')"),
        'activity_task.php?role=office&tab=visit_collect');
    $__q('Cash to verify', 'fa-receipt', 'rose',
        d1($db, "SELECT COUNT(*) v FROM seller_collections WHERE LOWER(status)='pending'"),
        'activity_task.php?role=office&tab=verify_collect');
}
if (acl_can(['tickets.view'])) {
    $__q('Open tickets', 'fa-headset', 'teal',
        d1($db, "SELECT COUNT(*) v FROM support_tickets WHERE LOWER(COALESCE(status,''))='open'"),
        'activity_task.php?role=user&tab=support_user');
}
if (acl_can(['users.upgrade', 'users.view'])) {
    $__q('Upgrade requests', 'fa-arrow-up-right-dots', 'violet',
        d1($db, "SELECT COUNT(*) v FROM seller_upgrade_requests WHERE LOWER(COALESCE(status,''))='pending'"),
        'upgrade_requests.php');
}

/* ---- where the money comes from ---- */
$top_services = $see['earning']
    ? dall($db, "SELECT service_name, COUNT(*) cnt, COALESCE(SUM(amount),0) total
                   FROM orders WHERE LOWER(COALESCE(status,''))='completed'
                  GROUP BY service_name ORDER BY total DESC LIMIT 6")
    : [];

/* ---- the last few orders ---- */
$recent = $see['recent']
    ? dall($db, "SELECT o.id, o.order_code, o.service_name, o.amount, o.status, o.created_at,
                        u.name, u.profile_pic
                   FROM orders o LEFT JOIN users u ON u.id = o.user_id
                  ORDER BY o.id DESC LIMIT 6")
    : [];

$notifs = dall($db, "SELECT * FROM notifications WHERE user_id = ? AND is_read = 0 ORDER BY created_at DESC LIMIT 5", [$user_id]);

$raw_logo     = getSetting('company_logo', 'assets/images/logo.png');
$company_logo = (strpos($raw_logo, 'http') === 0) ? $raw_logo : '../' . ltrim($raw_logo, '/');
$company_name = getSetting('company_name', 'WBMCZ');
$profile_image_url = !empty($user['profile_pic']) ? '../uploads/profiles/' . $user['profile_pic'] : null;

$month_delta = $M['last_month'] > 0 ? (($M['month'] - $M['last_month']) / $M['last_month']) * 100 : null;

$TONES = [
    'amber'   => 'bg-amber-50 text-amber-600 border-amber-100',
    'emerald' => 'bg-emerald-50 text-emerald-600 border-emerald-100',
    'sky'     => 'bg-sky-50 text-sky-600 border-sky-100',
    'orange'  => 'bg-orange-50 text-orange-600 border-orange-100',
    'rose'    => 'bg-rose-50 text-rose-600 border-rose-100',
    'teal'    => 'bg-teal-50 text-teal-600 border-teal-100',
    'violet'  => 'bg-violet-50 text-violet-600 border-violet-100',
    'indigo'  => 'bg-indigo-50 text-indigo-600 border-indigo-100',
    'slate'   => 'bg-slate-100 text-slate-600 border-slate-200',
];
?>
<!DOCTYPE html>
<html lang="<?php echo $current_lang; ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard — <?php echo htmlspecialchars($company_name); ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Inter', sans-serif; }
        .hide-scrollbar::-webkit-scrollbar { display: none; }
        .hide-scrollbar { -ms-overflow-style: none; scrollbar-width: none; }
        .tile      { background:#fff; border:1px solid #e2e8f0; border-radius:1rem; padding:1.15rem 1.25rem; }
        .tile-n    { font-size:1.55rem; font-weight:800; color:#0f172a; line-height:1.1; letter-spacing:-.02em; }
        .tile-l    { font-size:.72rem; font-weight:700; color:#475569; margin-top:.45rem; }
        .tile-s    { font-size:.66rem; color:#94a3b8; margin-top:.15rem; line-height:1.45; }
        .sec-h     { font-size:.72rem; font-weight:800; letter-spacing:.09em; text-transform:uppercase; color:#94a3b8; margin-bottom:.7rem; }
    </style>
</head>
<body class="bg-gray-50" x-data="{ sidebarOpen: window.innerWidth >= 768, profileOpen: false }">
<div class="flex h-screen overflow-hidden">

    <?php include __DIR__ . '/includes/sidebar.php'; ?>

    <div class="flex-1 flex flex-col min-w-0 bg-gray-100 overflow-hidden">
        <header class="h-20 bg-white text-slate-800 flex items-center justify-between px-4 lg:px-8 shadow-sm border-b border-gray-200 z-40 relative">
            <div class="flex items-center">
                <button @click="sidebarOpen = !sidebarOpen" class="p-2 mr-3 text-slate-500 hover:text-emerald-600 rounded-lg hover:bg-gray-100"><i class="fas fa-bars text-xl"></i></button>
                <a href="../index.php" class="md:hidden flex items-center" x-show="!sidebarOpen"><img src="<?php echo $company_logo; ?>" alt="" class="h-9 w-9 object-contain"></a>
                <div class="hidden md:block">
                    <h2 class="text-xl font-bold text-slate-800">Dashboard</h2>
                    <p class="text-[11px] text-slate-400 -mt-0.5">Good <?php echo (int)date('G') < 12 ? 'morning' : ((int)date('G') < 17 ? 'afternoon' : 'evening'); ?>, <?php echo htmlspecialchars(explode(' ', trim($user['name']))[0]); ?> · <?php echo date('D d M Y'); ?></p>
                </div>
            </div>
            <div class="flex items-center space-x-3 sm:space-x-5 ml-auto">
                <a href="../index.php" target="_blank" class="hidden sm:flex items-center text-sm font-semibold text-gray-500 hover:text-emerald-600"><i class="fas fa-external-link-alt mr-2"></i>Visit Site</a>
                <div class="relative">
                    <button @click="profileOpen = !profileOpen" @click.away="profileOpen = false" class="flex items-center focus:outline-none">
                        <?php if (!empty($profile_image_url) && file_exists($profile_image_url)): ?>
                            <img src="<?php echo $profile_image_url; ?>" class="w-10 h-10 rounded-full border-2 border-emerald-100 object-cover">
                        <?php else: ?>
                            <div class="w-10 h-10 rounded-full bg-emerald-100 border-2 border-emerald-200 text-emerald-600 flex items-center justify-center text-lg font-bold"><?php echo strtoupper(substr($user['name'], 0, 1)); ?></div>
                        <?php endif; ?>
                        <i class="fas fa-chevron-down text-xs ml-2 text-slate-400 hidden sm:block"></i>
                    </button>
                    <div x-show="profileOpen" x-transition style="display:none;" class="absolute right-0 mt-3 w-56 bg-white rounded-xl shadow-2xl py-2 border border-gray-100 z-50">
                        <div class="px-4 py-3 border-b border-gray-100">
                            <p class="text-sm text-gray-500">Signed in as <?php echo htmlspecialchars(ucfirst(acl_level())); ?></p>
                            <p class="text-sm font-bold text-gray-900 truncate"><?php echo htmlspecialchars($user['name']); ?></p>
                        </div>
                        <a href="profile.php" class="block px-4 py-2 text-sm text-gray-700 hover:bg-emerald-50"><i class="fas fa-user mr-2 w-4"></i>My Profile</a>
                        <div class="border-t border-gray-100 mt-2 pt-2">
                            <a href="../logout.php" onclick="return confirm('Sign out?');" class="block px-4 py-2 text-sm text-rose-600 hover:bg-rose-50"><i class="fas fa-sign-out-alt mr-2 w-4"></i>Logout</a>
                        </div>
                    </div>
                </div>
            </div>
        </header>

        <main class="flex-1 overflow-y-auto p-4 md:p-6 lg:p-7">

            <?php if (!empty($Q)): ?>
            <!-- ============ WAITING FOR SOMEBODY ============ -->
            <p class="sec-h">Waiting for somebody</p>
            <div class="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-6 gap-3 mb-7">
                <?php foreach ($Q as $q): $t = $TONES[$q['tone']] ?? $TONES['slate']; ?>
                    <a href="<?php echo htmlspecialchars($q['url']); ?>"
                       class="tile hover:border-slate-300 hover:shadow-sm transition-all <?php echo $q['n'] > 0 ? '' : 'opacity-60'; ?>">
                        <span class="w-8 h-8 rounded-lg border flex items-center justify-center <?php echo $t; ?> mb-2"><i class="fas <?php echo $q['icon']; ?> text-xs"></i></span>
                        <p class="tile-n"><?php echo nz($q['n']); ?></p>
                        <p class="tile-l"><?php echo htmlspecialchars($q['label']); ?></p>
                    </a>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>

            <?php if ($see['earning']): ?>
            <!-- ============ MONEY ============ -->
            <p class="sec-h">Money</p>
            <div class="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-3 mb-7">
                <div class="rounded-2xl p-5 text-white bg-gradient-to-br from-emerald-500 to-teal-600 shadow-lg relative overflow-hidden">
                    <div class="absolute -right-6 -top-6 w-24 h-24 bg-white/20 rounded-full blur-xl"></div>
                    <div class="relative">
                        <span class="w-9 h-9 rounded-lg bg-white/20 border border-white/30 flex items-center justify-center mb-3"><i class="fas fa-wallet text-sm"></i></span>
                        <p class="text-2xl font-extrabold leading-none"><?php echo rs($M['turnover']); ?></p>
                        <p class="text-[12px] font-bold text-emerald-50 mt-1.5">Total income</p>
                        <p class="text-[10.5px] text-emerald-100/80 mt-0.5">What customers paid across <?php echo nz($M['orders_done']); ?> completed order(s)</p>
                    </div>
                </div>

                <div class="tile">
                    <span class="w-8 h-8 rounded-lg border flex items-center justify-center <?php echo $TONES['rose']; ?> mb-2"><i class="fas fa-arrow-trend-down text-xs"></i></span>
                    <p class="tile-n"><?php echo rs($M['expenses']); ?></p>
                    <p class="tile-l">Expenses</p>
                    <p class="tile-s">
                        Seller <?php echo rs($M['seller'] + $M['seller_orders']); ?> ·
                        Referral <?php echo rs($M['referral']); ?> ·
                        Staff <?php echo rs($M['staff']); ?>
                    </p>
                </div>

                <div class="tile">
                    <span class="w-8 h-8 rounded-lg border flex items-center justify-center <?php echo $TONES['indigo']; ?> mb-2"><i class="fas fa-building-columns text-xs"></i></span>
                    <p class="tile-n"><?php echo rs($M['company']); ?></p>
                    <p class="tile-l">Company income</p>
                    <p class="tile-s"><?php echo $M['expenses'] > 0
                        ? 'Total income less the ' . rs($M['expenses']) . ' paid out'
                        : 'Total income less everything paid out — nothing has been recorded as paid out yet, so this is the whole of it'; ?></p>
                </div>

                <div class="tile">
                    <span class="w-8 h-8 rounded-lg border flex items-center justify-center <?php echo $TONES['amber']; ?> mb-2"><i class="fas fa-crown text-xs"></i></span>
                    <p class="tile-n"><?php echo rs($M['subs']); ?></p>
                    <p class="tile-l">Subscription income</p>
                    <p class="tile-s"><?php echo nz($M['subs_n']); ?> subscription(s) taken · counted separately from orders</p>
                </div>
            </div>

            <div class="grid grid-cols-2 xl:grid-cols-4 gap-3 mb-7">
                <div class="tile">
                    <p class="tile-n"><?php echo rs($M['month']); ?></p>
                    <p class="tile-l">This month</p>
                    <p class="tile-s">
                        <?php if ($month_delta === null): ?>
                            Nothing came in last month to compare with
                        <?php else: ?>
                            <span class="<?php echo $month_delta >= 0 ? 'text-emerald-600' : 'text-rose-600'; ?> font-bold">
                                <?php echo $month_delta >= 0 ? '▲' : '▼'; ?> <?php echo number_format(abs($month_delta), 1); ?>%
                            </span>
                            against <?php echo rs($M['last_month']); ?> last month
                        <?php endif; ?>
                    </p>
                </div>
                <div class="tile">
                    <p class="tile-n"><?php echo rs($M['due']); ?></p>
                    <p class="tile-l">Still to collect</p>
                    <p class="tile-s">Owed on orders that are not cancelled</p>
                </div>
                <div class="tile">
                    <p class="tile-n"><?php echo rs($M['advance']); ?></p>
                    <p class="tile-l">Advances taken</p>
                    <p class="tile-s">Paid up front on part-payment orders</p>
                </div>
                <div class="tile">
                    <p class="tile-n"><?php echo rs($M['discount']); ?></p>
                    <p class="tile-l">Given to subscribers</p>
                    <p class="tile-s">What members saved by being subscribed</p>
                </div>
            </div>
            <?php endif; ?>

            <?php if ($see['orders']): ?>
            <!-- ============ ORDERS ============ -->
            <p class="sec-h">Orders</p>
            <div class="grid grid-cols-2 xl:grid-cols-4 gap-3 mb-7">
                <a href="orders.php" class="tile hover:border-slate-300 hover:shadow-sm transition-all">
                    <span class="w-8 h-8 rounded-lg border flex items-center justify-center <?php echo $TONES['slate']; ?> mb-2"><i class="fas fa-box text-xs"></i></span>
                    <p class="tile-n"><?php echo nz($O['total']); ?></p>
                    <p class="tile-l">Total orders</p>
                    <p class="tile-s"><?php echo nz($O['month']); ?> this month · <?php echo nz($O['today']); ?> today</p>
                </a>
                <div class="tile">
                    <span class="w-8 h-8 rounded-lg border flex items-center justify-center <?php echo $TONES['emerald']; ?> mb-2"><i class="fas fa-circle-check text-xs"></i></span>
                    <p class="tile-n"><?php echo nz($O['done']); ?></p>
                    <p class="tile-l">Completed</p>
                    <p class="tile-s"><?php echo $O['total'] > 0 ? number_format($O['done'] / $O['total'] * 100, 1) : '0'; ?>% of everything placed</p>
                </div>
                <div class="tile">
                    <span class="w-8 h-8 rounded-lg border flex items-center justify-center <?php echo $TONES['amber']; ?> mb-2"><i class="fas fa-spinner text-xs"></i></span>
                    <p class="tile-n"><?php echo nz($O['moving']); ?></p>
                    <p class="tile-l">In progress</p>
                    <p class="tile-s">Placed, paid or being worked on</p>
                </div>
                <div class="tile">
                    <span class="w-8 h-8 rounded-lg border flex items-center justify-center <?php echo $TONES['rose']; ?> mb-2"><i class="fas fa-circle-xmark text-xs"></i></span>
                    <p class="tile-n"><?php echo nz($O['lost']); ?></p>
                    <p class="tile-l">Cancelled or failed</p>
                    <p class="tile-s">Not counted in any income figure above</p>
                </div>
            </div>
            <?php endif; ?>

            <?php if ($see['users']): ?>
            <!-- ============ PEOPLE ============ -->
            <p class="sec-h">People</p>
            <div class="grid grid-cols-2 xl:grid-cols-4 gap-3 mb-3">
                <a href="users_all.php" class="tile hover:border-slate-300 hover:shadow-sm transition-all">
                    <span class="w-8 h-8 rounded-lg border flex items-center justify-center <?php echo $TONES['indigo']; ?> mb-2"><i class="fas fa-users text-xs"></i></span>
                    <p class="tile-n"><?php echo nz($P['members']); ?></p>
                    <p class="tile-l">Members</p>
                    <p class="tile-s"><?php echo nz($P['free']); ?> free · <?php echo nz($P['pro']); ?> pro<?php echo $P['blocked'] > 0 ? ' · ' . nz($P['blocked']) . ' blocked' : ''; ?></p>
                </a>
                <a href="users_seller.php" class="tile hover:border-slate-300 hover:shadow-sm transition-all">
                    <span class="w-8 h-8 rounded-lg border flex items-center justify-center <?php echo $TONES['amber']; ?> mb-2"><i class="fas fa-store text-xs"></i></span>
                    <p class="tile-n"><?php echo nz($P['sellers_live']); ?><span class="text-base text-slate-400 font-bold"> / <?php echo nz($P['sellers']); ?></span></p>
                    <p class="tile-l">Sellers active</p>
                    <p class="tile-s"><?php echo nz($P['sellers'] - $P['sellers_live']); ?> on the books but switched off</p>
                </a>
                <a href="refer.php" class="tile hover:border-slate-300 hover:shadow-sm transition-all">
                    <span class="w-8 h-8 rounded-lg border flex items-center justify-center <?php echo $TONES['violet']; ?> mb-2"><i class="fas fa-gift text-xs"></i></span>
                    <p class="tile-n"><?php echo nz($P['referred']); ?></p>
                    <p class="tile-l">Joined by referral</p>
                    <p class="tile-s">Brought in by <?php echo nz($P['referrers']); ?> member(s)</p>
                </a>
                <a href="users_employee.php" class="tile hover:border-slate-300 hover:shadow-sm transition-all">
                    <span class="w-8 h-8 rounded-lg border flex items-center justify-center <?php echo $TONES['teal']; ?> mb-2"><i class="fas fa-user-tie text-xs"></i></span>
                    <p class="tile-n"><?php echo nz($P['staff']); ?></p>
                    <p class="tile-l">Staff accounts</p>
                    <p class="tile-s"><?php echo nz($P['new_month']); ?> new sign-up(s) across the site this month</p>
                </a>
            </div>
            <?php if ($see['wallet']): ?>
            <div class="grid grid-cols-2 xl:grid-cols-4 gap-3 mb-7">
                <div class="tile">
                    <p class="tile-n"><?php echo rs($W['wallets']); ?></p>
                    <p class="tile-l">Held in wallets</p>
                    <p class="tile-s">Members' money, not the company's</p>
                </div>
                <div class="tile">
                    <p class="tile-n"><?php echo rs($W['bonus']); ?></p>
                    <p class="tile-l">Bonus wallets</p>
                    <p class="tile-s">Earned, not deposited</p>
                </div>
                <div class="tile">
                    <p class="tile-n"><?php echo rs($W['seller_cash']); ?></p>
                    <p class="tile-l">Collected by sellers</p>
                    <p class="tile-s">Cash and transfers already verified</p>
                </div>
                <a href="activity_task.php?role=office&tab=seller_dues" class="tile hover:border-slate-300 hover:shadow-sm transition-all">
                    <p class="tile-n <?php echo $W['seller_owed'] > 0 ? 'text-rose-600' : ''; ?>"><?php echo rs($W['seller_owed']); ?></p>
                    <p class="tile-l">Sellers still holding</p>
                    <p class="tile-s">Verified, not yet handed over</p>
                </a>
            </div>
            <?php else: ?><div class="mb-7"></div><?php endif; ?>
            <?php endif; ?>

            <div class="grid grid-cols-1 xl:grid-cols-3 gap-4">

                <?php if ($see['earning']): ?>
                <!-- ============ WHERE THE MONEY COMES FROM ============ -->
                <div class="bg-white border border-slate-200 rounded-2xl overflow-hidden">
                    <div class="px-5 py-4 border-b border-slate-100">
                        <h3 class="font-bold text-slate-800 text-sm">Where the money comes from</h3>
                        <p class="text-[11px] text-slate-400">Completed orders, biggest first</p>
                    </div>
                    <?php if (empty($top_services)): ?>
                        <p class="p-8 text-center text-sm text-slate-400">No completed orders yet.</p>
                    <?php else: $top = (float)$top_services[0]['total']; ?>
                    <div class="p-4 space-y-3">
                        <?php foreach ($top_services as $t): $pc = $top > 0 ? ((float)$t['total'] / $top) * 100 : 0; ?>
                            <div>
                                <div class="flex justify-between items-baseline gap-3 mb-1">
                                    <p class="text-[12.5px] font-semibold text-slate-700 truncate"><?php echo htmlspecialchars((string)$t['service_name']); ?></p>
                                    <p class="text-[12.5px] font-bold text-slate-800 whitespace-nowrap"><?php echo rs($t['total']); ?></p>
                                </div>
                                <div class="h-1.5 rounded-full bg-slate-100 overflow-hidden">
                                    <div class="h-full rounded-full bg-emerald-500" style="width: <?php echo max(3, round($pc)); ?>%"></div>
                                </div>
                                <p class="text-[10.5px] text-slate-400 mt-1"><?php echo nz($t['cnt']); ?> order(s)</p>
                            </div>
                        <?php endforeach; ?>
                    </div>
                    <?php endif; ?>
                </div>
                <?php endif; ?>

                <?php if ($see['recent']): ?>
                <!-- ============ RECENT ORDERS ============ -->
                <div class="bg-white border border-slate-200 rounded-2xl overflow-hidden xl:col-span-2">
                    <div class="px-5 py-4 border-b border-slate-100 flex items-center justify-between">
                        <div>
                            <h3 class="font-bold text-slate-800 text-sm">Latest orders</h3>
                            <p class="text-[11px] text-slate-400">The last six, newest first</p>
                        </div>
                        <a href="orders.php" class="text-[12px] font-bold text-emerald-600 hover:underline">See all →</a>
                    </div>
                    <?php if (empty($recent)): ?>
                        <p class="p-8 text-center text-sm text-slate-400">Nothing has been ordered yet.</p>
                    <?php else: ?>
                    <div class="divide-y divide-slate-100">
                        <?php foreach ($recent as $o):
                            $st = strtolower((string)$o['status']);
                            $stc = $st === 'completed' ? 'bg-emerald-50 text-emerald-700'
                                 : (in_array($st, ['cancelled','failed'], true) ? 'bg-rose-50 text-rose-700' : 'bg-amber-50 text-amber-700');
                        ?>
                        <div class="px-5 py-3 flex items-center gap-3">
                            <div class="w-9 h-9 rounded-full bg-slate-100 text-slate-500 flex items-center justify-center text-xs font-bold flex-shrink-0">
                                <?php echo strtoupper(substr((string)($o['name'] ?: '?'), 0, 1)); ?>
                            </div>
                            <div class="min-w-0 flex-1">
                                <p class="text-[13px] font-semibold text-slate-800 truncate"><?php echo htmlspecialchars((string)$o['service_name']); ?></p>
                                <p class="text-[11px] text-slate-400 truncate">
                                    <?php echo htmlspecialchars((string)($o['name'] ?: 'Unknown')); ?> ·
                                    <?php echo htmlspecialchars((string)($o['order_code'] ?: '#' . $o['id'])); ?> ·
                                    <?php echo date('d M, g:i a', strtotime((string)$o['created_at'])); ?>
                                </p>
                            </div>
                            <div class="text-right flex-shrink-0">
                                <p class="text-[13px] font-extrabold text-slate-800"><?php echo rs($o['amount']); ?></p>
                                <span class="text-[10px] font-bold px-2 py-0.5 rounded-full <?php echo $stc; ?>"><?php echo htmlspecialchars((string)$o['status']); ?></span>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    <?php endif; ?>
                </div>
                <?php endif; ?>
            </div>

            <?php if (!empty($notifs)): ?>
            <div class="mt-4 bg-white border border-slate-200 rounded-2xl overflow-hidden">
                <div class="px-5 py-4 border-b border-slate-100 flex items-center justify-between">
                    <h3 class="font-bold text-slate-800 text-sm">Unread for you</h3>
                    <a href="notifications.php" class="text-[12px] font-bold text-emerald-600 hover:underline">All notifications →</a>
                </div>
                <div class="divide-y divide-slate-100">
                    <?php foreach ($notifs as $n): ?>
                    <div class="px-5 py-3">
                        <p class="text-[13px] font-semibold text-slate-800"><?php echo htmlspecialchars((string)($n['title'] ?? '')); ?></p>
                        <p class="text-[11.5px] text-slate-500"><?php echo htmlspecialchars((string)($n['message'] ?? '')); ?></p>
                        <p class="text-[10.5px] text-slate-400 mt-0.5"><?php echo date('d M Y, g:i a', strtotime((string)$n['created_at'])); ?></p>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endif; ?>

            <?php if (!$see['earning'] && !$see['orders'] && !$see['users'] && !$see['wallet']
                      && !$see['charts'] && !$see['recent'] && empty($Q)): ?>
            <div class="bg-white border border-slate-200 rounded-2xl p-12 text-center">
                <i class="fas fa-lock text-3xl text-slate-300 mb-3"></i>
                <p class="font-bold text-slate-700">Nothing to show here yet</p>
                <p class="text-sm text-slate-400 mt-1 max-w-md mx-auto">Your account can open the dashboard, but none of the figure
                    blocks have been granted to it. Whoever set up your access can turn them on from Custom Roles.</p>
            </div>
            <?php endif; ?>

        </main>
    </div>
</div>
</body>
</html>
