class AlipayException extends Exception {}

class Alipay {

    private $_partner_id = "";
    private $_key = "";
    private $_endpoint = "https://khqr-nang--ten.vercel.app/api/check";

    public function __construct($partnerId, $privateKey)
    {
        $this->_partner_id = $partnerId;
        $this->_key = $privateKey;
    }

    public function verifyPayment($data = array())
    {
        $md5 = $data['out_trade_no']; // treat this as the transaction md5

        $payload = json_encode([
            "md5" => $md5
        ]);

        $headers = [
            "Content-Type: application/json",
            "Authorization: Bearer {$this->_key}"
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->_endpoint);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);

        $response = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);

        if ($error) {
            throw new AlipayException("Curl error: $error");
        }

        $res = json_decode($response, true);

        if (isset($res['verified']) && $res['verified'] === true && $res['responseCode'] === 0) {
            return true;
        } else {
            throw new AlipayException("KHQR Payment not verified: " . $res['responseMessage'] ?? 'Unknown error');
        }

        return false;
    }
}
