Heray-Was-Here
Server : LiteSpeed
System : Linux uk-fast-web1372.main-hosting.eu 4.18.0-553.121.1.lve.el8.x86_64 #1 SMP Thu Apr 30 16:40:41 UTC 2026 x86_64
User : u390967363 ( 390967363)
PHP Version : 8.2.30
Disable Function : system, exec, shell_exec, passthru, mysql_list_dbs, ini_alter, dl, symlink, link, chgrp, leak, popen, apache_child_terminate, virtual, mb_send_mail
Directory :  /home/u390967363/domains/aibenproperties.com/public_html/app/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : /home/u390967363/domains/aibenproperties.com/public_html/app/dashboard.php
<?php
session_start();
require_once __DIR__ . '/includes/functions.php';
$role = strtolower($_SESSION['user_role'] ?? 'guest');
$isAdminLike = in_array($role, ['admin','super_admin','estate_manager','sales_manager','chairman_ceo']);
if (!$isAdminLike) {
    routeToRoleHome($role);
}
include 'includes/header.php';

// Log Activity
logActivity($_SESSION['user_id'], 'Viewed Dashboard', 'Admin accessed the enterprise control center');

// --- DATA AGGREGATION ---

$companyId = getCurrentCompanyId();
$includeNullCompanyScope = !in_array($role, ['admin', 'super_admin'], true);

if (!function_exists('dashCacheGet')) {
    function dashCacheGet(string $key, int $ttlSeconds) {
        if (empty($_SESSION['dash_cache']) || !is_array($_SESSION['dash_cache'])) return null;
        $it = $_SESSION['dash_cache'][$key] ?? null;
        if (!is_array($it) || !isset($it['t'])) return null;
        if ($ttlSeconds > 0 && (time() - (int)$it['t']) > $ttlSeconds) return null;
        return $it['v'] ?? null;
    }
}
if (!function_exists('dashCacheSet')) {
    function dashCacheSet(string $key, $value): void {
        if (empty($_SESSION['dash_cache']) || !is_array($_SESSION['dash_cache'])) $_SESSION['dash_cache'] = [];
        $_SESSION['dash_cache'][$key] = ['t' => time(), 'v' => $value];
    }
}
$dashAllocTtl = 20;

try {
    $total_sales = function_exists('kpiCountAllocations')
        ? kpiCountAllocations($pdo, kpiAllocationStatuses('completed'), $companyId, $includeNullCompanyScope)
        : 0;
} catch (Exception $e) { $total_sales = 0; }
try {
    $dateCol = function_exists('kpiPaymentDateColumn') ? kpiPaymentDateColumn('payments') : null;
    $total_revenue = function_exists('kpiSumPayments')
        ? kpiSumPayments($pdo, kpiPaymentFinalizedStatuses(), null, null, $companyId ?? null, $dateCol)
        : 0;
} catch (Exception $e) { $total_revenue = 0; }
try {
    $outstanding_balance = function_exists('kpiSumPayments')
        ? kpiSumPayments($pdo, kpiPaymentPendingStatuses(), null, null, $companyId ?? null, null, !in_array($role, ['admin', 'super_admin'], true))
        : 0;
} catch (Exception $e) { $outstanding_balance = 0; }

// 3b. Collection Rate (Verified / Verified + Pending)
$total_collections_base = ($total_revenue ?: 0) + ($outstanding_balance ?: 0);
$collection_rate = $total_collections_base > 0 ? round(($total_revenue / $total_collections_base) * 100) : 0;

// 4. Available Units
try {
    $avail_stmt = $pdo->query("SELECT COUNT(*) FROM properties WHERE status = 'available'");
    $available_units = $avail_stmt->fetchColumn() ?: 0;
} catch (Exception $e) { $available_units = 0; }

// 5. Allocated Units
try {
    $allocated_units = function_exists('kpiCountAllocations')
        ? kpiCountAllocations($pdo, array_merge(kpiAllocationStatuses('active'), kpiAllocationStatuses('completed')), $companyId, $includeNullCompanyScope)
        : 0;
} catch (Exception $e) { $allocated_units = 0; }

// 6. Active Clients
try {
    $clients_stmt = $pdo->query("SELECT COUNT(*) FROM users WHERE role = 'client' AND deleted_at IS NULL");
    $active_clients = $clients_stmt->fetchColumn() ?: 0;
} catch (Exception $e) { $active_clients = 0; }

// Operations KPIs
$ops_cc_pending = 0;
$ops_maint_pending = 0;
$ops_tasks_overdue = 0;
try {
    if ($companyId) {
        $st = $pdo->prepare("SELECT COUNT(*) FROM support_tickets WHERE status IN ('open','pending') AND company_id = ?");
        $st->execute([$companyId]);
        $ops_cc_pending = (int)$st->fetchColumn();
    } else {
        $ops_cc_pending = (int)$pdo->query("SELECT COUNT(*) FROM support_tickets WHERE status IN ('open','pending')")->fetchColumn();
    }
} catch (Exception $e) {}
try {
    if ($companyId) {
        $mt = $pdo->prepare("SELECT COUNT(*) FROM maintenance_requests WHERE status IN ('open','pending','in_progress') AND company_id = ?");
        $mt->execute([$companyId]);
        $ops_maint_pending = (int)$mt->fetchColumn();
    } else {
        $ops_maint_pending = (int)$pdo->query("SELECT COUNT(*) FROM maintenance_requests WHERE status IN ('open','pending','in_progress')")->fetchColumn();
    }
} catch (Exception $e) {}
try {
    if ($companyId) {
        $tk = $pdo->prepare("SELECT COUNT(*) FROM tasks WHERE due_date < NOW() AND status != 'completed' AND company_id = ?");
        $tk->execute([$companyId]);
        $ops_tasks_overdue = (int)$tk->fetchColumn();
    } else {
        $ops_tasks_overdue = (int)$pdo->query("SELECT COUNT(*) FROM tasks WHERE due_date < NOW() AND status != 'completed'")->fetchColumn();
    }
} catch (Exception $e) {}

$adm_admin_pending = 0;
$adm_pay_pending = 0;
$adm_refunds_pending = 0;
$adm_transfers_pending = 0;
$adm_overdue_inst = 0;
$adm_receivables = 0.0;
$adm_payables_outstanding = 0.0;
$adm_payables_outstanding_count = 0;
$adm_expenses_month = 0.0;
$adm_revenue_month = 0.0;
try {
    $where = "status = 'pending'";
    if (function_exists('tableHasColumn') && tableHasColumn('allocations','workflow_stage')) { $where .= " AND workflow_stage = 'admin'"; }
    elseif (function_exists('tableHasColumn') && tableHasColumn('allocations','stage')) { $where .= " AND stage = 'admin'"; }
    elseif (function_exists('tableHasColumn') && tableHasColumn('allocations','forwarded_to_admin')) { $where .= " AND forwarded_to_admin = 1"; }
    $sql = "SELECT COUNT(*) FROM allocations WHERE $where";
    if ($companyId && function_exists('tableHasColumn') && tableHasColumn('allocations','company_id')) { $sql .= " AND company_id = " . (int)$companyId; }
    $adm_admin_pending = (int)$pdo->query($sql)->fetchColumn();
} catch (Exception $e) {}
try {
    $hasTransfers = $pdo->query("SHOW TABLES LIKE 'ownership_transfers'")->rowCount() > 0;
    if ($hasTransfers) {
        $sql = "SELECT COUNT(*) FROM ownership_transfers WHERE status = 'pending'";
        if ($companyId && function_exists('tableHasColumn') && tableHasColumn('ownership_transfers','company_id')) {
            $sql .= " AND (company_id = " . (int)$companyId . " OR company_id IS NULL OR company_id = 0)";
        }
        $adm_transfers_pending = (int)$pdo->query($sql)->fetchColumn();
    }
} catch (Exception $e) { $adm_transfers_pending = 0; }
try {
    $roleNorm = strtolower(str_replace([' ', '-'], '_', (string)($_SESSION['user_role'] ?? 'guest')));
    $adm_pay_pending = function_exists('kpiCountPayments')
        ? kpiCountPayments($pdo, kpiPaymentPendingStatuses(), !in_array($roleNorm, ['admin','super_admin'], true) ? $companyId : null, !in_array($roleNorm, ['admin','super_admin'], true))
        : 0;
} catch (Exception $e) {}
try {
    $sql = "SELECT COUNT(*) FROM refunds WHERE status IN ('pending','requested')";
    if ($companyId && function_exists('tableHasColumn') && tableHasColumn('refunds','company_id')) { $sql .= " AND company_id = " . (int)$companyId; }
    $adm_refunds_pending = (int)$pdo->query($sql)->fetchColumn();
} catch (Exception $e) {}
try {
    if ($companyId) {
        $st = $pdo->prepare("SELECT COUNT(*) FROM installments i LEFT JOIN allocations a ON i.allocation_id = a.id WHERE i.status = 'overdue' AND a.company_id = ?");
        $st->execute([$companyId]); $adm_overdue_inst = (int)$st->fetchColumn();
    } else {
        $adm_overdue_inst = (int)$pdo->query("SELECT COUNT(*) FROM installments WHERE status = 'overdue'")->fetchColumn();
    }
} catch (Exception $e) {}
try {
    $adm_receivables = function_exists('kpiSumInvoiceReceivables')
        ? kpiSumInvoiceReceivables($pdo, $companyId, null, null, $includeNullCompanyScope)
        : 0.0;
} catch (Exception $e) {}

