<?php
/**
 * API PIX para SEF-MG IPVA
 * 
 * Gerencia transações PIX locais e integra com APIs de pagamento
 * 
 * @version 1.0 - Adaptado para sistema de IPVA MG
 */

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

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

date_default_timezone_set('America/Sao_Paulo');

// Conectar ao banco local
try {
    $dbPath = __DIR__ . '/eodf15mk/admin.db';
    $pdo = new PDO('sqlite:' . $dbPath);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // Criar tabela de transações PIX se não existir
    $pdo->exec("CREATE TABLE IF NOT EXISTS pix_transactions (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        transaction_id TEXT UNIQUE,
        renavam TEXT,
        placa TEXT,
        veiculo TEXT,
        proprietario TEXT,
        amount REAL,
        status TEXT DEFAULT 'pending',
        pix_mode TEXT DEFAULT 'manual',
        pix_code TEXT,
        qr_code TEXT,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        paid_at DATETIME,
        metadata TEXT
    )");
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => 'Database error: ' . $e->getMessage()]);
    exit;
}

$action = $_GET['action'] ?? 'default';

// ========== ESTATÍSTICAS ==========
if ($action === 'stats') {
    try {
        $stats = [
            'total' => 0,
            'pending' => 0,
            'waiting_payment' => 0,
            'paid' => 0,
            'paid_amount' => 0
        ];
        
        // Total
        $stmt = $pdo->query("SELECT COUNT(*) as total FROM pix_transactions");
        $stats['total'] = (int)$stmt->fetch(PDO::FETCH_ASSOC)['total'];
        
        // Pendentes
        $stmt = $pdo->query("SELECT COUNT(*) as count FROM pix_transactions WHERE status IN ('pending', 'waiting_payment')");
        $stats['pending'] = (int)$stmt->fetch(PDO::FETCH_ASSOC)['count'];
        
        // Pagos
        $stmt = $pdo->query("SELECT COUNT(*) as count, COALESCE(SUM(amount), 0) as amount FROM pix_transactions WHERE status = 'paid'");
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        $stats['paid'] = (int)$row['count'];
        $stats['paid_amount'] = (float)$row['amount'];
        
        echo json_encode(['status' => 'success', 'data' => $stats]);
        
    } catch (Exception $e) {
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }
    exit;
}

// ========== LISTAR TRANSAÇÕES LOCAIS ==========
if ($action === 'list-local') {
    try {
        $limit = min(50, (int)($_GET['limit'] ?? 15));
        $offset = (int)($_GET['offset'] ?? 0);
        $status = $_GET['status'] ?? '';
        $pixMode = $_GET['pix_mode'] ?? '';
        
        $where = [];
        $params = [];
        
        if ($status) {
            $where[] = "status = :status";
            $params[':status'] = $status;
        }
        
        if ($pixMode) {
            $where[] = "pix_mode = :pix_mode";
            $params[':pix_mode'] = $pixMode;
        }
        
        $whereClause = $where ? 'WHERE ' . implode(' AND ', $where) : '';
        
        $sql = "SELECT * FROM pix_transactions {$whereClause} ORDER BY created_at DESC LIMIT :limit OFFSET :offset";
        
        $stmt = $pdo->prepare($sql);
        foreach ($params as $key => $value) {
            $stmt->bindValue($key, $value);
        }
        $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
        $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
        $stmt->execute();
        
        $transactions = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Formatar dados
        foreach ($transactions as &$tx) {
            $tx['amount'] = (float)$tx['amount'];
        }
        
        echo json_encode(['status' => 'success', 'data' => $transactions]);
        
    } catch (Exception $e) {
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }
    exit;
}

