<?PHP
/**
 * For embedding from museum-digital functions.
 *
 * @file
 *
 * @author Joshua Ramon Enslin <joshua@jrenslin.de>
 */

/**
 * Function for checking a text for the existence of pseudocode
 * for embedding from museum-digital.
 *
 * @param string $text     Input string.
 * @param array  $settings General settings.
 *
 * @return string
 */
function checkForEmbeds(string $text, array $settings):string {

    $embedOptions = [
        "singleObjectTile",
        "singleObjectDetails",
        "singleCollectionTile",
        "exhibitionCalendar",
        "eventCalendar"
    ];

    foreach ($embedOptions as $option) {

        if (strpos($text, $option) === false) continue;
        $position = strpos($text, $option) - 1;

        $nextTag = $nextWhitespace = strlen($text);
        if (strpos($text, "<", $position) !== false) $nextTag        = strpos($text, "<", $position);
        if (strpos($text, " ", $position) !== false) $nextWhitespace = strpos($text, " ", $position);

        $end = min($nextTag, $nextWhitespace);

        $pseudocode = substr($text, $position, $end - $position);

        $command   = substr($pseudocode, 1, strpos($pseudocode, "]") - 1);
        $arguments = [];
        if (strpos($pseudocode, "{") !== false) $arguments = explode("&", substr($pseudocode, strpos($pseudocode, "{") + 1, -1));

        switch ($command) {
        case "singleObjectTile":
            $text = str_replace($pseudocode, embedObject($arguments, $settings), $text);
            break;
        case "singleObjectDetails":
            $text = str_replace($pseudocode, embedObject($arguments, $settings, true), $text);
            break;
        case "exhibitionCalendar":
            $text = str_replace($pseudocode, embedExhibitionCalendar($arguments), $text);
            break;
        case "eventCalendar":
            $text = str_replace($pseudocode, embedEventCalendar($arguments), $text);
            break;
        }

    }

    return $text;

}

/**
 * Function drawObjectTile creates a tile with just the most basic information on an object.
 *
 * @param string[] $contents Input data fetched from the object API at museum-digital.
 * @param array    $settings Settings variable.
 *
 * @return string
 */
function drawObjectTile(array $contents, array $settings):string {

    $output = '
    <div class="objTile">
    ';

    if (count($contents['object_images']) > 0) {
        foreach ($contents['object_images'] as $image) {
            if ($image['is_main'] != "j") continue;
            $output .= '
        <img src="' . $settings['mdImgFolder'] . $image['folder'] . '/' . $image['preview'] . '" />';
        }
    }

    $output .= '
        <div>

            <h4>' . $contents['object_name'] . '</h4>

            <div>
                <a href="./object.php?id=' . $contents['object_id'] . '" class="toTranslate" data-content="More"></a>
                <a href="' . $settings['mdVersion'] . '?t=objekt&oges=' . $contents['object_id'] . '" class="toTranslate" data-content="MoreAtMuseumDigital">' . $contents['object_name'] . '</a>
            </div>

        </div>

    </div>
    ';

    return $output;

}

/**
 * Function drawObjectDetails creates a tile with just the most basic information on an object.
 *
 * @param string[] $contents Input data fetched from the object API at museum-digital.
 * @param array    $settings Settings variable.
 *
 * @return string
 */
function drawObjectDetails(array $contents, array $settings):string {

    $output = '
    <div class="objDetails">

        <h2>' . $contents['object_name'] . '</h2>
    ';

    if (count($contents['object_images']) > 0) {
        foreach ($contents['object_images'] as $image) {
            if ($image['is_main'] != "j") continue;
            $output .= '
        <img class="objMainImg" src="' . $settings['mdImgFolder'] . $image['folder'] . '/' . $image['filename_loc'] . '" />';
        }
    }

    $output .= '
        <div>
    ';

    $output .= '
            <p>
                ' . $contents['object_description'] . '
            </p>';

    $simpleDefinedConts = [
        "object_material_technique",
        "object_dimensions",
    ];

    $output .= "
            <dl>";
    if (count($contents['object_collection']) > 0) {
        $output .= '
                <dt class="toTranslate" data-content="Collection"></dt>';
        foreach ($contents['object_collection'] as $collection) {
            $output .= '
                <dd>' . $collection['collection_name'] . '</dd>
                ';
        }
    }

    foreach ($simpleDefinedConts as $value) {
        $output .= "
                <dt class='toTranslate' data-content='" . $value . "'></dt>
                <dd>" . $contents[$value] . "</dd>
        ";
    }

    if (count($contents['object_tags']) > 0) {
        $output .= '
                <dt class="toTranslate" data-content="Tags"></dt>';
        foreach ($contents['object_tags'] as $tag) {
            $output .= '
                <dd>' . $tag['tag_name'] . '</dd>
                ';
        }
    }

    if (count($contents['object_relation_places']) > 0) {
        $output .= '
                <dt class="toTranslate" data-content="Places"></dt>';
        foreach ($contents['object_relation_places'] as $place) {
            $output .= '
                <dd>' . $place['place']['place_name'] . '</dd>
                ';
        }
    }

    if (count($contents['object_relation_people']) > 0) {
        $output .= '
                <dt class="toTranslate" data-content="People"></dt>';
        foreach ($contents['object_relation_people'] as $people) {
            $output .= '
                <dd>' . $people['people']['displayname'] . '</dd>
                ';
        }
    }
    $output .= "
            </dl>";

    if (count($contents['object_events']) > 0) {
        $output .= "
            <div class='events'>";
        foreach ($contents['object_events'] as $event) {
            $output .= '

    <div class="objevent">
        <h5 class="toTranslate" data-content="eventType' . $event['event_type'] . '"></h5>
        <table>
        ';

            if (isset($event['people'])) $output .= '
        <tr>
            <th class="toTranslate" data-content="... who"></th>
            <td class="vcard h-card">
                <a rel="tag" class="u-url fn p-name url">' . $event['people']['displayname'] . '</a>
            </td>
        </tr>';

            if (isset($event['time'])) $output .= '
        <tr>
            <th class="toTranslate" data-content="... when"></th>
            <td>
                <a>' . $event['time']['time_name'] . '</a>
            </td>
        </tr>';

            if (isset($event['place'])) $output .= '
        <tr>
            <th class="toTranslate" data-content="... where"></th>
            <td class="h-geo geo">
                <a rel="tag">' . $event['place']['place_name'] . '</a>
            </td>
        </tr>';
            $output .= '
        </table>
    </div>
                ';
        }
        $output .= '
            </div>
        ';
    }

    $output .= '
            <p class="metadataLine">
                <span><span class="toTranslate" data-content="Metadata"></span></span>
                <span><span class="toTranslate" data-content="LastUpdated"></span>: ' . $contents['object_last_updated'] . '</span>
                <span><span class="toTranslate" data-content="Licence"></span>: ' . $contents['licence']['metadata_rights_status'] . '</span>
                <span><a class="toTranslate" data-content="ObjectAtMuseumDigital" href="' . $settings['mdVersion'] . '?t=objekt&oges=' . $contents['object_id'] . '"></a></span>
            </p>
        </div>
    ';

    $output .= '
    </div>
    ';

    return $output;

}

