<?php
namespace App\Service;
use App\Config\Main;
use App\Core\Service\Logger;
class Api
{
    public function __construct() {
    }

    private function encodeUrlQueryParams(string $url)
    {
        try {
            $parts = parse_url($url);
            if (empty($parts['query'])) {
                return ["status"=>true, "data"=>$url];
            }
    
            parse_str($parts['query'], $queryArray);
    
            $encoded = [];
            foreach ($queryArray as $key => $value) {
                $encoded[] = rawurlencode($key) . '=' . rawurlencode($value);
            }
    
            $base =
                (isset($parts['scheme']) ? $parts['scheme'] . '://' : '') .
                ($parts['host']   ?? '') .
                (isset($parts['port']) ? ':' . $parts['port'] : '') .
                ($parts['path']   ?? '');
    
            return ["status"=>true, "data"=>$base . '?' . implode('&', $encoded)];
        } catch(\Exception $e) {
            Logger::error($e->getMessage(), ['File' => $e->getFile(), 'Line'=>$e->getLine()]);
            return ["status"=>false, "error"=>$e->getMessage()];
        }  
    }

    public function call(String $url, String $method, Array $headers=[], $data=NULL) {
        try {
            $finalrs = $this->encodeUrlQueryParams($url);
            
            if(empty($finalrs['status'])) {
                throw new \Exception($finalrs['error']);
            }

            $url = $finalrs['data'];
            Logger::debug($url, ['File' => __FILE__, 'Line'=>__LINE__]);
            Logger::debug($method, ['File' => __FILE__, 'Line'=>__LINE__]);
            Logger::debug(json_encode($headers), ['File' => __FILE__, 'Line'=>__LINE__]);
            Logger::debug(json_encode($data), ['File' => __FILE__, 'Line'=>__LINE__]);
            $ch = \curl_init();
            curl_setopt_array($ch, [
                CURLOPT_URL => $url,
                CURLOPT_ENCODING => '',
                CURLOPT_TIMEOUT => 30,
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_SSL_VERIFYHOST => false,
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1
            ]);
            if(!empty($headers)) {
                $api_headers = [];
                foreach($headers as $key=>$val) {
                    $api_headers[] = $key . ":". $val;
                }
                curl_setopt($ch, CURLOPT_HTTPHEADER, $api_headers);
            }
            if(strtoupper($method) == 'POST') {
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
                if(!empty($data)) {
                    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
                }
            } else {
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
            }
            $curl_error = curl_error($ch);
            $response = curl_exec($ch);
            $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $curlinfo = curl_getinfo($ch);
            // curl_close($ch);
            Logger::debug($response, ['File' => __FILE__, 'Line'=>__LINE__]);
            Logger::debug("HTTP status:".(string)$http_status, ['File' => __FILE__, 'Line'=>__LINE__]);
            if (!empty($curl_error)) {
                throw new \Exception('API Error : ' . $curl_error);
            }
            if (!in_array((string)$http_status, ["200", "201"])) {
                throw new \Exception(strval($response));
            }
            return ["status"=>true, "data"=>$response, "reqinfo"=>$curlinfo, "http_status"=>$http_status];
        } catch(\Exception $e) {
            Logger::error($e->getMessage(), ['File' => $e->getFile(), 'Line'=>$e->getLine()]);
            return ["status"=>false, "error"=>$e->getMessage()];
        }
    }

    public function emitSocketEvent($client_id, $user_id, $event, $message) {
        try {
            $url = Main::getNodeServer();
            $headers = [
                'Content-Type: application/json'
            ];
            $data = [
                "client_id" => $client_id, 
                "user_id" => $user_id,
                "event" => $event,
                "message" => $message
            ];
            
            $callrs = $this->call($url . '/send_client_message', "POST", $headers, json_encode($data));
            if(empty($callrs['status'])) {
                throw new \Exception($callrs['error']);
            }
            if(empty($callrs['data'])) {
                throw new \Exception("No response from BlueDart login API");
            }
            $response = json_decode($callrs['data'], true);
            return ["status"=>true, "data"=>$response];
        } catch(\Exception $e) {
            Logger::error($e->getMessage(), ['File' => $e->getFile(), 'Line'=>$e->getLine()]);
            return ["status"=>false, "error"=>$e->getMessage()];
        }
    }
} 