<?php
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: HEAD, GET, POST, PUT, PATCH, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method,Access-Control-Request-Headers, Authorization");
header('Content-Type: application/json');
$method = $_SERVER['REQUEST_METHOD'];
if ($method == "OPTIONS") {
    header('Access-Control-Allow-Origin: *');
    header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method,Access-Control-Request-Headers, Authorization");
    header("HTTP/1.1 200 OK");
    die();
}


require_once('./vendor/autoload.php');
use Dusterio\LinkPreview\Client;

$format='json';
$callback='';
$site = htmlspecialchars($_GET["url"]);

// fake for testing
// $site = "https://www.eventfull-us.com";

$previewClient = new Client($site);

// Get previews from all available parsers
// $previews = $previewClient->getPreviews();


// Get a preview from specific parser
$preview = $previewClient->getPreview('general');

// Convert output to array
$preview = $preview->toArray();

$title = "";
$description = "";
$url = "";
$site_name = "";

if (isset($preview['title'])){
    $title = $preview['title'];
    $site_name = $preview['title'];
}

if (isset($preview['site_name'])){
    $title = $preview['site_name'];
}

if (isset($preview['cover'])){
    $url = $preview['cover'];
}

if ($url == ""){
    if (isset($preview['images'])){
        if (count($preview['images']) > 0){
            echo(count($preview['images']));
            $url = $preview['images'][0];
        }
    } 
}

$image['url'] = $url;
$out['success'] = 1;
$out['meta'] = array (
    'title' => $title,
    'site_name' => $site_name,
    'description' => $description,
    'image' => $image
);

require_once('display_output.php');
exit;

/*
We want to return the following:
{
    "success" : 1,
    "meta" : {
        "title" : "CodeX Team",
        "site_name" : "CodeX",
        "description" : "Club of web-development, design and marketing. We build team learning how to build full-valued projects on the world market.",
        "image" : {
            "url" : "https://codex.so/public/app/img/meta_img.png"
        }
    }
}

*/