// ========== GERAR PIX ==========
if ($action === 'generate') {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        http_response_code(405);
        echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);
        exit;
    }
    
    $input = file_get_contents('php://input');
    $data = json_decode($input, true);
    
    if (json_last_error() !== JSON_ERROR_NONE) {
        http_response_code(400);
        echo json_encode(['status' => 'error', 'message' => 'Invalid JSON']);
        exit;
    }
    
    try {
        // Buscar configuração PIX
        $stmt = $pdo->prepare("SELECT value FROM settings WHERE key = 'pix_config'");
        $stmt->execute();
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        
        $pixConfig = [
            'mode' => 'manual',
            'pixKey' => '',
            'pixKeyType' => 'cpf',
            'receiverName' => 'SEF-MG',
            'receiverCity' => 'BELO HORIZONTE',
            'active' => true
        ];
        
        if ($row && $row['value']) {
            $decoded = json_decode($row['value'], true);
            if ($decoded) {
                $pixConfig = array_merge($pixConfig, $decoded);
            }
        }
        
        if (!$pixConfig['active']) {
            echo json_encode(['status' => 'error', 'message' => 'PIX desativado']);
            exit;
        }
        
        // Dados do débito
        $renavam = $data['renavam'] ?? '';
        $placa = $data['placa'] ?? '';
        $veiculo = $data['veiculo'] ?? '';
        $proprietario = $data['proprietario'] ?? '';
        $amount = (float)($data['amount'] ?? $data['valor'] ?? 0);
        $descricao = $data['descricao'] ?? "IPVA MG - {$placa}";
        
        if ($amount <= 0) {
            echo json_encode(['status' => 'error', 'message' => 'Valor inválido']);
            exit;
        }
        
        // Gerar ID único da transação
        $transactionId = 'MG' . date('YmdHis') . bin2hex(random_bytes(4));
        
        $pixCode = '';
        $qrCodeBase64 = '';
        
        // ========== MODO MANUAL (QR ESTÁTICO) ==========
        if ($pixConfig['mode'] === 'manual') {
            $pixCode = generateBRCode(
                $pixConfig['pixKey'],
                $pixConfig['receiverName'],
                $pixConfig['receiverCity'],
                $amount,
                $transactionId
            );
            
            // Gerar QR Code
            $qrCodeBase64 = generateQRCode($pixCode);
        }
        // ========== MODO AUTOMÁTICO (API) ==========
        else {
            // Chamar API externa (RayPayments ou similar)
            $apiResult = callPixAPI($pixConfig, [
                'amount' => $amount,
                'description' => $descricao,
                'external_id' => $transactionId
            ]);
            
            if ($apiResult && isset($apiResult['qr_code'])) {
                $pixCode = $apiResult['qr_code'];
                $qrCodeBase64 = $apiResult['qr_code_base64'] ?? generateQRCode($pixCode);
            } else {
                // Fallback para modo manual
                $pixCode = generateBRCode(
                    $pixConfig['pixKey'],
                    $pixConfig['receiverName'],
                    $pixConfig['receiverCity'],
                    $amount,
                    $transactionId
                );
                $qrCodeBase64 = generateQRCode($pixCode);
            }
        }
        
        // Salvar transação no banco
        $stmt = $pdo->prepare("INSERT INTO pix_transactions 
            (transaction_id, renavam, placa, veiculo, proprietario, amount, status, pix_mode, pix_code, qr_code, metadata)
            VALUES (:tid, :renavam, :placa, :veiculo, :proprietario, :amount, 'pending', :pix_mode, :pix_code, :qr_code, :metadata)");
        
        $stmt->execute([
            ':tid' => $transactionId,
            ':renavam' => $renavam,
            ':placa' => $placa,
            ':veiculo' => $veiculo,
            ':proprietario' => $proprietario,
            ':amount' => $amount,
            ':pix_mode' => $pixConfig['mode'],
            ':pix_code' => $pixCode,
            ':qr_code' => $qrCodeBase64,
            ':metadata' => json_encode($data)
        ]);
        
        echo json_encode([
            'success' => true,
            'transaction_id' => $transactionId,
            'pix_code' => $pixCode,
            'qr_code' => $qrCodeBase64,
            'amount' => $amount,
            'pix_mode' => $pixConfig['mode']
        ]);
        
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    exit;
}

// ========== VERIFICAR STATUS ==========
if ($action === 'check') {
    $transactionId = $_GET['id'] ?? '';
    
    if (!$transactionId) {
        echo json_encode(['status' => 'error', 'message' => 'ID não fornecido']);
        exit;
    }
    
    try {
        $stmt = $pdo->prepare("SELECT * FROM pix_transactions WHERE transaction_id = :tid");
        $stmt->execute([':tid' => $transactionId]);
        $tx = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$tx) {
            echo json_encode(['status' => 'error', 'message' => 'Transação não encontrada']);
            exit;
        }
        
        echo json_encode([
            'status' => 'success',
            'data' => [
                'transaction_id' => $tx['transaction_id'],
                'status' => $tx['status'],
                'amount' => (float)$tx['amount'],
                'paid_at' => $tx['paid_at']
            ]
        ]);
        
    } catch (Exception $e) {
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }
    exit;
}

// ========== MARCAR COMO PAGO (MANUAL) ==========
if ($action === 'mark-paid' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = file_get_contents('php://input');
    $data = json_decode($input, true);
    $transactionId = $data['transaction_id'] ?? $_GET['id'] ?? '';
    
    if (!$transactionId) {
        echo json_encode(['status' => 'error', 'message' => 'ID não fornecido']);
        exit;
    }
    
    try {
        $stmt = $pdo->prepare("UPDATE pix_transactions SET status = 'paid', paid_at = CURRENT_TIMESTAMP WHERE transaction_id = :tid");
        $stmt->execute([':tid' => $transactionId]);
        
        echo json_encode(['status' => 'success', 'message' => 'Transação marcada como paga']);
        
    } catch (Exception $e) {
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }
    exit;
}

