<?php
/* * * * * * * * * * * * * * * * * * * * *
 *
 *  ██████╗ ███╗   ███╗ ██████╗ ███████╗
 * ██╔═══██╗████╗ ████║██╔════╝ ██╔════╝
 * ██║   ██║██╔████╔██║██║  ███╗█████╗
 * ██║   ██║██║╚██╔╝██║██║   ██║██╔══╝
 * ╚██████╔╝██║ ╚═╝ ██║╚██████╔╝██║
 *  ╚═════╝ ╚═╝     ╚═╝ ╚═════╝ ╚═╝
 *
 * @package  : OMGF
 * @author   : Daan van den Bergh
 * @copyright: (c) 2019 Daan van den Bergh
 * @url      : https://daan.dev
 * * * * * * * * * * * * * * * * * * * */

defined('ABSPATH') || exit;

$db                = new OMGF_DB();
$fonts             = $db->get_downloaded_fonts();
$families          = array_unique(
    array_map(
        function ($i) {
            return $i->font_family;
        },
        $fonts
    )
);
$omgfStaticVersion = '?ver=' . OMGF_STATIC_VERSION;
$omgfSrcUrl        = OMGF_UPLOAD_URL . '/' . OMGF_FILENAME . (OMGF_REMOVE_VERSION ? null : $omgfStaticVersion);
$wflVersion        = '?ver=' . OMGF_WEB_FONT_LOADER_VERSION;
$wflSrcUrl         = plugin_dir_url(OMGF_PLUGIN_FILE) . 'js/libraries/webfont.js' . (OMGF_REMOVE_VERSION ? null : $wflVersion);
?>
<?php if ($fonts && $families): ?>
    <script type="text/javascript">
        /**
         * Using Typekit's Web Font Loader to load OMGF's fonts asynchronously.
         *
         * @type {{custom: {urls: string[], families: string[]}}}
         */
        WebFontConfig = {
            custom: {
                families: [
                    <?php foreach ($families as $family): ?>
                    <?php
                        $fvds = [];
                        foreach ($fonts as $font) {
                            if ($font->font_family != $family) {
                                continue;
                            }
                            $fvds[] = mb_substr($font->font_style, 0, 1) . mb_substr($font->font_weight, 0, 1);
                        }
                    ?>
                    '<?= $family; ?>:<?= implode(',', $fvds); ?>',
                    <?php endforeach; ?>
                ],
                urls: [
                    '<?= $omgfSrcUrl; ?>'
                ]
            }
        };

        (function (d) {
            var wf = d.createElement(
                'script'),
                s = d.scripts[0];
            wf.src = '<?= $wflSrcUrl; ?>';
            wf.async = true;
            wf.text = 'text/javascript';
            s.parentNode.insertBefore(
                wf,
                s
            );
        })(document);
    </script>
<?php endif; ?>
