Files
musadaq-saas/app/modules_app/dashboard/stats.php
2026-05-04 00:37:14 +03:00

75 lines
2.4 KiB
PHP

<?php
/**
* Dashboard Stats Endpoint (Role-Based & Tenant-Aware)
*/
use App\Core\Database;
use App\Middleware\AuthMiddleware;
// 1. Auth Check
$decoded = AuthMiddleware::check();
$db = Database::getInstance();
$tenantId = $decoded['tenant_id'] ?? null;
$companyId = $decoded['company_id'] ?? null;
$role = $decoded['role'];
try {
$where = "WHERE 1=1";
$params = [];
// 2. Apply Filters based on Role
if ($role === 'super_admin') {
// No filters - see everything
} elseif ($role === 'admin') {
// Filter by Tenant (Accounting Office)
$where .= " AND tenant_id = :tenant_id";
$params[':tenant_id'] = $tenantId;
} else {
// Accountant/Viewer: Filter by assigned companies
$where .= " AND tenant_id = :tenant_id";
$params[':tenant_id'] = $tenantId;
// Get assigned company IDs
$stmtUser = $db->prepare("SELECT company_id FROM user_company_assignments WHERE user_id = ? AND is_active = 1");
$stmtUser->execute([$decoded['user_id']]);
$assignedCompanyIds = $stmtUser->fetchAll(PDO::FETCH_COLUMN);
if (empty($assignedCompanyIds)) {
// No companies assigned, see nothing
$where .= " AND 1=0";
} else {
$placeholders = implode(',', array_fill(0, count($assignedCompanyIds), '?'));
$where .= " AND company_id IN ($placeholders)";
// We need to merge params carefully since we are using both named and positional
// Actually, let's switch to pure positional for simplicity here
$where = str_replace(':tenant_id', '?', $where);
$params = array_merge([$tenantId], $assignedCompanyIds);
}
}
// 3. Fetch Stats
$stmt = $db->prepare("SELECT COUNT(*) FROM invoices $where");
$stmt->execute(array_values($params));
$total = $stmt->fetchColumn();
$stmt = $db->prepare("SELECT COUNT(*) FROM invoices $where AND status = 'pending'");
$stmt->execute(array_values($params));
$pending = $stmt->fetchColumn();
$stmt = $db->prepare("SELECT COUNT(*) FROM invoices $where AND status = 'approved'");
$stmt->execute(array_values($params));
$approved = $stmt->fetchColumn();
} catch (\Exception $e) {
$total = 0;
$pending = 0;
$approved = 0;
}
json_success([
'total' => $total,
'pending' => $pending,
'approved' => $approved
]);