<?php

    function get_merged_torrent_results($query)
    {
        global $config;

        $results = array();
        $num = array_rand($config->instances);
        $instance = $config->instances[$num];
        $url = "https://$instance/api.php";

        $post_string = "q=$query&t=3";

        $api_ch = curl_init($url);
        curl_setopt_array($api_ch, $config->curl_settings);
        curl_setopt($api_ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($api_ch, CURLOPT_TIMEOUT, 20); // what
        curl_setopt($api_ch, CURLOPT_POSTFIELDS, $post_string);
        $results = json_decode(curl_exec($api_ch),true);

        //if($results == null) $results = "$instance is broken";
        return $results;
    }

    function print_merged_torrent_results($results)
    {
        echo "<div class=\"text-result-container\">";

        if (!empty($results))
        {
            foreach($results as $result)
            {
                $source = $result["source"];
                $name = $result["name"];
                $magnet = $result["magnet"];
                $seeders = $result["seeders"];
                $leechers = $result["leechers"];
                $size = $result["size"];

                echo "<div class=\"text-result-wrapper\">";
                echo "<a href=\"$magnet\">";
                echo "$source";
                echo "<h2>$name</h2>";
                echo "</a>";
                echo "<span>SE: <span class=\"seeders\">$seeders</span> - ";
                echo "LE: <span class=\"leechers\">$leechers</span> - ";
                echo "$size</span>";
                echo "</div>";
            }
        }
        else
            echo "<p>There are no results. Please try different keywords!</p>";

        echo "</div>";
    }

?>