<?php
require('includes/config.php');
require('includes/ImgHelper.php');
require('includes/phpuri.php');

$stmt = $db->prepare('SELECT postID, postHook, postTitle, postCont, postDate, postThumb, postModified FROM blog_posts_seo WHERE postSlug = :postSlug');
$stmt->execute(array(':postSlug' => $_GET['id']));
$row = $stmt->fetch();

//if post does not exists redirect user.
if($row['postID'] == ''){
	header('Location: ./');
	exit;
}

$phelper = new ImgHelper('imagick');
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=G-J0WB1CGFLJ"></script>
    <script>
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());

        gtag('config', 'G-J0WB1CGFLJ');
    </script>

    <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1179008588405496"
            crossorigin="anonymous"></script>

    <?php
        $adSpots = [
            'ezoic-pub-ad-placeholder-112',
            'ezoic-pub-ad-placeholder-113',
            'ezoic-pub-ad-placeholder-114',
            'ezoic-pub-ad-placeholder-115'
        ];
    ?>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="<?php echo $row['postHook'];?>">
    <title><?php echo getTitle($row['postTitle']);?></title>
<!--    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">-->
<!--   -->
    <link rel="stylesheet" type="text/css" href="../style/bootstrap_main.css"/>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/progressive-image.js/dist/progressive-image.css">
    <link rel="stylesheet" href="../style/normalize.css">
    <link rel="stylesheet" href="../style/main.css">
    <link rel="stylesheet" href="../style/carousel.css">
    <link rel="stylesheet" href="/style/prism.css" />
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/progressive-image.js/dist/progressive-image.js"></script>
    <script type="application/ld+json">
    <?php
        $schema = array(
            '@context' =>     "https://schema.org",
            '@type' =>        "BlogPosting",
            'url' =>          'https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'],
            'headline' =>      $row['postTitle'],
            'alternativeHeadline' => $row['postTitle'],
            'description' =>   $row['postHook'],
            'datePublished' => $row['postDate'],
            'dateModified' =>  $row['postModified'],
            'image' => array(
                '@type' => 'imageObject',
                'url' =>   phpUri::parse('https://'.$_SERVER['HTTP_HOST'].'/')->join($row['postThumb'])
            ),
            'publisher' => array(
                '@type' => 'Organization',
                'name' =>  'Wltd',
                'logo' => array(
                   '@type' => 'imageObject',
                    'url' => phpUri::parse('https://'.$_SERVER['HTTP_HOST'].'/')->join('blog_images/logo.png')
                )
            ),
            'author' => array(
                '@type' => 'Person',
                'name' =>  'Raphael Budd'
            ),
            'genre' =>       'Tech',
            'accessMode' =>  array('textual', 'visual'),
            'accessModeSufficient' => array('textual', 'visual'),
            'discussionUrl' => 'https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']."/#disqus_thread",
            'inLanguage' => 'English',
            'articleBody' =>  $row['postHook']
        );

        echo json_encode($schema);
    ?>
    </script>
