<?php
class signapi
{
    /**
     * Method 1: Send POST request using file_get_contents
     * (Fixed header issue here)
     */
    public static function http_post($url, $data)
    {
        $options = array(
            'http' => array(
                'method'  => 'POST',
                // Headers ko \r\n se join karna zaroori hai, alag lines nahi
                'header'  => "Content-type: application/x-www-form-urlencoded\r\n" .
                             "Content-Encoding: gzip",
                'content' => $data,
                'timeout' => 15 * 60
            )
        );
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        return $result;
    }

    /**
     * Method 2: Send POST request using cURL (Recommended)
     * Better for Payment Gateways
     */
    public static function http_post_res($url, $data)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_MAXREDIRS, 4);
        curl_setopt($ch, CURLOPT_ENCODING, ""); // Auto handle gzip
        curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        
        // SSL Verification OFF (Development/Testing ke liye, Production me ON rakhein agar zaroorat ho)
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    /**
     * Encoding Converter (For Chinese Gateways)
     */
    public static function convToGBK($str) {
        if (mb_detect_encoding($str, "UTF-8, ISO-8859-1, GBK") != "UTF-8") {
            return iconv("utf-8", "gbk", $str);
        } else {
            return $str;
        }
    }

    /**
     * Create MD5 Signature
     */
    public static function sign($signSource, $key) {
        if (!empty($key)) {
            $signSource = $signSource . "&key=" . $key;
        }
        return md5($signSource);
    }

    /**
     * Validate Signature (Response Check)
     */
    public static function validateSignByKey($signSource, $key, $retsign) {
        if (!empty($key)) {
            $signSource = $signSource . "&key=" . $key;
        }
        $signkey = md5($signSource);
        
        // Case-insensitive comparison is safer for MD5
        return (strtolower($signkey) == strtolower($retsign));
    }
}
?>