<?php

if (isset($_GET['s'])) {
    highlight_file("index.php");
    return;
}

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    // Leggo il nome del film
    if (isset($_GET['n'])) {
        if (!is_string($_GET['n']) || $_GET['n'] === "" || $_GET['n'] === null) {
            http_response_code(400);
            echo '<code>Dati mancanti!</code>';
            return;
        }
        $nome = htmlspecialchars($_GET['n']);

        try {
            $url = "https://imdb.iamidiotareyoutoo.com/search?q=" . urlencode($nome) . "&tt=&lsn=1&v=1";
            $curl = curl_init($url);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            $res = curl_exec($curl);
            $json = json_decode($res);
        } catch (Exception $e) {
            header("Content-Type: image/png");
            echo file_get_contents("film-placeholder.png");
            return;
        }

        if ($res && $json && isset($json->description[0])) {
            $imgUrl = $json->description[0]->{'#IMG_POSTER'};

            $downloadImg = curl_init($imgUrl);
            curl_setopt($downloadImg, CURLOPT_RETURNTRANSFER, true);
            $imageData = curl_exec($downloadImg);
            $contentType = curl_getinfo($downloadImg, CURLINFO_CONTENT_TYPE);
            header("Content-Type: " . $contentType);
            echo $imageData;
        } else {
            header("Content-Type: image/png");
            echo file_get_contents("film-placeholder.png");
            return;
        }
    } else {
        http_response_code(400);
        echo '<code>Dati mancanti!</code>';
        return;
    }
} else {
    http_response_code(405);
    echo '<code>Metodo non consentito!</code>';
    return;
}