<?php

namespace Models;

class TshieldWebhookModel
{
    private \PDO $pdo;

    public function __construct()
    {
        if (!isset($GLOBALS['pdo']) || !($GLOBALS['pdo'] instanceof \PDO)) {
            throw new \RuntimeException('Database connection not initialized.');
        }

        $this->pdo = $GLOBALS['pdo'];
    }

    public function approveByExternalId(string $externalId): bool
    {
        $stmt = $this->pdo->prepare(
            'UPDATE "user" SET user_kyc = 1 WHERE kyc_external_id = :external_id AND user_flag = \'a\''
        );
        $stmt->execute(['external_id' => $externalId]);
        return $stmt->rowCount() > 0;
    }

    public function approveByExternalIds(array $externalIds): int
    {
        $ids = [];
        foreach ($externalIds as $id) {
            if (!is_string($id)) {
                continue;
            }
            $trimmed = trim($id);
            if ($trimmed === '') {
                continue;
            }
            $ids[$trimmed] = true;
        }
        $ids = array_keys($ids);
        if (empty($ids)) {
            return 0;
        }

        $placeholders = [];
        $params = [];
        foreach ($ids as $idx => $value) {
            $key = ':id' . $idx;
            $placeholders[] = $key;
            $params[$key] = $value;
        }

        $sql = 'UPDATE "user" SET user_kyc = 1 '
            . 'WHERE user_flag = \'a\' AND kyc_external_id IN (' . implode(',', $placeholders) . ')';

        $stmt = $this->pdo->prepare($sql);
        $stmt->execute($params);
        return $stmt->rowCount();
    }

    public function approveByCpf(string $cpf): int
    {
        $cpf = preg_replace('/\D+/', '', $cpf);
        $cpf = trim((string)$cpf);
        if ($cpf === '') {
            return 0;
        }

        $stmt = $this->pdo->prepare(
            'UPDATE "user" '
            . 'SET user_kyc = 1 '
            . 'WHERE user_flag = \'a\' '
            . '  AND regexp_replace(user_cpf, \'\\D\', \'\', \'g\') = :cpf'
        );
        $stmt->execute(['cpf' => $cpf]);
        return $stmt->rowCount();
    }

    public function approveCompanyOwnerByCnpj(string $cnpj): int
    {
        $cnpj = preg_replace('/\D+/', '', $cnpj);
        $cnpj = trim((string)$cnpj);
        if ($cnpj === '') {
            return 0;
        }

        $stmt = $this->pdo->prepare(
            'UPDATE "user" u '
            . 'SET user_kyc = 1 '
            . 'FROM "company" c '
            . 'WHERE u.company_id = c.company_id '
            . '  AND regexp_replace(c.company_cnpj, \'\\D\', \'\', \'g\') = :cnpj '
            . '  AND u.role_id = 1 '
            . '  AND u.user_flag = \'a\''
        );
        $stmt->execute(['cnpj' => $cnpj]);
        return $stmt->rowCount();
    }
}
