<?php
ini_set("display_errors", 0);
require '../../app/Controllers/sessions.php';
require '../../app/Controllers/security_admin.php';
require '../../config/db.php';

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

// Consultar configs
$stmtPlatConfigs = $pdo->prepare("SELECT taxa_saq FROM configs WHERE id = '1'");
$stmtPlatConfigs->execute();
$resultPlatConfigs = $stmtPlatConfigs->fetch(PDO::FETCH_ASSOC);

// Validação de sessão admin
session_start();
if (!isset($_SESSION['admin_session'])) {
    header("Location: ../login.php");
    exit;
}

// Verificar se o método é POST
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['payment_pix'])) {
    $idWith = filter_input(INPUT_POST, 'id_with', FILTER_VALIDATE_INT);
    var_dump($idWith);
    // Verificar se o ID foi enviado.
    if (!$idWith) {
        echo json_encode(['error' => 'ID inválido.']);
        http_response_code(400);
        exit;
    }
    
    // Consultar se está pendente a retirada.
    $stmtSearchWith = $pdo->prepare("SELECT * FROM withdrawal WHERE id = :id AND status = 'pending'");
    $stmtSearchWith->execute([':id' => $idWith]);
    $resultWithData = $stmtSearchWith->fetch(PDO::FETCH_ASSOC);

    // Se não encontrar a retirada, encerra o código.
    if ($stmtSearchWith->rowCount() === 0) {
        echo json_encode(['error' => 'Retirada não encontrada.']);
        http_response_code(404);
        exit;
    }

    // Formatações
    $cpfFormated = str_replace(['.', '-'], '', $resultWithData['cpf_beneficiary']);
    $keyPixFormated = str_replace(['.', '-', '(', ')', ' '], '', $resultWithData['key_beneficiary']);
    $value = filter_var($resultWithData['value'], FILTER_VALIDATE_FLOAT);

    if($resultWithData['type_pix'] === 'EMAIL') {
        $keyPixFormated = $resultWithData['key_beneficiary'];
    }

    // Verifica se o gateway ativo é ROCKETPAY.
    if ($resultGateways['name'] === 'RocketPay') {
        $value = $value - (($value * (float)$resultPlatConfigs['taxa_saq']) / 100);
        $apiKey = $resultGateways['api_key'];
        $urlCashOut = $resultGateways['uri'] . '/withdrawal/';
        
        $base64 = base64_encode($resultGateways['client_id'] . ':' . $resultGateways['client_secret']);

        $ch = curl_init('https://api.rocketpaydigital.com/auth/token/create/');
        curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_POST => 1,
        CURLOPT_HTTPHEADER => [
            "Authorization: Basic $base64",
            "Content-Type: application/json"
        ]
        ]);
        
        $response = curl_exec($ch);
        $responseDecode = json_decode($response, true);
        file_put_contents('token.log', json_encode($responseDecode['token']));
        
        $token = $responseDecode['token'];

        $payload = [
            "amount" => (float)$value,
            "key" => $keyPixFormated,
            "type" => $resultWithData['type_pix'],
            "type_operation" => "PIX",
            "document" => $cpfFormated
        ];
    $authorization = 'Authorization: Bearer ' . $token;
    // Verifica se o gateway ativo é SYNCPAY.
    } elseif ($resultGateways['name'] === 'SyncPay') {
        $value = $value - (($value * (float)$resultPlatConfigs['taxa_saq']) / 100);
        $apiKey = $resultGateways['api_key'];
        $apiBase = base64_encode($apiKey);
        $urlCashOut = $resultGateways['uri'] . '/c1/cashout/api/';
        $authorization = 'Authorization: Basic ' . $apiBase;
        $urlWebhook = (isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] !== 'off' ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . "/app/Controllers/webhook_with.php";
        
        $payload = [
            "amount" => (float)$value,
            "pixKey" => $keyPixFormated,
            "pixType" => $resultWithData['type_pix'],
            "beneficiaryName" => $resultWithData['name_beneficiary'],
            "beneficiaryDocument" => $cpfFormated,
            "description" => "Pagamento generico",
            "postbackUrl" => $urlWebhook
        ];
    }
    
    file_put_contents('payload.txt', json_encode($payload) . PHP_EOL, FILE_APPEND);
    $ch = curl_init($urlCashOut);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        $authorization,
        'Content-Type: application/json'
    ]);
    $response = curl_exec($ch);
    file_put_contents('testeResponsePIX.txt', $response);
    file_put_contents('testeToken.log', $authorization);

    if (curl_errno($ch)) {
        echo "Erro Curl: " . curl_error($ch);
        exit;
    }

    curl_close($ch);
    $data = json_decode($response, true);
    file_put_contents('teste.txt', json_encode($data) . PHP_EOL, FILE_APPEND);

    if (!is_array($data)) {
        $_SESSION['toastMessage'] = $toastMessage = 'Resposta inválida da API.';
        $_SESSION['toastType'] = $toastType = 'error';
        header("Location: index.php?busca_saques=&status_saques=pending&page=withdrawals");
        exit;
    }

    if ($resultGateways['name'] === "SyncPay" && isset($data['data']['externalreference'])) {
        $stmtUpdateTransaction = $pdo->prepare("UPDATE withdrawal SET external_reference = :external_reference WHERE id = :id");
        $stmtUpdateTransaction->execute([
            ':external_reference' => $data['data']['externalreference'],
            ':id' => $idWith
        ]);
    }

    if ($data['status'] == 'PENDING') {
         $stmtUpdateTransaction1 = $pdo->prepare("UPDATE withdrawal SET status = :status, external_reference = :external_reference WHERE id = :id");
        $stmtUpdateTransaction1->execute([
            ':status' => 'approved',
            ':external_reference' => $data['idTransaction'],
            ':id' => $idWith
        ]);
        $_SESSION['toastMessage'] = $toastMessage = 'Saque aprovado com sucesso!';
        $_SESSION['toastType'] = $toastType = 'success';
        header("Location: index.php?busca_saques=&status_saques=pending&page=withdrawals");
        exit;
    } else {
        $_SESSION['toastMessage'] = $toastMessage = 'Ocorreu um erro ao sacar: ' . $data['message'] ?? 'Erro Desconhecido.';
        $_SESSION['toastType'] = $toastType = 'error';
        header("Location: index.php?busca_saques=&status_saques=pending&page=withdrawals");
        exit;
}

}