<?php
/**
 * API Config - Gerencia a API Key (Bearer Token) para consultas no DETRAN
 */
require_once __DIR__ . '/require_auth.php';

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Expires: 0');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

date_default_timezone_set('America/Sao_Paulo');

function get_default_api_config() {
    return [
        'apiToken' => '',
        'lastUpdated' => null,
        'description' => ''
    ];
}

try {
    $dbPath = __DIR__ . '/admin.db';
    $pdo = new PDO('sqlite:' . $dbPath);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->exec('PRAGMA journal_mode = WAL');
    $pdo->exec('PRAGMA busy_timeout = 10000');

    // Criar tabela de configurações se não existir
    $pdo->exec("CREATE TABLE IF NOT EXISTS settings (
        key TEXT PRIMARY KEY,
        value TEXT NOT NULL,
        updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )");
    
    // Tabela de histórico de alterações da API Token
    $pdo->exec("CREATE TABLE IF NOT EXISTS api_token_history (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        token_old_masked TEXT,
        token_new_masked TEXT,
        description_old TEXT,
        description_new TEXT,
        changed_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        changed_by_ip TEXT,
        change_type TEXT DEFAULT 'update'
    )");

    // GET - Retorna config atual e histórico
    if ($_SERVER['REQUEST_METHOD'] === 'GET') {
        $stmt = $pdo->prepare('SELECT value FROM settings WHERE key = :key LIMIT 1');
        $stmt->execute([':key' => 'api_config']);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        $cfg = get_default_api_config();
        if ($row && isset($row['value'])) {
            $decoded = json_decode($row['value'], true);
            if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
                $cfg = array_merge($cfg, $decoded);
            }
        }
        
        // Mascarar token para exibição (mostrar apenas últimos 8 caracteres)
        $tokenMasked = '';
        if (!empty($cfg['apiToken'])) {
            $token = $cfg['apiToken'];
            $len = strlen($token);
            if ($len > 8) {
                $tokenMasked = str_repeat('•', min(20, $len - 8)) . substr($token, -8);
            } else {
                $tokenMasked = $token;
            }
        }
        
        // Histórico de alterações (últimas 20)
        $historyStmt = $pdo->query("SELECT * FROM api_token_history ORDER BY changed_at DESC LIMIT 20");
        $history = $historyStmt->fetchAll(PDO::FETCH_ASSOC);

        echo json_encode([
            'status' => 'success', 
            'data' => [
                'apiTokenMasked' => $tokenMasked,
                'hasToken' => !empty($cfg['apiToken']),
                'lastUpdated' => $cfg['lastUpdated'] ?? null,
                'description' => $cfg['description'] ?? ''
            ],
            'history' => $history
        ]);
        exit;
    }

    // POST - Salvar nova configuração
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $input = file_get_contents('php://input');
        $data = json_decode($input, true);
        if (json_last_error() !== JSON_ERROR_NONE || !is_array($data)) {
            http_response_code(400);
            echo json_encode(['status' => 'error', 'message' => 'Invalid JSON']);
            exit;
        }

        // Buscar config atual para histórico
        $stmt = $pdo->prepare('SELECT value FROM settings WHERE key = :key LIMIT 1');
        $stmt->execute([':key' => 'api_config']);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        
        $oldCfg = get_default_api_config();
        $isFirstConfig = true;
        if ($row && isset($row['value'])) {
            $decoded = json_decode($row['value'], true);
            if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
                $oldCfg = array_merge($oldCfg, $decoded);
                $isFirstConfig = false;
            }
        }

        $apiToken = isset($data['apiToken']) ? trim((string)$data['apiToken']) : '';
        $description = isset($data['description']) ? trim((string)$data['description']) : '';

        if ($apiToken === '') {
            http_response_code(400);
            echo json_encode(['status' => 'error', 'message' => 'apiToken é obrigatório']);
            exit;
        }

        $newCfg = [
            'apiToken' => $apiToken,
            'description' => substr($description, 0, 255),
            'lastUpdated' => date('Y-m-d H:i:s')
        ];

        // Função para mascarar token
        $maskToken = function($token) {
            if (empty($token)) return '';
            $len = strlen($token);
            if ($len > 8) {
                return substr($token, 0, 4) . '...' . substr($token, -4);
            }
            return '****';
        };

        // Verificar se houve mudança
        $hasChange = ($oldCfg['apiToken'] !== $newCfg['apiToken']) || 
                     ($oldCfg['description'] !== $newCfg['description']);

        // Salvar no histórico se houve mudança
        if ($hasChange || $isFirstConfig) {
            $ip = $_SERVER['REMOTE_ADDR'] ?? '';
            $changeType = $isFirstConfig ? 'create' : 'update';
            
            $histStmt = $pdo->prepare("INSERT INTO api_token_history 
                (token_old_masked, token_new_masked, description_old, description_new, changed_by_ip, change_type, changed_at)
                VALUES (:token_old, :token_new, :desc_old, :desc_new, :ip, :change_type, datetime('now', 'localtime'))");
            
            $histStmt->execute([
                ':token_old' => $isFirstConfig ? null : $maskToken($oldCfg['apiToken']),
                ':token_new' => $maskToken($newCfg['apiToken']),
                ':desc_old' => $isFirstConfig ? null : $oldCfg['description'],
                ':desc_new' => $newCfg['description'],
                ':ip' => $ip,
                ':change_type' => $changeType
            ]);
        }

        // Salvar config
        $stmt = $pdo->prepare('INSERT INTO settings (key, value, updated_at) VALUES (:key, :value, datetime(\'now\', \'localtime\'))
            ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = datetime(\'now\', \'localtime\')');
        $stmt->execute([
            ':key' => 'api_config',
            ':value' => json_encode($newCfg, JSON_UNESCAPED_UNICODE)
        ]);

        // Mascarar token para resposta
        $tokenMasked = '';
        $len = strlen($newCfg['apiToken']);
        if ($len > 8) {
            $tokenMasked = str_repeat('•', min(20, $len - 8)) . substr($newCfg['apiToken'], -8);
        } else {
            $tokenMasked = $newCfg['apiToken'];
        }

        echo json_encode([
            'status' => 'success', 
            'data' => [
                'apiTokenMasked' => $tokenMasked,
                'hasToken' => true,
                'lastUpdated' => $newCfg['lastUpdated'],
                'description' => $newCfg['description']
            ],
            'history_recorded' => $hasChange || $isFirstConfig
        ]);
        exit;
    }

    http_response_code(405);
    echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => 'Internal Server Error', 'error' => $e->getMessage()]);
}
