<?php

class RedPay {
    private $username = "agen_test"; 
    private $key = "YERE_23A5FE03EBA6DCE2013F26E72B167D37";
    private $api_url = "https://api.idryerepay.com/bill/api";

    public function __construct() {
    }

    public function generateQRIS($amount, $player_username) {
        $params = [
            'amount' => $amount,
            'player_username' => $player_username,
            'channel' => 'QRIS'
        ];
        return $this->sendRequest('generate', $params);
    }

    public function generateDANA($amount, $player_username) {
        $params = [
            'amount' => $amount,
            'player_username' => $player_username,
            'channel' => 'DANA'
        ];
        return $this->sendRequest('generate', $params);
    }

    public function checkStatus($transaction_id) {
        $params = [
            'transaction_id' => $transaction_id
        ];
        return $this->sendRequest('status', $params);
    }

    public function withdraw($amount, $player_username, $bank_target, $acc_number, $acc_name, $description = "") {
        $params = [
            'amount' => $amount,
            'player_username' => $player_username,
            'bank_target' => $bank_target,
            'account_number' => $acc_number,
            'account_name' => $acc_name,
            'description' => $description
        ];
        return $this->sendRequest('payout', $params);
    }

    private function sendRequest($action, $data) {
        $url = $this->api_url . "/" . $action;
        
        $data['username'] = $this->username;
        $data['key'] = $this->key;

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'Accept: application/json'
        ]);
        
        $response = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);

        if ($error) {
            return ['success' => false, 'message' => "CURL Error: $error"];
        }

        return json_decode($response, true);
    }
}