<?php
require_once __DIR__ . '/p24_config.php';

class Przelewy24 {
    private $merchantId;
    private $posId;
    private $crc;
    private $apiKey;
    private $baseUrl;
    private $isSandbox;

    public function __construct() {
        $this->merchantId = P24_MERCHANT_ID;
        $this->posId = P24_POS_ID;
        $this->crc = P24_CRC;
        $this->apiKey = P24_API_KEY;
        $this->baseUrl = P24_BASE_URL;
        $this->isSandbox = (P24_ENV === 'sandbox');
    }

    public function createSign($json_data) {
        return hash('sha384', $json_data . $this->crc);
    }
    
    public function registerTransaction(array $data) {
        $payload = [
            'merchantId' => $this->merchantId,
            'posId' => $this->posId,
            'sessionId' => $data['sessionId'],
            'amount' => $data['amount'],
            'currency' => 'PLN',
            'description' => $data['description'],
            'email' => $data['email'],
            'client' => $data['client'],
            'urlReturn' => P24_URL_RETURN,
            'urlStatus' => P24_URL_STATUS,
            'language' => 'pl',
        ];
        $payload['sign'] = $this->createTransactionSign($payload);

        return $this->postRequest('/api/v1/transaction/register', $payload);
    }

    public function verifyTransaction(array $data) {
        $payload = [
            'merchantId' => $this->merchantId,
            'posId' => $this->posId,
            'sessionId' => $data['sessionId'],
            'amount' => $data['amount'],
            'currency' => 'PLN',
            'orderId' => $data['orderId'],
        ];
        $payload['sign'] = $this->createVerificationSign($payload);

        return $this->putRequest('/api/v1/transaction/verify', $payload);
    }

    public function getRedirectUrl($token) {
        return $this->baseUrl . '/trnRequest/' . $token;
    }
    
    private function createTransactionSign(array $payload) {
        $json = json_encode([
            "sessionId" => $payload['sessionId'],
            "merchantId" => $this->merchantId,
            "amount" => $payload['amount'],
            "currency" => $payload['currency'],
            "crc" => $this->crc,
        ]);
        return hash('sha384', $json);
    }
    
    private function createVerificationSign(array $payload) {
        $json = json_encode([
            "sessionId" => $payload['sessionId'],
             "orderId" => $payload['orderId'],
            "amount" => $payload['amount'],
            "currency" => $payload['currency'],
            "crc" => $this->crc,
        ]);
        return hash('sha384', $json);
    }

    private function postRequest($endpoint, $data) {
        return $this->sendRequest('POST', $endpoint, $data);
    }

    private function putRequest($endpoint, $data) {
        return $this->sendRequest('PUT', $endpoint, $data);
    }

    private function sendRequest($method, $endpoint, $data) {
        $url = $this->baseUrl . $endpoint;

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_USERPWD, $this->posId . ':' . $this->apiKey);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
        ]);

        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($http_code >= 200 && $http_code < 300) {
            return json_decode($response, true);
        } else {
            // Handle error, log response for debugging
            error_log("P24 API Error: HTTP {$http_code} - {$response}");
            return null;
        }
    }
}
