63 lines
1.6 KiB
PHP
63 lines
1.6 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 specific company
|
|
$where .= " AND tenant_id = :tenant_id";
|
|
$params[':tenant_id'] = $tenantId;
|
|
|
|
if ($companyId) {
|
|
$where .= " AND company_id = :company_id";
|
|
$params[':company_id'] = $companyId;
|
|
}
|
|
}
|
|
|
|
// 3. Fetch Stats
|
|
$stmt = $db->prepare("SELECT COUNT(*) FROM invoices $where");
|
|
$stmt->execute($params);
|
|
$total = $stmt->fetchColumn();
|
|
|
|
$stmt = $db->prepare("SELECT COUNT(*) FROM invoices $where AND status = 'pending'");
|
|
$stmt->execute($params);
|
|
$pending = $stmt->fetchColumn();
|
|
|
|
$stmt = $db->prepare("SELECT COUNT(*) FROM invoices $where AND status = 'approved'");
|
|
$stmt->execute($params);
|
|
$approved = $stmt->fetchColumn();
|
|
|
|
} catch (\Exception $e) {
|
|
$total = 0;
|
|
$pending = 0;
|
|
$approved = 0;
|
|
}
|
|
|
|
json_success([
|
|
'total' => $total,
|
|
'pending' => $pending,
|
|
'approved' => $approved
|
|
]);
|