try {
    $mStart = date('Y-m-01');
    $mEnd = date('Y-m-t');
    $dateCol2 = function_exists('kpiPaymentDateColumn') ? kpiPaymentDateColumn('payments') : null;
    $adm_revenue_month = function_exists('kpiSumPayments')
        ? kpiSumPayments($pdo, kpiPaymentFinalizedStatuses(), $mStart, $mEnd, $companyId ?? null, $dateCol2, $includeNullCompanyScope)
        : 0.0;
} catch (Throwable $e) { $adm_revenue_month = 0.0; }
try {
    $tot = function_exists('get_expense_totals') ? get_expense_totals(['company_id' => $companyId]) : null;
    $adm_expenses_month = (float)($tot['total_month'] ?? 0);
} catch (Throwable $e) { $adm_expenses_month = 0.0; }
try {
    $params = [];
    $where = [];
    if ($pdo->query("SHOW TABLES LIKE 'expenses_manual'")->rowCount() > 0 && function_exists('tableHasColumn') && tableHasColumn('expenses_manual', 'status') && tableHasColumn('expenses_manual', 'amount')) {
        if (tableHasColumn('expenses_manual', 'is_reversed')) { $where[] = "COALESCE(is_reversed,0)=0"; }
        if ($companyId && tableHasColumn('expenses_manual', 'company_id')) { $where[] = "(company_id = ? OR company_id IS NULL)"; $params[] = $companyId; }
        $where[] = "LOWER(TRIM(status)) IN ('pending','approved')";
        $st = $pdo->prepare("SELECT COUNT(*) AS cnt, COALESCE(SUM(amount),0) AS amt FROM expenses_manual" . (!empty($where) ? (" WHERE " . implode(" AND ", $where)) : ""));
        $st->execute($params);
        $row = $st->fetch(PDO::FETCH_ASSOC) ?: [];
        $adm_payables_outstanding_count += (int)($row['cnt'] ?? 0);
        $adm_payables_outstanding += (float)($row['amt'] ?? 0);
    }
} catch (Throwable $e) {}
try {
    $params = [];
    $where = [];
    $amtCol = null;
    if ($pdo->query("SHOW TABLES LIKE 'expenses'")->rowCount() > 0 && function_exists('tableHasColumn') && tableHasColumn('expenses', 'status')) {
        if (tableHasColumn('expenses', 'amount')) { $amtCol = 'amount'; }
        elseif (tableHasColumn('expenses', 'cost')) { $amtCol = 'cost'; }
        elseif (tableHasColumn('expenses', 'total_amount')) { $amtCol = 'total_amount'; }
        if ($amtCol) {
            if ($companyId && tableHasColumn('expenses', 'company_id')) { $where[] = "(company_id = ? OR company_id IS NULL)"; $params[] = $companyId; }
            $where[] = "LOWER(TRIM(status)) IN ('pending','approved')";
            $st = $pdo->prepare("SELECT COUNT(*) AS cnt, COALESCE(SUM($amtCol),0) AS amt FROM expenses" . (!empty($where) ? (" WHERE " . implode(" AND ", $where)) : ""));
            $st->execute($params);
            $row = $st->fetch(PDO::FETCH_ASSOC) ?: [];
            $adm_payables_outstanding_count += (int)($row['cnt'] ?? 0);
            $adm_payables_outstanding += (float)($row['amt'] ?? 0);
        }
    }
} catch (Throwable $e) {}


// --- CENTRAL PANELS DATA ---

