<?php

class HTTPRequester
{
    /**
     * تنفيذ طلب HTTP عام
     * @param string $method GET, POST, PUT, DELETE
     * @param string $url
     * @param array  $params
     * @param array  $headers
     * @return string
     */
    public static function http_request($method, $url, $params = [], $headers = [], $options = ['cacert' => 'C:/xampp/php/extras/ssl/cacert.pem']) 
    {
        $ch = curl_init();

        $method = strtoupper($method);

        // بناء الـ URL لطلبات GET/DELETE
        if (in_array($method, ['GET', 'DELETE']) && !empty($params)) {
            $url .= (strpos($url, '?') === false ? '?' : '&') . http_build_query($params);
        }

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    

        if (!empty($headers)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }

        switch ($method) {
            case 'POST':
                curl_setopt($ch, CURLOPT_POST, true);
                if (!empty($params)) {
                    // لو Content-Type = JSON ابعت JSON، غير كده ابعت form-urlencoded
                    $isJson = false;
                    foreach ($headers as $h) {
                        if (stripos($h, 'application/json') !== false) {
                            $isJson = true;
                            break;
                        }
                    }
                    curl_setopt($ch, CURLOPT_POSTFIELDS, $isJson ? json_encode($params) : http_build_query($params));
                }
                break;

            case 'PUT':
            case 'PATCH':
            case 'DELETE':
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
                if (!empty($params)) {
                    $isJson = false;
                    foreach ($headers as $h) {
                        if (stripos($h, 'application/json') !== false) {
                            $isJson = true;
                            break;
                        }
                    }
                    curl_setopt($ch, CURLOPT_POSTFIELDS, $isJson ? json_encode($params) : http_build_query($params));
                }
                break;

            default:
                // GET لا تحتاج إعدادات إضافية
                break;
        }

        $rawResponse = curl_exec($ch);
        $curlErrNo  = curl_errno($ch);
        $curlError  = curl_error($ch);
        $httpCode   = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        curl_close($ch);

        // بناء رد منظم
        $result = [
            'success' => false,
            'http_code' => $httpCode,
            'response' => $rawResponse,
            'error' => '',
            'warning' => ''
        ];

        if ($curlErrNo !== 0) {
            $result['error'] = $curlError . " (errno: $curlErrNo)";
            // شائع: SSL certificate problem: unable to get local issuer certificate
            if (stripos($curlError, 'SSL certificate problem') !== false ||
                stripos($curlError, 'unable to get local issuer certificate') !== false) {
                $result['warning'] = 'SSL error: تأكد من وجود ملف cacert.pem واضبط curl.cainfo في php.ini أو مرر المسار في options["cacert"]';
            }
            return $rawResponse;
        }


        // لو HTTP status 2xx اعتبرها نجاح
        if ($httpCode >= 200 && $httpCode < 300) {
            $result['success'] = true;
        }

        // غير ذلك نرجّع رسالة خطأ مع جسم الاستجابة
        $result['error'] = "HTTP error: $httpCode";
        return $rawResponse;
    }

    public static function HTTPGet($url, array $params = array(), array $headers = array())
    {
        return self::http_request('GET', $url, $params, $headers);
    }

    public static function HTTPPost($url, array $params = array(), array $headers = array())
    {
        return self::http_request('POST', $url, $params, $headers);
    }

    public static function HTTPPut($url, array $params = array(), array $headers = array())
    {
        return self::http_request('PUT', $url, $params, $headers);
    }

    public static function HTTPDelete($url, array $params = array(), array $headers = array())
    {
        return self::http_request('DELETE', $url, $params, $headers);
    }
}
