<?php
ini_set("display_errors", 0);

// Consultar configs da plataforma
$stmtConfigs = $pdo->prepare("SELECT * FROM configs");
$stmtConfigs->execute();
$resultConfigs = $stmtConfigs->fetch(PDO::FETCH_ASSOC);

// Consultar gateway ativo
$stmtGateways = $pdo->prepare("SELECT * FROM gateways WHERE status = '1' LIMIT 1");
$stmtGateways->execute();
$resultGateways = $stmtGateways->fetch(PDO::FETCH_ASSOC);

session_start();
if (!isset($_SESSION['user'])) {
    header('Location: login.php');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['amount'])) {
    // Capturamos o valor do depósito
    $amount = filter_input(INPUT_POST, "amount", FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);

    // Capturamos o cpf do depositante
    $cpf = filter_input(INPUT_POST, "cpf", FILTER_SANITIZE_SPECIAL_CHARS);

    // Tratamos o cpf do depositante
    $documentTrated = str_replace(['-', '.', ' '], '', $cpf);

    // Tratar dados
    if (!is_numeric($documentTrated)) {
        $_SESSION['toastMessage'] = "O CPF deve ser apenas digitado apenas números.";
        $_SESSION['toastType'] = 'error';
        header("Location: payment.php");
        exit;
    } elseif (strlen($documentTrated) > 11) {
        $_SESSION['toastMessage'] = "O CPF deve ser válido.";
        $_SESSION['toastType'] = 'error';
        header("Location: payment.php");
        exit;
    } elseif ($amount < $resultConfigs['min_dep']) {
        $_SESSION['toastMessage'] = "O valor mínimo para depósito é de R$ " . $resultConfigs['min_dep'];
        $_SESSION['toastType'] = 'error';
        header("Location: payment.php");
        exit;
        // Verificar se o valor não é numérico ou excede o limite
    } elseif (!is_numeric($amount) || $amount > 1000000) {
        $_SESSION['toastMessage'] = "O valor não é numérico, ou excede o limite.";
        $_SESSION['toastType'] = 'error';
        header("Location: payment.php");
        exit;
    }
    
    // Atualizar documento do usuário
    $stmtUpdateUser = $pdo->prepare('UPDATE users SET document = :document WHERE id = :id');
    $stmtUpdateUser->execute([
        ':document' => $cpf,
        ':id' => $user['id']
        ]);

    if ($resultGateways['name'] === 'RocketPay') {
        // Pega callback do servidor
        $callbackUrl = (isset($_SERVER['HTTPS']) ? "https://" : "http://") . $_SERVER['HTTP_HOST'] . "/app/Controllers/webhook_rocketpay.php";
        
        $base64 = base64_encode('ddea8731e3baf859ae69e74f88faa4b8171e9d98f71806d722567445cebeaaa1:ddea8731e3baf859ae69e74f88faa4b8171e9d98f71806d722567445cebeaaa1');

       // Requisição para obter token
                $ch = curl_init($resultGateways['uri'] . '/auth/token/create/');
                curl_setopt_array($ch, [
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_POST => true,
                    CURLOPT_HTTPHEADER => [
                        "Authorization: Basic " . $base64,
                        "Content-Type: application/json",
                        "Accept: application/json"
                        ]
                ]);
                $response = curl_exec($ch);
                $respondeDec = json_decode($response, true);
                $token = $respondeDec['token'];
                
                // Payload para requisição obter PIX
                $urlGateway = $resultGateways['uri'] . "/deposit/";
                $apiKey = $resultGateways['api_key'];
                $authorization = 'Authorization: Bearer ' . $token; 
                
                $payload = [
                    "requestNumber" => uniqid(),
                    "dueDate" => date('Y-m-d', strtotime('+1 day')),
                    "amount" => (float) $amount,
                    "type_operation" => "PIX",
                    "callbackUrl" => $callbackUrl,
                    "usernameCheckout" => "minhaloja",
                    "client" => [
                        "name" => $user['name'] ?? "Maersk User",
                        "document" => $documentTrated,
                        "email" => "user@maersk.com",
                        "phoneNumber" => $user['phone'],
                        "address" => [
                            "street" => "Rua Exemplo",
                            "number" => "123",
                            "zipCode" => "01310-100",
                            "neighborhood" => "Centro",
                            "city" => "São Paulo",
                            "state" => "SP",
                            "complement" => "Apto 45",
                            "codIbge" => "3550308"
                        ]
                    ],
                
                    "products" => [
                        [
                            "description" => "Produto 1",
                            "quantity" => 2,
                            "value" => 50.25
                        ],
                        [
                            "description" => "Produto 2",
                            "quantity" => 1,
                            "value" => 25.00
                        ]
                    ],
                    
                    "split" => [
                        "username" => "afiliado",
                        "valueSplit" => 10,
                        "typeSplit" => 'percentage'
                    ],
                
                    "shippingAmount" => 10.00,
                    "discountAmount" => 10.00,
                ];
    } elseif ($resultGateways['name'] === 'SyncPay') {
        // Pegamos endpoint SyncPay
        $urlGateway = $resultGateways['uri'] . "/v1/gateway/api/";

        // Api key SyncPay
        $apiKey = base64_encode($resultGateways['api_key']);

        // Authorization próprio para SyncPay
        $authorization = 'Authorization: Basic ' . $apiKey;

        // Callback URL
        $callbackUrl = (isset($_SERVER['HTTPS']) ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . "/app/Controllers/webhook_syncpay.php";

        // Criamos o payload para envio SyncPay
        $payload = [
            "amount" => (float) $amount,
            "customer" => [
                "name" => "Paulo Queiroz",
                "email" => "cliente@email.com",
                "cpf" => "02965847521"
            ],
            "postbackUrl" => $callbackUrl
        ];
    }

    // Fazemos a requisição para a Gateway selecionada
    $ch = curl_init($urlGateway);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        $authorization,
        'Content-Type: application/json',
        'User-Agent: Mozilla/5.0',
        'Accept: application/json',
    ]);

    $response = curl_exec($ch);
    $data = json_decode($response, true);

    // Tratamos erros
    if (curl_errno($ch)) {
        echo "Erro Curl: " . curl_error($ch);
    } elseif (!isset($data['status']) || $data['status'] !== 'success' || !isset($data['paymentCode'])) {
        http_response_code(502);
        $toastMessage = 'Erro na conexão com a API: ' . ($data['message'] ?? 'Resposta inesperada.');
        $toastType = 'error';
    } else {
        // Retornamos dados importantes caso haja sucesso
        $qrCode = $data['paymentCode'];
        $urlQR = "https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=" . urlencode($qrCode);
        // Tenta inserir dados da transação no banco

        do {
            $reference = bin2hex(random_bytes(6));
            $stmtReference = $pdo->prepare("SELECT 1 FROM transactions WHERE reference_id = :reference_id LIMIT 1");
            $stmtReference->execute([
                ':reference_id' => $reference
            ]);
            $existis = $stmtReference->fetchColumn() > 0;
        } while ($existis);

        http_response_code(200);
        try {
            $pdo->beginTransaction();
            $stmtInsert = $pdo->prepare("INSERT INTO transactions (user_id, phone, idTransaction, reference_id, value, created_at, qr_code, status) VALUES (:user_id, :phone, :idTransaction, :reference_id, :value, :created_at, :qr_code, :status)");
            $stmtInsert->execute([
                ':user_id' => $user['id'],
                ':phone' => $user['phone'],
                ':idTransaction' => $data['idTransaction'],
                ':value' => $amount ?? null,
                ':reference_id' => $reference,
                ':created_at' => date('Y-m-d H:i:s'),
                ':qr_code' => $data['paymentCode'],
                ':status' => 'awaiting'
            ]);
            $pdo->commit();
            // Caso haja erro, exibe em tela
        } catch (PDOException $e) {
            $pdo->rollBack();
            http_response_code(500);
            $toastMessage = 'Erro interno: ' . $e->getMessage();
            $toastType = 'error';
        }
    }
}