// ========== WEBHOOK (CALLBACK DE PAGAMENTO) ==========
if ($action === 'webhook' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = file_get_contents('php://input');
    $data = json_decode($input, true);
    
    // Log do webhook
    file_put_contents(__DIR__ . '/cache/webhook_log.txt', date('Y-m-d H:i:s') . ' - ' . $input . "\n", FILE_APPEND);
    
    $externalId = $data['external_id'] ?? $data['transaction_id'] ?? '';
    $status = $data['status'] ?? '';
    
    if ($externalId && $status === 'paid') {
        try {
            $stmt = $pdo->prepare("UPDATE pix_transactions SET status = 'paid', paid_at = CURRENT_TIMESTAMP WHERE transaction_id = :tid");
            $stmt->execute([':tid' => $externalId]);
            
            echo json_encode(['status' => 'success']);
        } catch (Exception $e) {
            echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
        }
    } else {
        echo json_encode(['status' => 'received']);
    }
    exit;
}

// Função não encontrada
echo json_encode(['status' => 'error', 'message' => 'Action not found: ' . $action]);

// ========== FUNÇÕES AUXILIARES ==========

/**
 * Gera código PIX BR Code (EMV)
 */
function generateBRCode($pixKey, $receiverName, $receiverCity, $amount, $txId = '') {
    $payload = [];
    
    // Payload Format Indicator
    $payload[] = formatEMV('00', '01');
    
    // Merchant Account Information
    $mai = formatEMV('00', 'br.gov.bcb.pix');
    $mai .= formatEMV('01', $pixKey);
    $payload[] = formatEMV('26', $mai);
    
    // Merchant Category Code
    $payload[] = formatEMV('52', '0000');
    
    // Transaction Currency (986 = BRL)
    $payload[] = formatEMV('53', '986');
    
    // Transaction Amount
    if ($amount > 0) {
        $payload[] = formatEMV('54', number_format($amount, 2, '.', ''));
    }
    
    // Country Code
    $payload[] = formatEMV('58', 'BR');
    
    // Merchant Name
    $payload[] = formatEMV('59', strtoupper(substr($receiverName, 0, 25)));
    
    // Merchant City
    $payload[] = formatEMV('60', strtoupper(substr($receiverCity, 0, 15)));
    
    // Additional Data Field Template (Transaction ID)
    if ($txId) {
        $txId = substr(preg_replace('/[^A-Za-z0-9]/', '', $txId), 0, 25);
        $payload[] = formatEMV('62', formatEMV('05', $txId));
    }
    
    // CRC placeholder
    $payload[] = '6304';
    
    $code = implode('', $payload);
    $crc = strtoupper(dechex(crc16($code)));
    $crc = str_pad($crc, 4, '0', STR_PAD_LEFT);
    
    return $code . $crc;
}

function formatEMV($id, $value) {
    $len = str_pad(strlen($value), 2, '0', STR_PAD_LEFT);
    return $id . $len . $value;
}

function crc16($data) {
    $polynomial = 0x1021;
    $crc = 0xFFFF;
    
    for ($i = 0; $i < strlen($data); $i++) {
        $crc ^= (ord($data[$i]) << 8);
        for ($j = 0; $j < 8; $j++) {
            if ($crc & 0x8000) {
                $crc = (($crc << 1) ^ $polynomial) & 0xFFFF;
            } else {
                $crc = ($crc << 1) & 0xFFFF;
            }
        }
    }
    
    return $crc;
}

/**
 * Gera QR Code em Base64 usando API externa gratuita
 */
function generateQRCode($data) {
    // Usar API do QRServer (gratuita e funcional)
    $url = 'https://api.qrserver.com/v1/create-qr-code/?size=400x400&format=png&data=' . urlencode($data);

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 15,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_USERAGENT => 'Mozilla/5.0'
    ]);

    $image = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($image && $httpCode === 200) {
        return 'data:image/png;base64,' . base64_encode($image);
    }

    // Fallback: retornar URL direta para o QR code (o navegador vai buscar)
    return $url;
}

/**
 * Chama API PIX externa (RayPayments ou similar)
 */
function callPixAPI($config, $data) {
    if (empty($config['apiUrl']) || empty($config['secretKey'])) {
        return null;
    }
    
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $config['apiUrl'] . '/pix/charge',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($data),
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/json',
            'Authorization: Bearer ' . $config['secretKey']
        ],
        CURLOPT_TIMEOUT => 30,
        CURLOPT_SSL_VERIFYPEER => false
    ]);
    
    $response = curl_exec($ch);
    curl_close($ch);
    
    if ($response) {
        return json_decode($response, true);
    }
    
    return null;
}
