<?php
namespace Modules\Payments\Controllers;

use Gestoreasy\Core\Http\Request;
use Gestoreasy\Core\Http\Response;
use Gestoreasy\Core\Tenant\ConnectionManager;
use Gestoreasy\Core\Security\Crypto;
use Gestoreasy\Core\Audit\AuditLogger;

class SettingsController {
    private function pdo(): \PDO { return ConnectionManager::forTenant(); }

    private function ensureTable(\PDO $pdo): void {
        try {
            $pdo->exec('CREATE TABLE IF NOT EXISTS payment_provider_settings (
                id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
                provider VARCHAR(64) NOT NULL,
                api_key_enc BLOB NULL,
                api_key_iv BLOB NULL,
                api_key_tag BLOB NULL,
                api_key_salt BLOB NULL,
                webhook_secret_enc BLOB NULL,
                webhook_secret_iv BLOB NULL,
                webhook_secret_tag BLOB NULL,
                webhook_secret_salt BLOB NULL,
                target_account_id INT NULL,
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                UNIQUE KEY uniq_provider (provider)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
            // Garantir coluna quando tabela já existe
            $pdo->exec('ALTER TABLE payment_provider_settings ADD COLUMN IF NOT EXISTS target_account_id INT NULL');
        } catch (\Throwable $e) { /* ignore */ }
    }

    private function ensureAsaasTable(\PDO $pdo): void {
        try {
            $pdo->exec('CREATE TABLE IF NOT EXISTS asaas_settings (
                id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
                webhook_secret_enc BLOB NULL,
                webhook_secret_iv BLOB NULL,
                webhook_secret_tag BLOB NULL,
                webhook_secret_salt BLOB NULL,
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
        } catch (\Throwable $e) { /* ignore */ }
    }

    public function get(Request $r): Response {
        $pdo = $this->pdo();
        $this->ensureTable($pdo);
        $params = (array)$r->get('params', []);
        $provider = strtolower((string)($params[0] ?? ''));
        if ($provider === '') return Response::json(['error' => 'provider inválido'], 422);
        if ($provider === 'asaas') {
            $this->ensureAsaasTable($pdo);
            $stmt = $pdo->query('SELECT webhook_secret_enc FROM asaas_settings ORDER BY id DESC LIMIT 1');
            $row = $stmt->fetch(\PDO::FETCH_ASSOC);
            $hasWebhookSecret = $row && !empty($row['webhook_secret_enc']);
            return Response::json(['provider' => $provider, 'has_api_key' => false, 'has_webhook_secret' => $hasWebhookSecret]);
        } else {
            $stmt = $pdo->prepare('SELECT api_key_enc, api_key_iv, api_key_tag, api_key_salt, webhook_secret_enc, webhook_secret_iv, webhook_secret_tag, webhook_secret_salt, target_account_id FROM payment_provider_settings WHERE provider = ? ORDER BY id DESC LIMIT 1');
            $stmt->execute([$provider]);
            $row = $stmt->fetch(\PDO::FETCH_ASSOC);
            $hasApiKey = false;
            $hasWebhookSecret = false;
            if ($row) {
                $hasApiKey = !empty($row['api_key_enc']);
                $hasWebhookSecret = !empty($row['webhook_secret_enc']);
            }
            return Response::json(['provider' => $provider, 'has_api_key' => $hasApiKey, 'has_webhook_secret' => $hasWebhookSecret, 'target_account_id' => isset($row['target_account_id']) ? (int)$row['target_account_id'] : null]);
        }
    }

    public function save(Request $r): Response {
        $pdo = $this->pdo();
        $this->ensureTable($pdo);
        $params = (array)$r->get('params', []);
        $provider = strtolower((string)($params[0] ?? ''));
        if ($provider === '' || !in_array($provider, ['mercadopago','pagbank','asaas','pagarme','itau'], true)) {
            return Response::json(['error' => 'provider inválido (use mercadopago, pagbank, pagarme, itau ou asaas)'], 422);
        }
        $apiKey = (string)($r->body['api_key'] ?? '');
        $webhookSecret = (string)($r->body['webhook_secret'] ?? '');
        $targetAccountId = isset($r->body['target_account_id']) ? (int)$r->body['target_account_id'] : null;
        $encKey = !empty($apiKey) ? Crypto::encryptJson(['api_key' => $apiKey]) : null;
        $encWebhook = !empty($webhookSecret) ? Crypto::encryptJson(['webhook_secret' => $webhookSecret]) : null;

        // Upsert: provider genérico ou asaas
        try {
            $pdo->beginTransaction();
            if ($provider === 'asaas') {
                $this->ensureAsaasTable($pdo);
                $pdo->exec('DELETE FROM asaas_settings');
                $insA = $pdo->prepare('INSERT INTO asaas_settings (webhook_secret_enc, webhook_secret_iv, webhook_secret_tag, webhook_secret_salt) VALUES (?,?,?,?)');
                $insA->execute([
                    $encWebhook['cipher'] ?? null,
                    $encWebhook['iv'] ?? null,
                    $encWebhook['tag'] ?? null,
                    $encWebhook['salt'] ?? null,
                ]);
                AuditLogger::log('update', 'asaas_settings', null, null, null, ['provider' => $provider]);
            } else {
                $del = $pdo->prepare('DELETE FROM payment_provider_settings WHERE provider = ?');
                $del->execute([$provider]);
                $ins = $pdo->prepare('INSERT INTO payment_provider_settings (provider, api_key_enc, api_key_iv, api_key_tag, api_key_salt, webhook_secret_enc, webhook_secret_iv, webhook_secret_tag, webhook_secret_salt, target_account_id) VALUES (?,?,?,?,?,?,?,?,?,?)');
                $ins->execute([
                    $provider,
                    $encKey['cipher'] ?? null,
                    $encKey['iv'] ?? null,
                    $encKey['tag'] ?? null,
                    $encKey['salt'] ?? null,
                    $encWebhook['cipher'] ?? null,
                    $encWebhook['iv'] ?? null,
                    $encWebhook['tag'] ?? null,
                    $encWebhook['salt'] ?? null,
                    $targetAccountId,
                ]);
                AuditLogger::log('update', 'payment_provider_settings', null, null, null, ['provider' => $provider]);
            }
            $pdo->commit();
        } catch (\Throwable $e) {
            if ($pdo->inTransaction()) { $pdo->rollBack(); }
            return Response::json(['error' => 'falha ao salvar: ' . $e->getMessage()], 500);
        }
        return Response::json(['ok' => true]);
    }
}