</head>
<body class="d-flex flex-column min-vh-100">
    <?php
        include('includes/cookie_consent.php');
        include('includes/mailinglist/call_to_action.php');
    ?>
	<div class="container-fluid">
        <div class="row sticky-top bg-white" id="heading">
            <div class="col no-pad">
                <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
                    <div class="container-fluid">
                      <a class="navbar-brand" href="/">
                        <img src="/blog_images/logo.svg" height="30" width="auto" class="d-inline-block align-top" alt="">
                        Wltd
                      </a>
                      <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo01" aria-controls="navbarTogglerDemo01" aria-expanded="false" aria-label="Toggle navigation">
                        <span class="navbar-toggler-icon"></span>
                      </button>
                      <div class="collapse navbar-collapse" id="navbarTogglerDemo01">
                              <ul class="navbar-nav me-auto">
                                <li class="nav-item">
                                  <a class="nav-link" href="/">Home</a>
                                </li>
                                <li class="nav-item dropdown">
                                  <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                                    Categories
                                  </a>
                                  <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
                                      <?php include $_SERVER['DOCUMENT_ROOT'].'/contactsNav.php'; ?>
                                  </div>
                                </li>
                                <li class="nav-item dropdown">
                                  <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuTools" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                                      Tools
                                  </a>
                                  <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuTools">
                                      <?php include $_SERVER['DOCUMENT_ROOT'].'/toolsNav.php'; ?>
                                  </div>
                                </li>
                                <li class="nav-item">
                                  <a class="nav-link" href="/about">About</a>
                                </li>
                                <li class="nav-item">
                                  <a class="nav-link" href="/contact">Contact</a>
                                </li>
                              </ul>
                              <form class="d-flex mt-2 mb-2 mb-lg-0 mt-lg-0">
                                  <button type="button" class="btn btn-primary my-2 my-sm-0 me-sm-2" data-bs-toggle="modal" data-bs-target="#joinMailingList">
                                      Subscribe
                                  </button>
                              </form>
                              <form class="d-flex mb-2 mb-lg-0" action="/search" method="get">
                                  <input class="form-control me-sm-2 h-auto" type="search" placeholder="Search" aria-label="Search" name="q">
                                  <button class="btn btn-success my-2 my-sm-0" type="submit">Search</button>
                              </form>
                          </div>
                    </div>
                </nav>
            </div>
        </div>

		<div class="row">

            <div class="col-xxl-2 col-xl-2 col-lg-3">
                <!-- Ezoic - SidebarFloatingMain - sidebar_floating_1 -->
                <div id="ezoic-pub-ad-placeholder-140"> </div>
                <!-- End Ezoic - SidebarFloatingMain - sidebar_floating_1 -->
            </div>

            <div class="col-xxl-7 col-xl-7 col-lg-9 col-12">

                <?php
                    echo '<div class="post">';
                        echo '<h1>'.$row['postTitle'].'</h1>';
                        echo '<p>Updated on '.date('jS M Y H:i', strtotime($row['postModified'])).' in ';

                            $stmt2 = $db->prepare('SELECT catTitle, catSlug	FROM blog_cats, blog_post_cats WHERE blog_cats.catID = blog_post_cats.catID AND blog_post_cats.postID = :postID');
                            $stmt2->execute(array(':postID' => $row['postID']));

                            $catRow = $stmt2->fetchAll(PDO::FETCH_ASSOC);

                            $links = array();
                            foreach ($catRow as $cat)
                            {
                                $links[] = "<a href='/category/".$cat['catSlug']."'>".$cat['catTitle']."</a>";
                            }
                            echo implode(", ", $links);

                        echo '</p>';

                        $pContent = $row['postCont'];

                        //do some work here to make the ad divs actually have ads in them
                        $dom = new DOMDocument();
                        @$dom->loadHTML(mb_convert_encoding($pContent, 'HTML-ENTITIES', "UTF-8"));

                        $xpath = new DomXPath($dom);
                        $i = 0;
                        foreach($xpath->query("//div[contains(concat(\" \", normalize-space(@class), \" \"), \" ad \")]") as $spot) {
                            $adDiv = $dom->createElement('div');
                            $adDiv->setAttribute('id', $adSpots[$i]);
                            $spot->parentNode->replaceChild($adDiv, $spot);
                            $i++;

                            if($i > count($adSpots)) {
                                //this isn't good
                                break;
                            }
                        }

                        foreach($dom->getElementsByTagName('img') as $img) {
                            $source = $img->getAttribute('src');
                            $exclude = strpos($source, '.svg') == true|| strpos($source, '.gif') == true;
                            if(strpos($source, 'blog_images/') !== false && !$exclude) {
                                //chop off the first part of the URL. We don't need it for internal imgs
                                $url = substr($source, strpos($source, 'blog_images/') + 12);

                                $width = $img->getAttribute('width');
                                $pic = $phelper->getPicture($url);
                                $img->parentNode->replaceChild($pic->getPictureElement($img, $width), $img);
                            }
                        }

                        $pContent = $dom->saveHTML();

                        echo '<p>'.$pContent.'</p>';
                    echo '</div>';
                ?>

                <div class="row">
                    <div class="col">
                        <!-- Ezoic - bottom_of_page 106 - bottom_of_page -->
                        <div id="ezoic-pub-ad-placeholder-106"> </div>
                        <!-- End Ezoic - bottom_of_page 106 - bottom_of_page -->
                    </div>
                </div>

                <div class="row">
                    <div class="col">
                        <h2>Other Posts</h2>
                        <hr>
                    </div>
                </div>
                <div class="container-fluid">
                    <div id="carouselExample" class="carousel slide" data-bs-ride="carousel" data-bs-interval="9000">
                        <div class="suggestions carousel-inner row w-100 mx-auto" role="listbox">
                <?php
                $recommended = '     <div class="suggestion col-12 col-sm-6 col-md-4 carousel-item">
                                          <a><img class="img-fluid mx-auto d-block"></a>
                                          <div class="text-center d-md-block">
                                            <a class="postName"></a>
                                          </div>
                                     </div>';
                    $recommender = new Recommended();
                    $stmt = $recommender->getSimilarPosts($row['postID'], $db);
                    $maxWidth = 400; //the maximum width of the thumbnails, they auto scale but really will not be bigger than this. Even if they are, they will scale up worst case.
                    $first = true;
                    while($val = $stmt->fetch()){
                        $source = $val['postThumb'];
                        $src = $val['postThumb'];
                        $srcset = '';

                        $dom = new DOMDocument();
                        @$dom->loadHTML($recommended);
                        $xpath = new DomXPath($dom);

                        if($first) {
                            $container = $xpath->query("//div[contains(concat(\" \", normalize-space(@class), \" \"), \" suggestion \")]")->item(0);
                            $container->setAttribute('class', $container->getAttribute('class').' active');
                            $first = false;
                        }

                        $anchor = $xpath->query("//div[contains(concat(\" \", normalize-space(@class), \" \"), \" suggestion \")]/a")->item(0);
                        $img = $xpath->query("//div[contains(concat(\" \", normalize-space(@class), \" \"), \" suggestion \")]/a/img")->item(0);
                        $link = $xpath->query("//a[@class='postName']")->item(0);

                        $img->setAttribute('alt', $val['postTitle']);
                        if(strpos($source, 'blog_images/') !== false) {
                            //chop off the first part of the URL. We don't need it for internal imgs
                            $url = substr($source, strpos($source, 'blog_images/') + 12);

                            $pic = $phelper->getPicture($url);
                            $img->parentNode->replaceChild($pic->getPictureElement($img, $maxWidth), $img);
                        }

                        $anchor->setAttribute('href', '/posts/'.$val['postSlug']);

                        $title = $dom->createTextNode($val['postTitle']);
                        $link->setAttribute('href', '/posts/'.$val['postSlug']);
                        $link->appendChild($title);

                        $temp = $dom->saveHTML();
                        echo $temp;
                    }

                ?>
                        </div>
                    </div>
                </div>

                <div id="disqus_thread" class="mt-2"></div>
                <script>
                    /**
                    *  RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.
                    *  LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables*/

                    var disqus_config = function () {
                    var host = "<?php echo $_SERVER['HTTP_HOST'] ?>";
                    var content = "<?php echo $_SERVER['REQUEST_URI'] ?>";
                    this.page.url = "https://"+host+content;  // Replace PAGE_URL with your page's canonical URL variable
                    console.log(this.page.url);
                    <?php echo "this.page.identifier =".$row['postID'].";" ?>// Replace PAGE_IDENTIFIER with your page's unique identifier variable
                    };

                    var loaded = false;

                    var disqus = function() { // DON'T EDIT BELOW THIS LINE
                    var d = document, s = d.createElement('script');
                    s.src = 'https://wltd.disqus.com/embed.js';
                    s.setAttribute('data-timestamp', +new Date());
                    (d.head || d.body).appendChild(s);
                    };

                    $(window).on("scroll", function() {
                        if($(window).scrollTop() + window.innerHeight > $(document).height() - 100) {
                            if(!loaded) {
                                disqus();
                                loaded = true;
                            }
                        }
                    });
                </script>
                <noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
		    </div>

            <div class="col-xxl-2 col-xl-3 d-none d-xl-block" id="sidePane">
                <div id="sidePaneInner">
                    <?php require('sidebar.php'); ?>
                </div>
            </div>

            <div class="col-xxl-1">
            </div>
        </div>
	</div>

    <footer class="footer mt-auto">
      <div class="container text-center">
            <a href="/privacy" class="text-muted">Privacy Policy</a>
            &middot;
            ©<?php echo date('Y');?> Wltd
      </div>
    </footer>

    <script src="/js/prism.js"></script>
    <script type="application/javascript">
        $(document).ready(function() {
            $('#carouselExample').on('slide.bs.carousel', function (e) {

                /*

                CC 2.0 License Iatek LLC 2018
                Attribution required

                */

                var $e = $(e.relatedTarget);

                var idx = $e.index();

                var itemsPerSlide = 3;
                var totalItems = $('.suggestion.carousel-item').length;

                if (idx >= totalItems - (itemsPerSlide - 1)) {
                    var it = itemsPerSlide - (totalItems - idx);
                    for (var i = 0; i < it; i++) {
                        // append slides to end
                        if (e.direction == "left") {
                            $('.suggestion.carousel-item').eq(i).appendTo('.suggestions.carousel-inner');
                        } else {
                            $('.suggestion.carousel-item').eq(0).appendTo('.suggestions.carousel-inner');
                        }
                    }
                }
            });
        });
    </script>

</body>
</html>