<?php
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 clip_str(string $value, int $maxLen): string {
    if ($maxLen <= 0) return '';
    if (function_exists('mb_substr')) {
        return (string)mb_substr($value, 0, $maxLen, 'UTF-8');
    }
    return substr($value, 0, $maxLen);
}

function get_default_pix_config() {
    return [
        'pixKey' => '',
        'receiverName' => 'PAGAMENTO',
        'receiverCity' => 'SAO PAULO',
        'amount' => null
    ];
}

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');

    // Tabela de configurações
    $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 configurações PIX
    $pdo->exec("CREATE TABLE IF NOT EXISTS pix_config_history (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        pix_key_old TEXT,
        pix_key_new TEXT,
        receiver_name_old TEXT,
        receiver_name_new TEXT,
        receiver_city_old TEXT,
        receiver_city_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') {
        // Config atual
        $stmt = $pdo->prepare('SELECT value FROM settings WHERE key = :key LIMIT 1');
        $stmt->execute([':key' => 'pix_config']);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        $cfg = get_default_pix_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);
            }
        }
        
        // Histórico de alterações (últimas 50)
        $historyStmt = $pdo->query("SELECT * FROM pix_config_history ORDER BY changed_at DESC LIMIT 50");
        $history = $historyStmt->fetchAll(PDO::FETCH_ASSOC);

        echo json_encode(['status' => 'success', 'data' => $cfg, 'history' => $history]);
        exit;
    }

    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' => 'pix_config']);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        
        $oldCfg = get_default_pix_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;
            }
        }

        $cfg = get_default_pix_config();

        $pixKey = isset($data['pixKey']) ? trim((string)$data['pixKey']) : '';
        $receiverName = isset($data['receiverName']) ? trim((string)$data['receiverName']) : $cfg['receiverName'];
        $receiverCity = isset($data['receiverCity']) ? trim((string)$data['receiverCity']) : $cfg['receiverCity'];
        $amount = array_key_exists('amount', $data) ? $data['amount'] : null;

        if ($pixKey === '') {
            http_response_code(400);
            echo json_encode(['status' => 'error', 'message' => 'pixKey is required']);
            exit;
        }

        if ($receiverName === '') $receiverName = $cfg['receiverName'];
        if ($receiverCity === '') $receiverCity = $cfg['receiverCity'];
        $receiverName = clip_str($receiverName, 25);
        $receiverCity = clip_str($receiverCity, 15);

        if ($amount === '' || $amount === null) {
            $amount = null;
        } else {
            if (is_string($amount)) {
                $normalized = str_replace(['.', ','], ['', '.'], $amount);
                $amount = $normalized;
            }
            $num = floatval($amount);
            if (!is_finite($num) || $num <= 0) {
                http_response_code(400);
                echo json_encode(['status' => 'error', 'message' => 'amount is invalid']);
                exit;
            }
            $amount = $num;
        }

        $newCfg = [
            'pixKey' => $pixKey,
            'receiverName' => $receiverName,
            'receiverCity' => $receiverCity,
            'amount' => $amount
        ];

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

        // Salvar no histórico se houve mudança
        if ($hasChange || $isFirstConfig) {
            $ip = $_SERVER['REMOTE_ADDR'] ?? '';
            $changeType = $isFirstConfig ? 'create' : 'update';
            
            $histStmt = $pdo->prepare("INSERT INTO pix_config_history 
                (pix_key_old, pix_key_new, receiver_name_old, receiver_name_new, receiver_city_old, receiver_city_new, changed_by_ip, change_type, changed_at)
                VALUES (:pix_key_old, :pix_key_new, :receiver_name_old, :receiver_name_new, :receiver_city_old, :receiver_city_new, :ip, :change_type, datetime('now', 'localtime'))");
            
            $histStmt->execute([
                ':pix_key_old' => $isFirstConfig ? null : $oldCfg['pixKey'],
                ':pix_key_new' => $newCfg['pixKey'],
                ':receiver_name_old' => $isFirstConfig ? null : $oldCfg['receiverName'],
                ':receiver_name_new' => $newCfg['receiverName'],
                ':receiver_city_old' => $isFirstConfig ? null : $oldCfg['receiverCity'],
                ':receiver_city_new' => $newCfg['receiverCity'],
                ':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' => 'pix_config',
            ':value' => json_encode($newCfg, JSON_UNESCAPED_UNICODE)
        ]);

        echo json_encode(['status' => 'success', 'data' => $newCfg, '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()]);
}