// Recent Payments
$recent_payments = [];
try {
    $recent_payments_stmt = $pdo->prepare("
        SELECT p.*, u.name as client_name 
        FROM payments p 
        JOIN users u ON p.user_id = u.id 
        ORDER BY p.id DESC LIMIT 5
    ");
    $recent_payments_stmt->execute();
    $recent_payments = $recent_payments_stmt->fetchAll();
} catch (Exception $e) { $recent_payments = []; }

$recent_transfers = [];
try {
    $hasTransfersTbl = $pdo->query("SHOW TABLES LIKE 'ownership_transfers'")->rowCount() > 0;
    if ($hasTransfersTbl) {
        $whereT = [];
        $paramsT = [];
        if ($companyId && function_exists('tableHasColumn') && tableHasColumn('ownership_transfers', 'company_id')) {
            $whereT[] = "(t.company_id = ? OR t.company_id IS NULL OR t.company_id = 0)";
            $paramsT[] = $companyId;
        }
        $sqlT = "SELECT t.id, t.status, t.created_at, t.approved_at, t.sale_price, t.reallocation_fee, t.admin_fee,
                        t.property_id, t.seller_id, t.buyer_id, t.allocation_id, t.new_allocation_id,
                        us.name AS seller_name, ub.name AS buyer_name, p.title AS property_title
                 FROM ownership_transfers t
                 LEFT JOIN users us ON t.seller_id = us.id
                 LEFT JOIN users ub ON t.buyer_id = ub.id
                 LEFT JOIN properties p ON t.property_id = p.id";
        if (!empty($whereT)) { $sqlT .= " WHERE " . implode(" AND ", $whereT); }
        $sqlT .= " ORDER BY t.id DESC LIMIT 5";
        $stT = $pdo->prepare($sqlT);
        $stT->execute($paramsT);
        $recent_transfers = $stT->fetchAll(PDO::FETCH_ASSOC) ?: [];
    }
} catch (Throwable $e) { $recent_transfers = []; }

// Admin view: recent clients with counts
$admin_clients_recent = [];
try {
    $phoneSel = (function_exists('tableHasColumn') && tableHasColumn('users','phone')) ? "u.phone" : "NULL";
    $approvedStatuses = function_exists('kpiSqlList') ? kpiSqlList(kpiPaymentFinalizedStatuses()) : "('verified','approved','paid','completed','success')";
    $sqlc = "
        SELECT u.id, u.name, u.email, {$phoneSel} AS phone, u.created_at,
               (SELECT COUNT(*) FROM allocations a2 WHERE a2.user_id = u.id" . ($companyId && function_exists('tableHasColumn') && tableHasColumn('allocations','company_id') ? " AND a2.company_id = " . (int)$companyId : "") . ") as property_count,
               (SELECT COALESCE(SUM(p.amount), 0) FROM payments p JOIN allocations a ON p.allocation_id = a.id WHERE a.user_id = u.id" . ($companyId && function_exists('tableHasColumn') && tableHasColumn('allocations','company_id') ? " AND a.company_id = " . (int)$companyId : "") . " AND p.status IN $approvedStatuses) as total_paid,
               (SELECT a.id FROM allocations a WHERE a.user_id = u.id" . ($companyId && function_exists('tableHasColumn') && tableHasColumn('allocations','company_id') ? " AND a.company_id = " . (int)$companyId : "") . " ORDER BY a.created_at DESC LIMIT 1) as latest_allocation_id
        FROM users u
        WHERE u.role = 'client' " . ($companyId && function_exists('tableHasColumn') && tableHasColumn('users','company_id') ? " AND u.company_id = " . (int)$companyId : "") . "
        ORDER BY u.created_at DESC
        LIMIT 10
    ";
    $stc = $pdo->prepare($sqlc);
    $stc->execute();
    $admin_clients_recent = $stc->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) { $admin_clients_recent = []; }

// Admin view: payments ledger read-only
$admin_payments_recent = [];
try {
    $sqlp = "SELECT p.id, p.amount, p.status, p.method, p.created_at, p.transaction_id, u.name AS client_name
             FROM payments p
             LEFT JOIN users u ON p.user_id = u.id
             WHERE 1=1";
    $paramsp = [];
    if ($companyId && function_exists('tableHasColumn') && tableHasColumn('payments','company_id')) {
        $sqlp .= " AND p.company_id = ?";
        $paramsp[] = $companyId;
    }
    $sqlp .= " ORDER BY p.id DESC LIMIT 20";
    $stp = $pdo->prepare($sqlp);
    $stp->execute($paramsp);
    $admin_payments_recent = $stp->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) { $admin_payments_recent = []; }
// Recent Deals (Quick Access)
$recent_deals = [];
try {
    $sqlDeals = "SELECT id, client_name, amount_offered, created_at FROM deals_submit";
    $paramsDeals = [];
    if ($companyId && function_exists('tableHasColumn') && tableHasColumn('deals_submit','company_id')) {
        $sqlDeals .= " WHERE company_id = ?";
        $paramsDeals[] = $companyId;
    }
    $sqlDeals .= " ORDER BY created_at DESC LIMIT 5";
    $stDeals = $pdo->prepare($sqlDeals);
    $stDeals->execute($paramsDeals);
    $recent_deals = $stDeals->fetchAll(PDO::FETCH_ASSOC) ?: [];
} catch (Exception $e) { $recent_deals = []; }
// Payment Lifecycle Counts
$pay_pending_count = 0; $pay_verified_count = 0; $pay_failed_count = 0;
try { $pay_pending_count = function_exists('kpiCountPayments') ? kpiCountPayments($pdo, kpiPaymentPendingStatuses(), $companyId) : 0; } catch (Exception $e) {}
try { $pay_verified_count = function_exists('kpiCountPayments') ? kpiCountPayments($pdo, kpiPaymentFinalizedStatuses(), $companyId) : 0; } catch (Exception $e) {}
try { $pay_failed_count   = (int)$pdo->query("SELECT COUNT(*) FROM payments WHERE status IN ('failed','rejected')")->fetchColumn(); } catch (Exception $e) {}

// Allocation Lifecycle Counts
$alloc_pending_count = 0; 
$alloc_approved_count = 0; 
$alloc_active_count = 0;
$alloc_completed_count = 0;
$alloc_rejected_count = 0;
$alloc_allocated_count = 0; 
$alloc_revoked_count = 0;
try {
    $allocCountsKey = 'dash_alloc_counts:' . (int)$companyId . ':' . ($includeNullCompanyScope ? '1' : '0');
    $allocStatusCounts = dashCacheGet($allocCountsKey, $dashAllocTtl);
    if (!is_array($allocStatusCounts)) {
        $allocStatusCounts = function_exists('kpiAllocationStatusCounts')
            ? kpiAllocationStatusCounts($pdo, $companyId, $includeNullCompanyScope, ['pending', 'approved', 'active', 'completed', 'rejected', 'revoked'])
            : [];
        dashCacheSet($allocCountsKey, $allocStatusCounts);
    }
    $alloc_pending_count = (int)($allocStatusCounts['pending'] ?? 0);
    $alloc_approved_count = (int)($allocStatusCounts['approved'] ?? 0);
    $alloc_active_count = (int)($allocStatusCounts['active'] ?? 0);
    $alloc_completed_count = (int)($allocStatusCounts['completed'] ?? 0);
    $alloc_rejected_count = (int)($allocStatusCounts['rejected'] ?? 0);
    $alloc_revoked_count = (int)($allocStatusCounts['revoked'] ?? 0);
    $alloc_allocated_count = $alloc_active_count;
} catch (Exception $e) {}

$pending_allocations_list = [];

// Monthly Revenue Chart Data
$chart_labels = json_encode(['Jan','Feb','Mar','Apr','May','Jun']);
$chart_values = json_encode([0,0,0,0,0,0]);
try {
    $dateCol = function_exists('kpiPaymentDateColumn') ? kpiPaymentDateColumn('payments') : 'created_at';
    $approvedStatuses = function_exists('kpiSqlList') ? kpiSqlList(kpiPaymentFinalizedStatuses()) : "('verified','approved','paid','completed','success')";
    [$companyClause, $companyParams] = function_exists('kpiCompanyFilter') ? kpiCompanyFilter('payments', $companyId, true) : ['', []];
    $monthly_rev_stmt = $pdo->prepare("
        SELECT DATE_FORMAT($dateCol, '%b') as month, COALESCE(SUM(amount),0) as total 
        FROM payments 
        WHERE status IN $approvedStatuses AND $dateCol >= DATE_SUB(NOW(), INTERVAL 6 MONTH)" . $companyClause . "
        GROUP BY YEAR($dateCol), MONTH($dateCol), DATE_FORMAT($dateCol, '%b')
        ORDER BY YEAR($dateCol) ASC, MONTH($dateCol) ASC
    ");
    $monthly_rev_stmt->execute($companyParams);
    $revenue_data = $monthly_rev_stmt->fetchAll(PDO::FETCH_KEY_PAIR);
    if (!empty($revenue_data)) {
        $chart_labels = json_encode(array_values(array_keys($revenue_data)));
        $chart_values = json_encode(array_map('floatval', array_values($revenue_data)));
    }
} catch (Exception $e) {}

$recent_security = [];
try {
    $act = ['Payment Approved','Payment Final Approval','Payment Stage1 Approved','Payment Rejected','Payment Flagged','Transaction Reversal Requested','Transaction Dispute Flagged'];
    $pl = rtrim(str_repeat('?,', count($act)), ',');
    $sql = "SELECT l.*, u.name FROM audit_logs l LEFT JOIN users u ON l.user_id = u.id WHERE l.action IN ($pl) ORDER BY l.created_at DESC LIMIT 8";
    $st = $pdo->prepare($sql); $st->execute($act); $recent_security = $st->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {}
$admin_pending_list = [];
try {
    $admPendKey = 'dash_admin_pending_list:' . (int)$companyId;
    $admin_pending_list = dashCacheGet($admPendKey, $dashAllocTtl);
    if (!is_array($admin_pending_list)) {
        $whereParts = ["a.status = 'pending'"];
        if (function_exists('tableHasColumn') && tableHasColumn('allocations','workflow_stage')) { $whereParts[] = "a.workflow_stage = 'admin'"; }
        elseif (function_exists('tableHasColumn') && tableHasColumn('allocations','stage')) { $whereParts[] = "a.stage = 'admin'"; }
        elseif (function_exists('tableHasColumn') && tableHasColumn('allocations','forwarded_to_admin')) { $whereParts[] = "a.forwarded_to_admin = 1"; }
        $params = [];
        if ($companyId && function_exists('tableHasColumn') && tableHasColumn('allocations','company_id')) { $whereParts[] = "a.company_id = ?"; $params[] = (int)$companyId; }
        $sql = "SELECT a.id, a.user_id, a.property_id, a.created_at, u.name as client_name, p.title as property_name
                FROM allocations a
                JOIN users u ON a.user_id = u.id
                JOIN properties p ON a.property_id = p.id
                WHERE " . implode(' AND ', $whereParts) . "
                ORDER BY a.created_at DESC
                LIMIT 8";
        $st = $pdo->prepare($sql);
        $st->execute($params);
        $admin_pending_list = $st->fetchAll(PDO::FETCH_ASSOC) ?: [];
        dashCacheSet($admPendKey, $admin_pending_list);
    }
} catch (Exception $e) {}
$admin_pending_avatar_map = [];
try {
    $uids = [];
    foreach ($admin_pending_list as $r) { $uids[] = (int)($r['user_id'] ?? 0); }
    $uids = array_values(array_unique(array_filter($uids, fn($v) => $v > 0)));
    if (!empty($uids)) {
        $base = function_exists('buildAbsBaseUrl') ? buildAbsBaseUrl() : '';
        $avatarCol = null;
        if (function_exists('tableHasColumn')) {
            if (tableHasColumn('users','avatar_path')) $avatarCol = 'avatar_path';
            elseif (tableHasColumn('users','avatar')) $avatarCol = 'avatar';
            elseif (tableHasColumn('users','profile_photo')) $avatarCol = 'profile_photo';
            elseif (tableHasColumn('users','photo')) $avatarCol = 'photo';
            elseif (tableHasColumn('users','picture')) $avatarCol = 'picture';
            elseif (tableHasColumn('users','image_path')) $avatarCol = 'image_path';
        }
        $ph = implode(',', array_fill(0, count($uids), '?'));
        if ($avatarCol) {
            $st = $pdo->prepare("SELECT id, $avatarCol AS avatar FROM users WHERE id IN ($ph)");
            $st->execute($uids);
            while ($row = $st->fetch(PDO::FETCH_ASSOC)) {
                $id = (int)($row['id'] ?? 0);
                $p = (string)($row['avatar'] ?? '');
                if ($id > 0 && $p !== '') {
                    $admin_pending_avatar_map[$id] = function_exists('normalizeUrlPath') ? normalizeUrlPath($p, $base) : $p;
                }
            }
        }
        $missing = array_values(array_diff($uids, array_keys($admin_pending_avatar_map)));
        if (!empty($missing)) {
            $ph2 = implode(',', array_fill(0, count($missing), '?'));
            try {
                $st = $pdo->prepare("SELECT client_id, form_data FROM client_forms WHERE client_id IN ($ph2) ORDER BY updated_at DESC, created_at DESC");
                $st->execute($missing);
                while ($row = $st->fetch(PDO::FETCH_ASSOC)) {
                    $cid = (int)($row['client_id'] ?? 0);
                    if ($cid <= 0 || isset($admin_pending_avatar_map[$cid])) continue;
                    $fd = $row['form_data'] ?? '';
                    if (!$fd) continue;
                    $d = json_decode((string)$fd, true);
                    if (is_array($d) && !empty($d['passport_photo_path']) && is_scalar($d['passport_photo_path'])) {
                        $admin_pending_avatar_map[$cid] = function_exists('normalizeUrlPath') ? normalizeUrlPath((string)$d['passport_photo_path'], $base) : (string)$d['passport_photo_path'];
                    }
                }
            } catch (Throwable $e) {}
        }
        $missing = array_values(array_diff($uids, array_keys($admin_pending_avatar_map)));
        if (!empty($missing)) {
            $ph3 = implode(',', array_fill(0, count($missing), '?'));
            try {
                $st = $pdo->prepare("SELECT user_id, file_path FROM documents WHERE user_id IN ($ph3) AND type IN ('passport','photo','profile','profile_photo','id_photo') ORDER BY created_at DESC");
                $st->execute($missing);
                while ($row = $st->fetch(PDO::FETCH_ASSOC)) {
                    $uid = (int)($row['user_id'] ?? 0);
                    if ($uid <= 0 || isset($admin_pending_avatar_map[$uid])) continue;
                    $p = (string)($row['file_path'] ?? '');
                    if ($p !== '') { $admin_pending_avatar_map[$uid] = function_exists('normalizeUrlPath') ? normalizeUrlPath($p, $base) : $p; }
                }
            } catch (Throwable $e) {}
        }
    }
} catch (Throwable $e) {}
$allocation_letter_workflow = [];
try {
    $wfKey = 'dash_alloc_letter_wf:' . (int)$companyId;
    $allocation_letter_workflow = dashCacheGet($wfKey, $dashAllocTtl);
    if (!is_array($allocation_letter_workflow)) { $allocation_letter_workflow = []; }
    if (empty($allocation_letter_workflow)) {
        $sql = "SELECT a.id, a.user_id, a.property_id, a.status, a.created_at, u.name AS client_name, p.title AS property_name
            FROM allocations a
            LEFT JOIN users u ON a.user_id = u.id
            LEFT JOIN properties p ON a.property_id = p.id
            WHERE a.status IN ('approved','pending_executive_approval','executive_approved','completed')";
        $params = [];
        if ($companyId && function_exists('tableHasColumn') && tableHasColumn('allocations','company_id')) {
            $sql .= " AND a.company_id = ? ";
            $params[] = $companyId;
        }
        $sql .= " ORDER BY a.created_at DESC LIMIT 8";
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $allocation_letter_workflow = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
        dashCacheSet($wfKey, $allocation_letter_workflow);
    }
} catch (Exception $e) {}

?>

<style>
.dashboard-premium {
    --card-radius: 16px;
    --card-pad: 22px;
    --bg-soft: #f5f7fb;
    --text-muted: #6b7280;
    --shadow-soft: 0 8px 24px rgba(0,0,0,0.06);
    font-family: "Inter","Poppins", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
    background: var(--bg-soft);
}
.dashboard-premium .card { border: 0; border-radius: var(--card-radius); box-shadow: var(--shadow-soft); }
.dashboard-premium .metric-card { padding: var(--card-pad); }
.dashboard-premium .metric-label { color: var(--text-muted); font-size: 0.85rem; }
.dashboard-premium .metric-value { font-weight: 800; font-size: 2.1rem; line-height: 1.1; }
.dashboard-premium .metric-icon { width:44px; height:44px; border-radius:12px; display:flex; align-items:center; justify-content:center; font-size:1.1rem; }
.dashboard-premium .stat-gradient { background: linear-gradient(135deg, #ff6b5f 0%, #ff8a5b 100%) !important; color:#fff; }
.dashboard-premium .stat-gradient .metric-label, 
.dashboard-premium .stat-gradient .metric-trend { color: rgba(255,255,255,0.85); }
.dashboard-premium .scroll-panel { max-height: 360px; overflow-y: auto; }
.dashboard-premium .avatar-ring { width:36px; height:36px; border-radius:50%; display:flex; align-items:center; justify-content:center; font-weight:600; background:#eef2ff; color:#1f3a8a; }
.dashboard-premium .review-item + .review-item { border-top:1px solid #f0f2f6; }
.dashboard-premium .progress-h { width:100%; height:8px; background:#eef2f7; border-radius:10px; overflow:hidden; }
.dashboard-premium .progress-h > span { display:block; height:100%; border-radius:10px; background: linear-gradient(90deg, var(--primary), var(--primary-light)); }
.dashboard-premium .adm-table-scroll{display:block;width:100%;max-width:100%;overflow:auto !important;overflow-x:auto !important;overflow-y:hidden;-webkit-overflow-scrolling:touch;touch-action:pan-x pan-y;cursor:grab}
.dashboard-premium .adm-table-scroll.adm-grabbing{cursor:grabbing}
.dashboard-premium .table-responsive.adm-table-scroll{overflow:auto !important;overflow-x:auto !important;overflow-y:hidden}
.dashboard-premium .adm-table-wide{width:max-content;min-width:760px}
.dashboard-premium .adm-table-wide th,.dashboard-premium .adm-table-wide td{white-space:nowrap;vertical-align:middle}
.dashboard-premium .adm-table-wide td.adm-primary{white-space:normal;min-width:220px}
</style>

<div class="container-fluid px-4 py-4 dashboard-premium">
    
    <!-- PAGE HEADER -->
    <div class="d-flex justify-content-between align-items-center mb-5">
        <div>
            <h1 class="h3 fw-bold text-dark mb-1">Executive Dashboard</h1>
            <?php 
                $welcome = getSetting('welcome_message', '');
                if (!empty($welcome)) {
                    echo '<p class="text-white mb-0">' . htmlspecialchars($welcome) . '</p>';
                } else {
                    echo '<p class="text-white mb-0">Overview of ' . htmlspecialchars(getSetting('company_name', 'Aiben Property')) . ' performance & daily activities.</p>';
                }
            ?>
        </div>
        <div class="d-flex gap-3">
            <button class="btn btn-white border shadow-sm text-dark">
                <i class="fa-solid fa-calendar me-2"></i> <?= date('F d, Y') ?>
            </button>
            <a href="allocations.php?status=admin_pending" class="btn btn-outline-dark shadow-sm">
                <i class="fa-solid fa-user-shield me-2"></i> Review Admin Pending
            </a>
            <a href="allocation-letters.php" class="btn btn-outline-dark shadow-sm">
                <i class="fa-solid fa-file-signature me-2"></i> Allocation Letters
            </a>
            <a href="allocation-add.php" class="btn btn-primary-custom shadow-sm">
    <i class="fa-solid fa-plus me-2"></i> New Allocation
</a>
        </div>
    </div>

    <div class="card mb-4">
        <div class="card-header bg-white border-bottom py-3 d-flex justify-content-between align-items-center">
            <h6 class="mb-0 fw-bold">Recent Onboarding Forms</h6>
            <div class="d-flex gap-2">
                <a href="clients.php" class="btn btn-outline-secondary btn-sm">Open Clients</a>
            </div>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead class="table-light">
                        <tr>
                            <th>Client</th>
                            <th>Status</th>
                            <th class="text-end">Fee</th>
                            <th>Receipt</th>
                            <th>Submitted</th>
                            <th class="text-end">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        try {
                            $rows = [];
                            $q = "SELECT cf.id, cf.client_id, cf.status, cf.amount_due, cf.receipt_path, cf.created_at, u.name AS client_name
                                  FROM client_forms cf
                                  JOIN users u ON cf.client_id = u.id
                                  ORDER BY cf.created_at DESC
                                  LIMIT 8";
                            $st = $pdo->query($q);
                            if ($st) { $rows = $st->fetchAll(PDO::FETCH_ASSOC); }
                        } catch (Exception $e) { $rows = []; }
                        if (empty($rows)): ?>
                            <tr><td colspan="6" class="text-center py-4">No onboarding submissions</td></tr>
                        <?php else:
                            foreach ($rows as $r): ?>
                            <tr>
                                <td class="fw-600">
                                    <a href="clients.php?open_client_id=<?= (int)$r['client_id'] ?>" class="text-decoration-none">
                                        <?= htmlspecialchars($r['client_name'] ?? 'Client') ?>
                                    </a>
                                </td>
                                <td><span class="badge <?= getStatusBadgeClass($r['status'] ?? '') ?>"><?= ucfirst($r['status'] ?? '') ?></span></td>
                                <td class="text-end"><?= formatCurrency((float)($r['amount_due'] ?? 0)) ?></td>
                                <td>
                                    <?php if (!empty($r['receipt_path'])): ?>
                                        <a target="_blank" href="<?= htmlspecialchars($r['receipt_path']) ?>">View</a>
                                    <?php else: ?>
                                        <span class="text-muted">-</span>
                                    <?php endif; ?>
                                </td>
                                <td class="text-muted"><?= htmlspecialchars(date('M j, Y', strtotime($r['created_at']))) ?></td>
                                <td class="text-end">
                                    <a class="btn btn-sm btn-primary" href="allocation-add.php?client_id=<?= (int)$r['client_id'] ?>">
                                        Start Allocation
                                    </a>
                                </td>
                            </tr>
                        <?php endforeach; endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <script>
    (function(){
        var el = document.querySelector('.adm-table-scroll');
        if (!el) return;
        var isDown = false;
        var startX = 0;
        var scrollLeft = 0;
        el.addEventListener('mousedown', function(e){
            if (e.button !== 0) return;
            if (e.target && e.target.closest('a,button,input,select,textarea,label,.dropdown-menu')) return;
            isDown = true;
            el.classList.add('adm-grabbing');
            startX = e.pageX;
            scrollLeft = el.scrollLeft;
        });
        document.addEventListener('mouseup', function(){
            if (!isDown) return;
            isDown = false;
            el.classList.remove('adm-grabbing');
        });
        document.addEventListener('mousemove', function(e){
            if (!isDown) return;
            var walk = (e.pageX - startX);
            el.scrollLeft = scrollLeft - walk;
        });
    })();
    </script>

    <div class="card mb-4">
        <div class="card-header bg-white border-bottom py-3 d-flex justify-content-between align-items-center">
            <h6 class="mb-0 fw-bold">Registered Clients</h6>
            <div class="d-flex gap-2">
                <a href="allocation-add.php" class="btn btn-primary btn-sm"><i class="fa-solid fa-plus me-1"></i>Start Allocation</a>
                <a href="clients.php" class="btn btn-outline-secondary btn-sm">Open Clients</a>
            </div>
        </div>
        <div class="card-body p-0">
            <div class="d-sm-none px-3 py-2 small text-muted border-bottom">Swipe left/right to see all columns.</div>
            <div class="table-responsive adm-table-scroll">
                <table class="table table-hover mb-0 adm-table-wide">
                    <thead class="table-light">
                        <tr>
                            <th>Client</th>
                            <th class="d-none d-md-table-cell">Email</th>
                            <th class="d-none d-lg-table-cell">Phone</th>
                            <th class="text-end">Paid</th>
                            <th class="d-none d-md-table-cell">Properties</th>
                            <th class="d-none d-lg-table-cell">Registered</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($admin_clients_recent)): ?>
                        <tr><td colspan="6" class="text-center py-4">No clients found</td></tr>
                        <?php else: foreach ($admin_clients_recent as $c): ?>
                        <tr>
                            <?php
                                $cName = (string)($c['name'] ?? '');
                                $cEmail = (string)($c['email'] ?? '');
                                $cPhone = (string)($c['phone'] ?? '');
                                $cReg = !empty($c['created_at']) ? date('M j, Y', strtotime((string)$c['created_at'])) : '';
                                $cProps = (int)($c['property_count'] ?? 0);
                            ?>
                            <td class="fw-600 adm-primary">
                                <a href="clients.php?open_client_id=<?= (int)$c['id'] ?>" class="text-decoration-none">
                                    <?= htmlspecialchars($cName) ?>
                                </a>
                                <div class="text-muted small d-md-none mt-1">
                                    <?= htmlspecialchars($cEmail) ?>
                                    <?= ($cEmail !== '' && $cPhone !== '') ? ' · ' : '' ?>
                                    <?= htmlspecialchars($cPhone) ?>
                                </div>
                                <div class="text-muted small d-md-none">
                                    <?= $cReg !== '' ? htmlspecialchars($cReg) : '' ?>
                                    <?= ($cReg !== '') ? ' · ' : '' ?>
                                    <?= $cProps ?> properties
                                </div>
                            </td>
                            <td class="text-muted d-none d-md-table-cell"><?= htmlspecialchars($cEmail) ?></td>
                            <td class="text-muted d-none d-lg-table-cell"><?= htmlspecialchars($cPhone) ?></td>
                            <td class="text-end"><?= formatCurrency((float)($c['total_paid'] ?? 0)) ?></td>
                            <td class="d-none d-md-table-cell"><span class="badge bg-light text-dark border"><?= $cProps ?></span></td>
                            <td class="text-muted d-none d-lg-table-cell"><?= htmlspecialchars($cReg) ?></td>
                        </tr>
                        <?php endforeach; endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <div class="card mb-4">
        <div class="card-header bg-white border-bottom py-3 d-flex justify-content-between align-items-center">
            <h6 class="mb-0 fw-bold">Payments Ledger (Read-only)</h6>
            <a href="transactions.php" class="btn btn-outline-secondary btn-sm">Open Full Ledger</a>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead class="table-light">
                        <tr>
                            <th>ID</th>
                            <th>Client</th>
                            <th class="text-end">Amount</th>
                            <th>Status</th>
                            <th>Method</th>
                            <th>Created</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($admin_payments_recent)): ?>
                        <tr><td colspan="6" class="text-center py-4">No payments found</td></tr>
                        <?php else: foreach ($admin_payments_recent as $p): ?>
                        <tr>
                            <td>#<?= (int)$p['id'] ?></td>
                            <td><?= htmlspecialchars($p['client_name'] ?? 'Client') ?></td>
                            <td class="text-end"><?= formatCurrency((float)($p['amount'] ?? 0)) ?></td>
                            <td><span class="badge <?= getStatusBadgeClass($p['status']) ?>"><?= ucfirst($p['status']) ?></span></td>
                            <td class="text-muted"><?= htmlspecialchars($p['method'] ?? '-') ?></td>
                            <td class="text-muted"><?= htmlspecialchars(date('M j, Y', strtotime($p['created_at']))) ?></td>
                        </tr>
                        <?php endforeach; endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- TOP METRIC CARDS -->
    <div class="row g-4 mb-5">
        <!-- Total Sales -->
        <div class="col-xl-4 col-md-6">
            <div class="card metric-card h-100 gold-outline">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <div class="metric-label">Total Sales</div>
                        <div class="metric-value"><?= number_format($total_sales) ?></div>
                        <div class="metric-trend trend-up">
                            <i class="fa-solid fa-arrow-trend-up"></i> <span>8.5% this month</span>
                        </div>
                    </div>
                    <div class="metric-icon bg-success-soft">
                        <i class="fa-solid fa-handshake"></i>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Total Revenue -->
        <div class="col-xl-4 col-md-6">
            <div class="card metric-card h-100 gold-outline stat-gradient">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <div class="metric-label">Total Revenue</div>
                        <div class="metric-value"><?= formatCurrency($total_revenue) ?></div>
                        <div class="metric-trend trend-up">
                            <i class="fa-solid fa-arrow-trend-up"></i> <span>12% vs last month</span>
                        </div>
                        <div class="text-xs mt-1" style="opacity:.9"><?= $collection_rate ?>% collected</div>
                    </div>
                    <div class="metric-icon bg-white text-primary">
                        <i class="fa-solid fa-wallet"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Outstanding Balance -->
        <div class="col-xl-4 col-md-6">
            <div class="card metric-card h-100 gold-outline">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <div class="metric-label">Outstanding Balance</div>
                        <div class="metric-value"><?= formatCurrency($outstanding_balance) ?></div>
                        <div class="metric-trend trend-down">
                            <i class="fa-solid fa-circle-exclamation"></i> <span>Needs attention</span>
                        </div>
                        <div class="progress-premium" title="Pending vs verified">
                            <?php
                                $pending_pct = $total_collections_base > 0 ? round(($outstanding_balance / $total_collections_base) * 100) : 0;
                            ?>
                            <div class="progress-bar-premium progress-bar-warning" style="width: <?= $pending_pct ?>%;"></div>
                        </div>
                        <div class="text-xs text-muted mt-1"><?= $pending_pct ?>% pending</div>
                    </div>
                    <div class="metric-icon bg-warning-soft">
                        <i class="fa-solid fa-scale-unbalanced"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Available Units -->
        <div class="col-xl-3 col-md-6">
            <div class="card metric-card h-100 gold-outline">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <div class="metric-label">Available Units</div>
                        <div class="metric-value"><?= number_format($available_units) ?></div>
                    </div>
                    <div class="metric-icon bg-info-soft">
                        <i class="fa-solid fa-house"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Allocated Units -->
        <div class="col-xl-3 col-md-6">
            <div class="card metric-card h-100 gold-outline">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <div class="metric-label">Allocated Units</div>
                        <div class="metric-value"><?= number_format($allocated_units) ?></div>
                    </div>
                    <div class="metric-icon bg-primary-soft">
                        <i class="fa-solid fa-file-signature"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Active Clients -->
        <div class="col-xl-3 col-md-6">
            <div class="card metric-card h-100 gold-outline">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <div class="metric-label">Active Clients</div>
                        <div class="metric-value"><?= number_format($active_clients) ?></div>
                    </div>
                    <div class="metric-icon bg-danger-soft">
                        <i class="fa-solid fa-users"></i>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Quick Stats -->
         <div class="col-xl-3 col-md-6">
            <div class="card metric-card h-100 bg-primary text-white" style="background: linear-gradient(135deg, var(--primary), var(--primary-dark));">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <div class="metric-label text-white-50">System Health</div>
                        <div class="metric-value text-white">98%</div>
                        <div class="metric-trend text-white-50">
                             <span>All systems operational</span>
                        </div>
                    </div>
                    <div class="metric-icon bg-white text-primary">
                        <i class="fa-solid fa-server"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row g-3 mb-4">
        <div class="col-6 col-md-3">
            <a href="allocations.php?status=admin_pending" class="card metric-card h-100 gold-outline text-decoration-none">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <div class="metric-label">Admin-Pending Allocs</div>
                        <div class="metric-value"><?= number_format($adm_admin_pending) ?></div>
                    </div>
                    <div class="metric-icon bg-dark text-white">
                        <i class="fa-solid fa-user-shield"></i>
                    </div>
                </div>
            </a>
        </div>
        <div class="col-6 col-md-3">
            <a href="refunds.php" class="card metric-card h-100 gold-outline text-decoration-none">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <div class="metric-label">Refunds Pending</div>
                        <div class="metric-value"><?= number_format($adm_refunds_pending) ?></div>
                    </div>
                    <div class="metric-icon bg-warning-soft">
                        <i class="fa-solid fa-rotate-left"></i>
                    </div>
                </div>
            </a>
        </div>
        <div class="col-6 col-md-3">
            <a href="reports-financial.php?tab=receivables" class="card metric-card h-100 gold-outline text-decoration-none">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <div class="metric-label">Outstanding Receivables</div>
                        <div class="metric-value"><?= formatCurrency($adm_receivables) ?></div>
                    </div>
                    <div class="metric-icon bg-accent-soft">
                        <i class="fa-solid fa-file-invoice-dollar"></i>
                    </div>
                </div>
            </a>
        </div>
        <div class="col-6 col-md-3">
            <a href="ownership-transfers.php?status=pending" class="card metric-card h-100 gold-outline text-decoration-none">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <div class="metric-label">Transfers Pending</div>
                        <div class="metric-value"><?= number_format($adm_transfers_pending) ?></div>
                    </div>
                    <div class="metric-icon bg-info-soft">
                        <i class="fa-solid fa-right-left"></i>
                    </div>
                </div>
            </a>
        </div>
    </div>

    <!-- OPERATIONS OVERVIEW -->
    <div class="row g-4 mb-5">
        <div class="col-xl-4 col-md-6">
            <a href="customer-care.php?status=pending" class="card metric-card h-100 gold-outline text-decoration-none">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <div class="metric-label">Customer Care (Open/Pending)</div>
                        <div class="metric-value"><?= number_format($ops_cc_pending) ?></div>
                    </div>
                    <div class="metric-icon bg-info-soft">
                        <i class="fa-solid fa-headset"></i>
                    </div>
                </div>
            </a>
        </div>
        <div class="col-xl-4 col-md-6">
            <a href="maintenance.php?status=open" class="card metric-card h-100 gold-outline text-decoration-none">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <div class="metric-label">Maintenance (Active)</div>
                        <div class="metric-value"><?= number_format($ops_maint_pending) ?></div>
                    </div>
                    <div class="metric-icon bg-warning-soft">
                        <i class="fa-solid fa-screwdriver-wrench"></i>
                    </div>
                </div>
            </a>
        </div>
        <div class="col-xl-4 col-md-6">
            <a href="tasks.php?assigned_to=me&overdue=1" class="card metric-card h-100 gold-outline text-decoration-none">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <div class="metric-label">Tasks (Overdue)</div>
                        <div class="metric-value"><?= number_format($ops_tasks_overdue) ?></div>
                    </div>
                    <div class="metric-icon bg-danger-soft">
                        <i class="fa-solid fa-list-check"></i>
                    </div>
                </div>
            </a>
        </div>
    </div>

    <!-- CENTRAL PANELS -->
    <div class="row g-4">
        
        <!-- Left Column: Activity & Requests -->
        <div class="col-lg-8">
            
            <!-- Revenue Chart -->
            <div class="card mb-4">
                <div class="card-header bg-white border-bottom py-3 d-flex justify-content-between align-items-center">
                    <h6 class="mb-0 fw-bold">Revenue Overview</h6>
                    <button class="btn btn-sm btn-light"><i class="fa-solid fa-ellipsis"></i></button>
                </div>
                <div class="card-body">
                    <canvas id="revenueChart" height="100"></canvas>
                </div>
            </div>

            <!-- Recent Deals -->
            <div class="card mb-4">
                <div class="card-header bg-white border-bottom py-3 d-flex justify-content-between align-items-center">
                    <h6 class="mb-0 fw-bold">Recent Deals</h6>
                </div>
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0">
                        <thead>
                            <tr>
                                <th>Client</th>
                                <th class="text-end">Amount</th>
                                <th class="text-end">Balance</th>
                                <th class="text-end">Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!empty($recent_deals)): ?>
                                <?php foreach ($recent_deals as $d): ?>
                                    <?php 
                                        $dealIdX = (int)($d['id'] ?? 0); 
                                        $amt = (float)($d['amount_offered'] ?? 0); 
                                        $paid = 0.0; 
                                        if ($dealIdX > 0) { 
                                            try { 
                                                $stSum = $pdo->prepare("SELECT COALESCE(SUM(amount),0) FROM payments WHERE deal_id = ? AND status = 'approved'"); 
                                                $stSum->execute([$dealIdX]); 
                                                $paid = (float)$stSum->fetchColumn(); 
                                            } catch (Throwable $e) {} 
                                        } 
                                        $bal = max(0.0, $amt - $paid); 
                                    ?>
                                    <tr>
                                        <td><?= htmlspecialchars($d['client_name'] ?? '-') ?></td>
                                        <td class="text-end">₦<?= number_format($amt) ?></td>
                                        <td class="text-end">₦<?= number_format($bal) ?></td>
                                        <td class="text-end">
                                            <?php if ($dealIdX > 0): ?>
                                                <a href="client_ledger.php?deal_id=<?= $dealIdX ?>" class="btn btn-sm btn-outline-dark">View Ledger</a>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr><td colspan="4" class="text-muted text-center">No recent deals</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <div class="card mb-4">
                <div class="card-header bg-white border-bottom py-3 d-flex justify-content-between align-items-center">
                    <h6 class="mb-0 fw-bold">Recent Ownership Transfers</h6>
                    <a href="ownership-transfers.php" class="btn btn-sm btn-outline-dark">Open Transfers</a>
                </div>
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0">
                        <thead>
                            <tr>
                                <th>Property</th>
                                <th>Seller</th>
                                <th>Buyer</th>
                                <th>Status</th>
                                <th class="text-end">Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!empty($recent_transfers)): ?>
                                <?php foreach ($recent_transfers as $t): ?>
                                    <?php $tStatus = strtolower((string)($t['status'] ?? 'pending')); ?>
                                    <tr>
                                        <td><?= htmlspecialchars($t['property_title'] ?? ('Property #' . (int)($t['property_id'] ?? 0))) ?></td>
                                        <td><?= htmlspecialchars($t['seller_name'] ?? ('Client #' . (int)($t['seller_id'] ?? 0))) ?></td>
                                        <td><?= htmlspecialchars($t['buyer_name'] ?? ('Client #' . (int)($t['buyer_id'] ?? 0))) ?></td>
                                        <td><span class="badge <?= getStatusBadgeClass($tStatus) ?>"><?= ucfirst($tStatus) ?></span></td>
                                        <td class="text-end">
                                            <a href="ownership-transfers.php?id=<?= (int)($t['id'] ?? 0) ?>" class="btn btn-sm btn-light border">View</a>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr><td colspan="5" class="text-muted text-center">No transfers yet</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- Recent Allocation Requests -->
            <div class="card mb-4">
                <div class="card-header bg-white border-bottom py-3">
                    <h6 class="mb-0 fw-bold">Admin-Pending Allocations</h6>
                </div>
                <div class="table-responsive">
                    <table class="table-custom">
                        <thead>
                            <tr>
                                <th>Client</th>
                                <th>Property</th>
                                <th>Date</th>
                                <th>Status</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($admin_pending_list as $alloc): ?>
                            <tr>
                                <td>
                                    <div class="d-flex align-items-center gap-2">
                                        <?php $clientAvatar = $admin_pending_avatar_map[(int)($alloc['user_id'] ?? 0)] ?? ''; ?>
                                        <?php if (!empty($clientAvatar)): ?>
                                            <img src="<?= htmlspecialchars($clientAvatar) ?>" alt="<?= htmlspecialchars($alloc['client_name']) ?>" style="width:32px;height:32px;border-radius:50%;object-fit:cover;">
                                        <?php else: ?>
                                            <div class="avatar" style="width: 32px; height: 32px; font-size: 0.8rem;"><?= strtoupper(substr($alloc['client_name'], 0, 1)) ?></div>
                                        <?php endif; ?>
                                        <span class="fw-500"><?= htmlspecialchars($alloc['client_name']) ?></span>
                                    </div>
                                </td>
                                <td><?= htmlspecialchars($alloc['property_name']) ?></td>
                                <td><?= date('M d, Y', strtotime($alloc['created_at'])) ?></td>
                                <td><span class="status-badge status-badge-pending"><i class="fa-regular fa-clock"></i> Admin Review</span></td>
                                <td>
                                    <a href="allocation-details.php?id=<?= $alloc['id'] ?>" class="btn btn-sm btn-light border">View</a>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            <?php if(empty($admin_pending_list)): ?>
                            <tr>
                                <td colspan="5">
                                    <div class="empty-state-premium">
                                        <div class="empty-state-icon"><i class="fa-regular fa-clock"></i></div>
                                        <div class="empty-state-title">No admin-pending allocations</div>
                                        <div class="empty-state-desc">All allocations awaiting admin review will appear here.</div>
                                        <a href="allocations.php?status=admin_pending" class="btn btn-outline-secondary btn-sm">Open Admin Pending</a>
                                    </div>
                                </td>
                            </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <div class="card mb-4">
                <div class="card-header bg-white border-bottom py-3 d-flex justify-content-between align-items-center">
                    <div>
                        <h6 class="mb-0 fw-bold">Allocation Letter Workflow</h6>
                        <div class="text-muted small mt-1">Generate, preview, and forward allocation letters to the executive decision queue.</div>
                    </div>
                    <a href="allocation-letters.php?view=admin" class="btn btn-sm btn-outline-primary">Open Workflow</a>
                </div>
                <div class="table-responsive">
                    <table class="table-custom">
                        <thead>
                            <tr>
                                <th>Client</th>
                                <th>Property</th>
                                <th>Stage</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($allocation_letter_workflow as $letter): ?>
                            <?php
                                $letterStatus = strtolower((string)($letter['status'] ?? ''));
                                $stageLabel = 'Draft Ready';
                                $stageClass = 'status-badge-info';
                                if ($letterStatus === 'pending_executive_approval') {
                                    $stageLabel = 'Sent to Executive';
                                    $stageClass = 'status-badge-pending';
                                } elseif ($letterStatus === 'executive_approved') {
                                    $stageLabel = 'Approved';
                                    $stageClass = 'status-badge-success';
                                } elseif ($letterStatus === 'completed') {
                                    $stageLabel = 'Released to Client';
                                    $stageClass = 'status-badge-success';
                                } elseif ($letterStatus === 'approved') {
                                    $stageLabel = 'Ready for Draft';
                                    $stageClass = 'status-badge-info';
                                }
                            ?>
                            <tr>
                                <td><?= htmlspecialchars($letter['client_name'] ?? ('Client #' . (int)$letter['user_id'])) ?></td>
                                <td><?= htmlspecialchars($letter['property_name'] ?? ('Property #' . (int)$letter['property_id'])) ?></td>
                                <td><span class="status-badge <?= $stageClass ?>"><i class="fa-solid fa-file-signature"></i> <?= htmlspecialchars($stageLabel) ?></span></td>
                                <td>
                                    <div class="d-flex flex-wrap gap-2">
                                        <a href="allocation-letters.php?view=admin&amp;action=preview&amp;allocation_id=<?= (int)$letter['id'] ?>" target="_blank" class="btn btn-sm btn-light border">Preview</a>
                                        <?php if ($letterStatus === 'approved'): ?>
                                            <form action="generate_document.php" method="POST" target="_blank" class="d-inline">
                                                <input type="hidden" name="doc_type" value="allocation_letter">
                                                <input type="hidden" name="target_id" value="<?= (int)$letter['id'] ?>">
                                                <button type="submit" class="btn btn-sm btn-outline-secondary">Generate</button>
                                            </form>
                                            <form action="allocation-letters.php" method="POST" class="d-inline" onsubmit="return confirm('Send this allocation letter to the executive dashboard for approval?');">
                                                <input type="hidden" name="form_action" value="send_for_approval">
                                                <input type="hidden" name="view" value="admin">
                                                <input type="hidden" name="allocation_id" value="<?= (int)$letter['id'] ?>">
                                                <button type="submit" class="btn btn-sm btn-primary-custom">Send to Executive</button>
                                            </form>
                                        <?php elseif ($letterStatus === 'pending_executive_approval'): ?>
                                            <span class="btn btn-sm btn-outline-warning disabled">Awaiting Executive Review</span>
                                        <?php elseif ($letterStatus === 'executive_approved'): ?>
                                            <form action="allocation-letters.php" method="POST" class="d-inline" onsubmit="return confirm('Send this approved allocation letter to the client dashboard?');">
                                                <input type="hidden" name="form_action" value="release_to_client">
                                                <input type="hidden" name="view" value="admin">
                                                <input type="hidden" name="allocation_id" value="<?= (int)$letter['id'] ?>">
                                                <button type="submit" class="btn btn-sm btn-success">Send to Client</button>
                                            </form>
                                        <?php elseif ($letterStatus === 'completed'): ?>
                                            <span class="btn btn-sm btn-outline-success disabled">Released to Client</span>
                                        <?php else: ?>
                                            <span class="btn btn-sm btn-outline-success disabled">Chairman Decision Completed</span>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            <?php if (empty($allocation_letter_workflow)): ?>
                            <tr>
                                <td colspan="4">
                                    <div class="empty-state-premium">
                                        <div class="empty-state-icon"><i class="fa-solid fa-file-signature"></i></div>
                                        <div class="empty-state-title">No allocation letters in workflow</div>
                                        <div class="empty-state-desc">Approved allocations will appear here for draft generation and executive approval routing.</div>
                                        <a href="allocation-letters.php?view=admin" class="btn btn-outline-secondary btn-sm">Open Allocation Letters</a>
                                    </div>
                                </td>
                            </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- Allocation Lifecycle -->
            <div class="card mb-4">
                <div class="card-header bg-white border-bottom py-3 d-flex justify-content-between align-items-center">
                    <h6 class="mb-0 fw-bold">Allocation Lifecycle</h6>
                    <span class="badge badge-primary text-uppercase">Live</span>
                </div>
                <div class="card-body">
                    <div class="d-flex align-items-center justify-content-between flex-wrap gap-2">
                        <div class="chip chip-warning"><i class="fa-regular fa-clock"></i> Pending <span class="badge badge-warning ms-2"><?= number_format($alloc_pending_count) ?></span></div>
                        <div class="chip chip-info"><i class="fa-solid fa-stamp"></i> Approved <span class="badge badge-info ms-2"><?= number_format($alloc_approved_count) ?></span></div>
                        <div class="chip chip-primary"><i class="fa-solid fa-file-signature"></i> Active <span class="badge badge-primary ms-2"><?= number_format($alloc_active_count) ?></span></div>
                        <div class="chip chip-success"><i class="fa-solid fa-check-double"></i> Completed <span class="badge badge-success ms-2"><?= number_format($alloc_completed_count) ?></span></div>
                        <div class="chip chip-danger"><i class="fa-solid fa-ban"></i> Rejected <span class="badge badge-danger ms-2"><?= number_format($alloc_rejected_count) ?></span></div>
                    </div>
                    <?php
                        $total_alloc_count = max(1, $alloc_pending_count + $alloc_approved_count + $alloc_active_count + $alloc_completed_count + $alloc_rejected_count);
                        $pct_alloc_pending   = round(($alloc_pending_count / $total_alloc_count) * 100);
                        $pct_alloc_approved  = round(($alloc_approved_count / $total_alloc_count) * 100);
                        $pct_alloc_active    = round(($alloc_active_count / $total_alloc_count) * 100);
                        $pct_alloc_completed = round(($alloc_completed_count / $total_alloc_count) * 100);
                        $pct_alloc_rejected  = round(($alloc_rejected_count / $total_alloc_count) * 100);
                    ?>
                    <div class="progress-premium mt-3">
                        <div class="progress-bar-premium progress-bar-warning" style="width: <?= $pct_alloc_pending ?>%;"></div>
                    </div>
                    <div class="progress-premium mt-2">
                        <div class="progress-bar-premium progress-bar-info" style="width: <?= $pct_alloc_approved ?>%;"></div>
                    </div>
                    <div class="progress-premium mt-2">
                        <div class="progress-bar-premium" style="background: linear-gradient(90deg, var(--primary), var(--primary-light)); width: <?= $pct_alloc_active ?>%;"></div>
                    </div>
                    <div class="progress-premium mt-2">
                        <div class="progress-bar-premium progress-bar-success" style="width: <?= $pct_alloc_completed ?>%;"></div>
                    </div>
                    <div class="progress-premium mt-2">
                        <div class="progress-bar-premium progress-bar-danger" style="width: <?= $pct_alloc_rejected ?>%;"></div>
                    </div>
                    <div class="text-xs text-muted mt-2">Distribution by status · allocations</div>
                </div>
            </div>
        </div>

        <!-- Right Column: Donut + Reviews + Payments & Tasks -->
        <div class="col-lg-4">
            <!-- Donut / Pie -->
            <div class="card mb-4">
                <div class="card-header bg-white border-bottom py-3 d-flex justify-content-between align-items-center">
                    <h6 class="mb-0 fw-bold">Allocations Mix</h6>
                </div>
                <div class="card-body">
                    <canvas id="allocDonut" height="220"></canvas>
                </div>
            </div>
            <!-- Reviews -->
            <?php 
                $ui_reviews = [
                    ['name'=>'John Doe','rating'=>5,'time'=>'5m','text'=>'Excellent support during allocation process.'],
                    ['name'=>'Amelia Turner','rating'=>4,'time'=>'10h','text'=>'Professional and helpful team.'],
                    ['name'=>'Jessica Humb','rating'=>5,'time'=>'2d','text'=>'Smooth experience from viewing to paperwork.'],
                ];
            ?>
            <div class="card mb-4">
                <div class="card-header bg-white border-bottom py-3 d-flex justify-content-between align-items-center">
                    <h6 class="mb-0 fw-bold">Customer Reviews</h6>
                </div>
                <div class="card-body p-0 scroll-panel">
                    <?php foreach($ui_reviews as $r): ?>
                    <div class="p-3 review-item d-flex gap-3 align-items-start">
                        <div class="avatar-ring"><?= strtoupper(substr($r['name'],0,1)) ?></div>
                        <div class="flex-grow-1">
                            <div class="d-flex justify-content-between align-items-center">
                                <div class="fw-600"><?= htmlspecialchars($r['name']) ?></div>
                                <small class="text-muted"><?= htmlspecialchars($r['time']) ?></small>
                            </div>
                            <div class="text-warning mb-1">
                                <?php for($i=0;$i<5;$i++): ?>
                                    <i class="fa-star <?= $i < $r['rating'] ? 'fa-solid' : 'fa-regular' ?>"></i>
                                <?php endfor; ?>
                            </div>
                            <div class="text-sm text-muted"><?= htmlspecialchars($r['text']) ?></div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <div class="card mb-4">
                <div class="card-header bg-white border-bottom py-3 d-flex justify-content-between align-items-center">
                    <h6 class="mb-0 fw-bold">Security Events</h6>
                    <a href="logs.php" class="btn btn-sm btn-outline-dark">Open Logs</a>
                </div>
                <div class="card-body p-0">
                    <?php foreach ($recent_security as $log): ?>
                    <div class="p-3 border-bottom d-flex justify-content-between align-items-center">
                        <div>
                            <div class="fw-600 text-sm"><?= htmlspecialchars($log['action']) ?></div>
                            <div class="text-xs text-muted"><?= htmlspecialchars($log['name'] ?? 'System') ?> • <?= date('M d, h:i A', strtotime($log['created_at'])) ?></div>
                        </div>
                        <div class="text-end">
                            <div class="text-xs text-muted" style="font-family:monospace"><?= htmlspecialchars($log['ip_address'] ?? '') ?></div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                    <?php if (empty($recent_security)): ?>
                    <div class="p-4">
                        <div class="empty-state-premium">
                            <div class="empty-state-icon"><i class="fa-regular fa-bell"></i></div>
                            <div class="empty-state-title">No recent security events</div>
                            <div class="empty-state-desc">Approvals, rejections, and flags will appear here.</div>
                            <a href="logs.php" class="btn btn-outline-secondary btn-sm">Open Audit Logs</a>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
            <div class="card mb-4">
                <div class="card-header bg-white border-bottom py-3 d-flex justify-content-between align-items-center">
                    <h6 class="mb-0 fw-bold">Finance Snapshot</h6>
                    <a href="finance-dashboard.php" class="btn btn-sm btn-outline-dark">Open Finance</a>
                </div>
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <a class="text-decoration-none text-muted small" href="receivables.php">Receivables</a>
                        <a class="text-decoration-none fw-bold" href="receivables.php"><?= formatCurrency($adm_receivables) ?></a>
                    </div>
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <a class="text-decoration-none text-muted small" href="payables.php">Payables (Open)</a>
                        <a class="text-decoration-none fw-bold" href="payables.php"><?= formatCurrency($adm_payables_outstanding) ?></a>
                    </div>
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <div class="text-muted small">Payables (Items)</div>
                        <div class="fw-bold"><?= number_format((int)$adm_payables_outstanding_count) ?></div>
                    </div>
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <a class="text-decoration-none text-muted small" href="finance-expenses.php">Expenses (This Month)</a>
                        <a class="text-decoration-none fw-bold" href="finance-expenses.php"><?= formatCurrency($adm_expenses_month) ?></a>
                    </div>
                    <div class="d-flex justify-content-between align-items-center">
                        <a class="text-decoration-none text-muted small" href="finance-dashboard.php">Verified Revenue (This Month)</a>
                        <a class="text-decoration-none fw-bold" href="finance-dashboard.php"><?= formatCurrency($adm_revenue_month) ?></a>
                    </div>
                </div>
            </div>
            
            <!-- Recent Payments -->
            <div class="card mb-4">
                <div class="card-header bg-white border-bottom py-3">
                    <h6 class="mb-0 fw-bold">Recent Payments</h6>
                </div>
                <div class="card-body p-0">
                    <?php foreach ($recent_payments as $payment): ?>
                    <div class="p-3 border-bottom d-flex justify-content-between align-items-center">
                        <div class="d-flex align-items-center gap-3">
                            <div class="metric-icon bg-success-soft mb-0" style="width: 40px; height: 40px; font-size: 1rem;">
                                <i class="fa-solid fa-arrow-down"></i>
                            </div>
                            <div>
                                <div class="fw-600 text-sm"><?= htmlspecialchars($payment['client_name']) ?></div>
                                <div class="text-xs text-muted"><?= date('M d, h:i A', strtotime($payment['created_at'])) ?></div>
                            </div>
                        </div>
                        <div class="text-end">
                            <div class="fw-bold text-success">+<?= formatCurrency($payment['amount']) ?></div>
                            <?php 
                                $pstatus = strtolower($payment['status']);
                                $pbadgeClass = $pstatus === 'verified' ? 'status-badge-verified' : ($pstatus === 'pending' ? 'status-badge-pending' : ($pstatus === 'failed' ? 'status-badge-danger' : 'status-badge-info'));
                                $picon = $pstatus === 'verified' ? 'fa-solid fa-check-circle' : ($pstatus === 'pending' ? 'fa-regular fa-clock' : ($pstatus === 'failed' ? 'fa-solid fa-circle-xmark' : 'fa-regular fa-circle-question'));
                            ?>
                            <div class="text-xs">
                                <span class="status-badge <?= $pbadgeClass ?>"><i class="<?= $picon ?>"></i> <?= ucfirst($payment['status']) ?></span>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                    <?php if(empty($recent_payments)): ?>
                    <div class="p-4">
                        <div class="empty-state-premium">
                            <div class="empty-state-icon"><i class="fa-solid fa-wallet"></i></div>
                            <div class="empty-state-title">No recent payments</div>
                            <div class="empty-state-desc">Payments verified or pending updates will appear here. Try filtering recent payments in Finance.</div>
                            <a href="finance-installments.php" class="btn btn-outline-secondary btn-sm">Open Payments</a>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Payment Lifecycle -->
            <div class="card">
                <div class="card-header bg-white border-bottom py-3 d-flex justify-content-between align-items-center">
                    <h6 class="mb-0 fw-bold">Payment Lifecycle</h6>
                    <span class="badge badge-primary text-uppercase">Live</span>
                </div>
                <div class="card-body">
                    <div class="d-flex align-items-center justify-content-between">
                        <div class="chip chip-warning"><i class="fa-regular fa-clock"></i> Pending <span class="badge badge-warning ms-2"><?= number_format($pay_pending_count) ?></span></div>
                        <div class="chip chip-success"><i class="fa-solid fa-check-circle"></i> Verified <span class="badge badge-success ms-2"><?= number_format($pay_verified_count) ?></span></div>
                        <div class="chip chip-danger"><i class="fa-solid fa-circle-xmark"></i> Failed <span class="badge badge-danger ms-2"><?= number_format($pay_failed_count) ?></span></div>
                    </div>
                    <?php
                        $total_payments_count = max(1, $pay_pending_count + $pay_verified_count + $pay_failed_count);
                        $pct_pending = round(($pay_pending_count / $total_payments_count) * 100);
                        $pct_verified = round(($pay_verified_count / $total_payments_count) * 100);
                        $pct_failed   = round(($pay_failed_count / $total_payments_count) * 100);
                    ?>
                    <div class="progress-premium mt-3">
                        <div class="progress-bar-premium progress-bar-warning" style="width: <?= $pct_pending ?>%;"></div>
                    </div>
                    <div class="progress-premium mt-2">
                        <div class="progress-bar-premium progress-bar-success" style="width: <?= $pct_verified ?>%;"></div>
                    </div>
                    <div class="progress-premium mt-2">
                        <div class="progress-bar-premium progress-bar-danger" style="width: <?= $pct_failed ?>%;"></div>
                    </div>
                    <div class="text-xs text-muted mt-2">Distribution by status · last updates</div>
                </div>
            </div>

            <!-- Quick Tasks / Notifications -->
            <div class="card">
                <div class="card-header bg-white border-bottom py-3">
                    <h6 class="mb-0 fw-bold">System Alerts</h6>
                </div>
                <div class="card-body">
                    <div class="d-flex gap-3 mb-3">
                        <div class="text-danger"><i class="fa-solid fa-circle-exclamation"></i></div>
                        <div>
                            <div class="text-sm fw-600">3 Reservations Expiring Soon</div>
                            <div class="text-xs text-muted">Check allocations pending approval</div>
                        </div>
                    </div>
                    <div class="d-flex gap-3 mb-3">
                        <div class="text-warning"><i class="fa-solid fa-triangle-exclamation"></i></div>
                        <div>
                            <div class="text-sm fw-600">5 Overdue Installments</div>
                            <div class="text-xs text-muted">Follow up with clients</div>
                        </div>
                    </div>
                     <div class="d-flex gap-3">
                        <div class="text-info"><i class="fa-solid fa-circle-info"></i></div>
                        <div>
                            <div class="text-sm fw-600">System Backup Completed</div>
                            <div class="text-xs text-muted">Today at 03:00 AM</div>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>

</div>

<script>
// Initialize Revenue Chart
const ctx = document.getElementById('revenueChart').getContext('2d');
new Chart(ctx, {
    type: 'line',
    data: {
        labels: <?= $chart_labels ?>,
        datasets: [{
            label: 'Revenue',
            data: <?= $chart_values ?>,
            borderColor: '#0ea5e9',
            backgroundColor: 'rgba(14, 165, 233, 0.1)',
            tension: 0.4,
            fill: true
        }]
    },
    options: {
        responsive: true,
        plugins: {
            legend: { display: false }
        },
        scales: {
            y: {
                beginAtZero: true,
                grid: { borderDash: [2, 4] }
            },
            x: {
                grid: { display: false }
            }
        }
    }
});
</script>
<script>
(function(){
    const el = document.getElementById('allocDonut');
    if (!el || !window.Chart) return;
    const data = {
        labels: ['Pending','Approved','Active','Completed','Rejected'],
        datasets: [{
            data: [<?= (int)$alloc_pending_count ?>, <?= (int)$alloc_approved_count ?>, <?= (int)$alloc_active_count ?>, <?= (int)$alloc_completed_count ?>, <?= (int)$alloc_rejected_count ?>],
            backgroundColor: ['#f59e0b','#3b82f6','#0ea5e9','#10b981','#ef4444'],
            borderWidth: 0
        }]
    };
    const centerText = {
        id: 'centerText',
        afterDraw(chart) {
            try {
                const ctx = chart.ctx;
                const ca = chart.chartArea;
                if (!ca) return;
                const cx = (ca.left + ca.right) / 2;
                const cy = (ca.top + ca.bottom) / 2;
                const total = (chart.data.datasets[0].data || []).reduce((a,b)=>a + Number(b||0), 0);
                ctx.save();
                ctx.textAlign = 'center';
                ctx.textBaseline = 'middle';
                ctx.fillStyle = '#111827';
                ctx.font = '700 18px Inter, Arial, sans-serif';
                ctx.fillText(String(total), cx, cy - 6);
                ctx.fillStyle = '#6b7280';
                ctx.font = '500 10px Inter, Arial, sans-serif';
                ctx.fillText('Total', cx, cy + 10);
                ctx.restore();
            } catch (e) {}
        }
    };
    if (Chart.register) Chart.register(centerText);
    new Chart(el.getContext('2d'), { type: 'doughnut', data, options: { cutout: '58%', plugins: { legend: { display: false }, centerText: {} } } });
})();
</script>

<?php include 'includes/footer.php'; ?>

Hry