/**
 * Function for displaying objects.
 *
 * @param array   $arguments   Arguments / GET parameters for urls to query.
 * @param array   $settings    Settings variable.
 * @param boolean $showDetails Optional. By default, only a tile with most basic information is displayed.
 *
 * @return string
 */
function embedObject(array $arguments, array $settings, bool $showDetails = false):string {

    $toIgnore = ["t=", "output="];
    $srcArgs  = "t=objekt";
    foreach ($arguments as $arg) {
        if (startsWithAny($arg, $toIgnore)) continue;
        $srcArgs .= "&" . $arg;
    }
    $srcArgs .= "&output=json";

    $contents = json_decode(queryCachePage($settings['mdVersion'] . "?$srcArgs", "object", $settings), true);

    if (!$showDetails) return drawObjectTile($contents, $settings);
    else return drawObjectDetails($contents, $settings);

}

/**
 * Function for embedding event calendar.
 *
 * @param array $arguments Arguments / GET parameters for urls to query.
 *
 * @return string
 */
function embedExhibitionCalendar(array $arguments):string {

    $toIgnore = ["t=", "calendar=", "output="];
    $srcArgs  = "t=exhibitions_overview&calendar=1";
    foreach ($arguments as $arg) {
        if (startsWithAny($arg, $toIgnore)) continue;
        $srcArgs .= "&" . $arg;
    }
    $srcArgs .= "&output=json";

    $srcURL = "apiMirror.php?area=exhibitions&args=" . urlencode($srcArgs);

    if (isset($_GET['y'])) $y = $_GET['y'];
    else $y = date("Y");
    if (isset($_GET['m'])) $m = $_GET['m'];
    else $m = date("m");

    $prevMonth = strtotime('-1 month', strtotime("$y-$m-01"));
    $nextMonth = strtotime('+1 month', strtotime("$y-$m-01"));

    $output = '
        <section class="mdCalendar"
            data-year="'.$y.'" data-month="'.$m.'" data-colored="1"
            data-today="./index.php?id=' . $GLOBALS['id'] . '&' . date("Y").'&m='.date("m") . '"
            data-prev="./index.php?id=' . $GLOBALS['id'] . '&y=' . date("Y", $prevMonth).'&m='.date("m", $prevMonth) . '"
            data-next="./index.php?id=' . $GLOBALS['id'] . '&y=' . date("Y", $nextMonth).'&m='.date("m", $nextMonth) . '"
            data-src="' . $srcURL . '&y='.date("Y", $nextMonth).'&m='.date("m", $nextMonth) . '">
        </section>
    ';

    return $output;
}

/**
 * Function for embedding event calendar.
 *
 * @param array $arguments Arguments / GET parameters for urls to query.
 *
 * @return string
 */
function embedEventCalendar(array $arguments):string {

    $toIgnore = ["t=", "calendar=", "output="];
    $srcArgs  = "t=events&calendar=1";
    foreach ($arguments as $arg) {
        if (startsWithAny($arg, $toIgnore)) continue;
        $srcArgs .= "&" . $arg;
    }
    $srcArgs .= "&output=json";

    $srcURL = "apiMirror.php?area=events&args=" . urlencode($srcArgs);

    if (isset($_GET['y'])) $y = $_GET['y'];
    else $y = date("Y");
    if (isset($_GET['m'])) $m = $_GET['m'];
    else $m = date("m");

    $prevMonth = strtotime('-1 month', strtotime("$y-$m-01"));
    $nextMonth = strtotime('+1 month', strtotime("$y-$m-01"));

    $output = '
        <section class="mdCalendar"
            data-year="'.$y.'" data-month="'.$m.'" data-colored="1"
            data-today="./index.php?id=' . $GLOBALS['id'] . '&' . date("Y").'&m='.date("m") . '"
            data-prev="./index.php?id=' . $GLOBALS['id'] . '&y=' . date("Y", $prevMonth).'&m='.date("m", $prevMonth) . '"
            data-next="./index.php?id=' . $GLOBALS['id'] . '&y=' . date("Y", $nextMonth).'&m='.date("m", $nextMonth) . '"
            data-src="' . $srcURL . '&y='.date("Y", $nextMonth).'&m='.date("m", $nextMonth) . '">
        </section>
    ';

    return $output;
}

?>
