<?php

namespace Models;

class CompanySummaryModel
{
    private \PDO $pdo;

    public function __construct()
    {
        if (isset($GLOBALS['pdo']) && $GLOBALS['pdo'] instanceof \PDO) {
            $this->pdo = $GLOBALS['pdo'];
            return;
        }

        throw new \RuntimeException('Global PDO connection not initialized');
    }

    public function getSummary(int $companyId): array
    {
        return [
            'total_tokens' => $this->countCompanyTokens($companyId),
            'active_operations' => $this->countActiveOperations($companyId),
            'total_cprs' => $this->countCompanyCprs($companyId),
            'total_users' => $this->countCompanyUsers($companyId),
        ];
    }

    private function countCompanyTokens(int $companyId): int
    {
        $stmt = $this->pdo->prepare(
            'SELECT COUNT(*)
             FROM "token" t
             INNER JOIN "wallet" w ON w.wallet_id = t.wallet_id
             WHERE w.company_id = :company_id'
        );

        $stmt->execute(['company_id' => $companyId]);

        return (int)$stmt->fetchColumn();
    }

    private function countActiveOperations(int $companyId): int
    {
        $stmt = $this->pdo->prepare(
            'SELECT COUNT(*)
             FROM "orderbook" o
             INNER JOIN "wallet" w ON w.wallet_id = o.wallet_id
             WHERE w.company_id = :company_id
               AND o.status_id = :status_open'
        );

        $stmt->execute([
            'company_id' => $companyId,
            'status_open' => OrderbookModel::STATUS_OPEN,
        ]);

        return (int)$stmt->fetchColumn();
    }

    private function countCompanyCprs(int $companyId): int
    {
        $stmt = $this->pdo->prepare(
            'SELECT COUNT(*) FROM "cpr" WHERE company_id = :company_id'
        );

        $stmt->execute(['company_id' => $companyId]);

        return (int)$stmt->fetchColumn();
    }

    private function countCompanyUsers(int $companyId): int
    {
        $stmt = $this->pdo->prepare(
            'SELECT COUNT(*) FROM "user" WHERE company_id = :company_id'
        );

        $stmt->execute(['company_id' => $companyId]);

        return (int)$stmt->fetchColumn();
    }
}
