<?php
declare(strict_types=1);

/*
|--------------------------------------------------------------------------
| TechStackBase – Dashboard KPIs (AUTHORITATIVE)
|--------------------------------------------------------------------------
| - Single endpoint
| - Role-aware scope
| - COUNT-only queries
| - Backend authoritative
*/

require_once __DIR__ . '/../system/bootstrap.php';
require_once __DIR__ . '/../system/auth.php';
require_once __DIR__ . '/../system/response.php';

header('Content-Type: application/json');

/* =========================
   AUTH
   ========================= */
$actor = require_auth($pdo);

$role = $actor['role_key'];

if (!in_array($role, [
    'super_admin',
    'platform_admin',
    'rsp_admin',
    'company_admin'
], true)) {
    error_forbidden('Access denied');
}

/* =========================
   SCOPE
   ========================= */
$where = [];
$params = [];

if ($role === 'rsp_admin') {
    $where[] = 'rsp_id = :rsp_id';
    $params['rsp_id'] = (int)$actor['rsp_id'];
}

if ($role === 'company_admin') {
    $where[] = 'company_id = :company_id';
    $params['company_id'] = (int)$actor['company_id'];
}

$whereSql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';

/* =========================
   USERS KPIs
   ========================= */
$userCounts = function (string $extraWhere = '') use ($pdo, $whereSql, $params): int {
    $sql = "SELECT COUNT(*) FROM users $whereSql";
    if ($extraWhere !== '') {
        $sql .= ($whereSql ? ' AND ' : ' WHERE ') . $extraWhere;
    }
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    return (int)$stmt->fetchColumn();
};

$users = [
    'total'    => $userCounts(),
    'active'   => $userCounts("status = 'active'"),
    'locked'   => $userCounts("status = 'locked'"),
    'disabled' => $userCounts("status = 'disabled'")
];

/* =========================
   COMPANIES KPIs
   ========================= */
$companies = null;

if (in_array($role, ['super_admin','platform_admin','rsp_admin'], true)) {

    $companyWhere = [];
    $companyParams = [];

    if ($role === 'rsp_admin') {
        $companyWhere[] = 'rsp_id = :rsp_id';
        $companyParams['rsp_id'] = (int)$actor['rsp_id'];
    }

    $companyWhereSql = $companyWhere
        ? 'WHERE ' . implode(' AND ', $companyWhere)
        : '';

    // Total companies
    $stmt = $pdo->prepare("
        SELECT COUNT(*)
        FROM companies
        $companyWhereSql
    ");
    $stmt->execute($companyParams);
    $totalCompanies = (int)$stmt->fetchColumn();

    // Active companies
    $activeWhereSql = $companyWhere
        ? $companyWhereSql . " AND status = 'active'"
        : "WHERE status = 'active'";

    $stmt = $pdo->prepare("
        SELECT COUNT(*)
        FROM companies
        $activeWhereSql
    ");
    $stmt->execute($companyParams);
    $activeCompanies = (int)$stmt->fetchColumn();

    $companies = [
        'total'  => $totalCompanies,
        'active' => $activeCompanies
    ];
}

/* =========================
   SUBSCRIPTIONS KPIs
   ========================= */
$subsWhere = [];
$subsParams = [];

if ($role === 'rsp_admin') {
    $subsWhere[] = 'rsp_id = :rsp_id';
    $subsParams['rsp_id'] = (int)$actor['rsp_id'];
}

if ($role === 'company_admin') {
    $subsWhere[] = 'company_id = :company_id';
    $subsParams['company_id'] = (int)$actor['company_id'];
}

$subsWhereSql = $subsWhere ? 'WHERE ' . implode(' AND ', $subsWhere) : '';

/* =========================
   SUBSCRIPTIONS KPIs
   ========================= */
/*
 | Billing not implemented yet.
 | Do NOT query non-existent tables.
 | Keep dashboard stable until Billing module is live.
 */
$subscriptions = [
    'active'  => 0,
    'expired' => 0
];


/* =========================
   USAGE (LAST 24H)
   ========================= */
$usageWhere = [];
$usageParams = [];

if ($role === 'rsp_admin') {
    $usageWhere[] = 'rsp_id = :rsp_id';
    $usageParams['rsp_id'] = (int)$actor['rsp_id'];
}

if ($role === 'company_admin') {
    $usageWhere[] = 'company_id = :company_id';
    $usageParams['company_id'] = (int)$actor['company_id'];
}

$usageWhere[] = 'created_at >= (NOW() - INTERVAL 1 DAY)';
$usageWhereSql = 'WHERE ' . implode(' AND ', $usageWhere);

$stmt = $pdo->prepare("
    SELECT
        SUM(action = 'login')         AS logins,
        SUM(action = 'login_failed')  AS failed_logins,
        SUM(target_type IN ('user','company','module','subscription')) AS admin_actions
    FROM audit_logs
    $usageWhereSql
");
$stmt->execute($usageParams);
$usageRow = $stmt->fetch(PDO::FETCH_ASSOC);

$usage = [
    'logins_24h'        => (int)($usageRow['logins'] ?? 0),
    'failed_logins_24h' => (int)($usageRow['failed_logins'] ?? 0),
    'admin_actions_24h' => (int)($usageRow['admin_actions'] ?? 0)
];

/* =========================
   RESPONSE
   ========================= */
success('Dashboard KPIs loaded', [
    'users'         => $users,
    'companies'     => $companies,
    'subscriptions' => $subscriptions,
    'usage'         => $usage
]);
