<?php

namespace Hura8\System;


class Url
{

    /**
     * @param string $url
     * @return bool|string
     */
    public static function getUrlContent(string $url) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; rv:33.0) Gecko/20100101 Firefox/33.0");
        //curl_setopt($ch, CURLOPT_PROXY, $proxy); // $proxy is ip of proxy server
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        //$httpCode = curl_getinfo($ch , CURLINFO_HTTP_CODE); // this results 0 every time
        $response = curl_exec($ch);
        //if ($response === false) $response = curl_error($ch);
        //echo stripslashes($response);
        curl_close($ch);

        return $response;
    }


    public static function isUrlValid($url) {
        if(!$url) return false;
        return (filter_var($url, FILTER_VALIDATE_URL) !== false);
    }


    public static function parse($url) {
        $data = parse_url($url);
        $default = [
            'scheme' => '',
            'host' => '',
            'port' => '',
            'user' => '',
            'pass' => '',
            'path' => '',
            'query' => [],
            'fragment' => '',
        ];
        foreach ($data as $key => $value) {
            if(isset($default[$key])) {
                $default[$key] = ($key == 'query') ? self::parsedQuery($value) : $value;
            }
        }

        return $default;
    }


    public static function parsedQuery($query = '') {
        if(!$query) return [];
        $result = [];
        $parts = array_filter(explode("&", $query));

        foreach ($parts as $part) {
            $el = explode("=", $part);
            if(sizeof($el) != 2) continue;

            $cleaned_key    = preg_replace("/[^a-z0-9_\-\.]/i", '', $el[0]);
            $cleaned_value  = urldecode($el[1]); //preg_replace("/[^a-z0-9_\.\-;&,%]/i", '', urldecode($el[1]));

            $result[$cleaned_key] = $cleaned_value;
        }

        return $result;
    }


    //2-12-2010 build url base on query parameters
    // $query_para = array(key=>value)
    public static function buildUrl($base_url, $query_para, $exclude_page_id = true){

        $base_element = parse_url($base_url);

        if(!isset($base_element['scheme'])) {
            $port = $_SERVER['SERVER_PORT'] ?? '80';

            if((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || $port == 443 ) {
                $base_element['scheme'] = 'https';
            }
            else $base_element['scheme'] = 'http';
        }

        $current_query_para = array();
        if(isset($base_element['query'])){
            parse_str($base_element['query'], $current_query_para);
        }

        $new_query_para = array_merge($current_query_para, $query_para);
        $filter_query_para = [];
        foreach($new_query_para as $key => $val){
            if($val) $filter_query_para[$key] = $val; //urlencode($val); // http_build_query will encode value, no need for urlencode here
        }

        if($exclude_page_id && isset($filter_query_para['page'])) unset($filter_query_para['page']);

        ksort($filter_query_para);

        $query_string  = http_build_query($filter_query_para);

        $host_name = (isset($base_element['host'])) ? $base_element['host'] : ($_SERVER['HTTP_HOST'] ?? '');
        $url_path = isset($base_element['path']) ? $base_element['path'] : '';

        if(substr($url_path, 0, 1) !== '/') $url_path = '/'.$url_path;

        if($query_string) return $base_element['scheme'] . "://". $host_name . $url_path. "?" . $query_string;

        return $base_element['scheme'] . "://". $host_name . $url_path;
    }


}
