<?session_start();
require_once 'googleapis/vendor/autoload.php';

const INITIAL_NUMBER_OF_ARTICLES = 8;
const INITIAL_NUMBER_OF_ARTICLE_SLOTS = 16;
const ARTICLE_UPDATE_AMOUNT = 4;
$debug = false;

$startTime = hrtime(true);
$_SESSION["Log"] = "";
function tc($pretext = ""){
    global $startTime;
    $_SESSION["Log"] .= "\n";
    if (!empty($pretext)) $_SESSION["Log"] .= $pretext.": ";
    $_SESSION["Log"] .= ((hrtime(true) - $startTime) / 1000);
    $startTime = hrtime(true);
}

$servername = "localhost";
$database = "trumpzws_wtf";
$username = "trumpzws_stinson";
$password = "KeTSUa4VMi@L7Qf";

if ($debug || true){
    $_SESSION["Articles"] = array();
    $_SESSION["AllArticleURLs"] = array();
    $_SESSION["UsedArticles"] = array();
    $_SESSION["BadURLs"] = array();
}

$client = getClient();

// if SetSession posted, update the specified session val
// Note: will also apply SetSession as a session val, but that's ok
if (!empty($_POST["SetSession"])){
    foreach ($_POST as $name=>$value){
    	// support null values by interpreting "null" string
    	if ($value == "null") $value = null;
    	$_SESSION[$name] = $value;
    }
}
// if AddSession posted, add the specified value to the specified session array
else if (!empty($_POST["AddSession"])){
    $name = $_POST["SessionName"];
    $key = $_POST["SessionKey"];
    $value = $_POST["SessionValue"];
    
	// support null values by interpreting "null" string
	if ($value == "null") $value = null;
	
    if (!isset($key) || $key == null) array_push($_SESSION[$name], $value);
    else $_SESSION[$name][$key] = $value;
}
// if ArticleNum posted, produce a styled HTML preview from og meta data
else if (!empty($_POST["LoadArticles"])){
    for($i = 0; $i < $_POST["LoadArticles"]; $i++){
        generateArticle();
    }
}
// NOTE: update articles function disabled here on wedidntforget.com domain
// // if UpdateArticles posted, update db with new articles from sheets
// else if (!empty($_GET["UpdateArticles"])){
//     updateArticles(true);
// }
// otherwise, assume main page loading
else{
    ?><!DOCTYPE html>
<html>
    <head>
        <!-- Global site tag (gtag.js) - Google Analytics -->
        <script async src="https://www.googletagmanager.com/gtag/js?id=UA-179520843-1"></script>
        <script>
          window.dataLayer = window.dataLayer || [];
          function gtag(){dataLayer.push(arguments);}
          gtag('js', new Date());
          gtag('config', 'UA-179520843-1');
        </script>
        <title>We Didn't Forget</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta property="og:title" content="We Didn't Forget">
        <meta property="og:description" content="Refresh your memory of the thousands of head-shaking moments Trump created since taking office">
        <meta property="og:image" content="https://www.wedidntforget.com/Trump3x.png">
        <meta property="og:url" content="https://wedidntforget.com/">
        <meta property="og:type" content="article">
        <meta name="twitter:title" content="We Didn't Forget">
        <meta name="twitter:description" content="Refresh your memory of the thousands of head-shaking moments Trump created since taking office">
        <meta name="twitter:image" content="https://www.wedidntforget.com/Trump3x.png">
        <meta name="twitter:card" content="summary_large_image">
        <link rel="icon" type="image/png"  href="favicon4.png">
        <link href="https://wedidntforget.com" rel="canonical">
        <link rel="stylesheet" href="styles.css?version=67">
        <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Montserrat">
        <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
        <script src="https://kit.fontawesome.com/1c7485e8c5.js" crossorigin="anonymous"></script>
    </head>
    <body>
    <div id="MegaModal" class="overlay" style="display:none; position:fixed; top:0; left:0; right:0; bottom:0; z-index:1;" onclick="toggleModal()"></div>
    
    <!-- Navbar (sit on top) -->
    <div class="w3-bar w3-black flex" style="min-height:35%;">
        <div class="trump overlayContainer flex">
            <div class="flex overlay w3-wide" style="font-weight:bold;">
                <div class="flex trumpTitle">
                    <div style="">TRUMP THOUGHT WE WOULD FORGET.</div>
                </div>
                <div style="width:100%;height:0.3em;background-color:#BF1120;margin:0.6em;"></div>
                <div class="flex trumpHeadline">
                    <div style="">We didn’t forget all the times he caused us all to shake our heads at his actions since taking the highest office in the world.
Let’s refresh our memories. Then vote.</div>
                </div>
            </div>
        </div>
    </div>
    <div class="actionArea flex healthyMargins" style="">
        <button onclick="toggleModal()" class="actionItem modalButton">TAP FOR VOTER RESOURCES</button>
        <div id="ActionItems" class="flex" style="flex-direction:row; border-radius:0.5em;">
            <div class="modalMessage" style="font-size:1.4em;font-weight:bold;">Voter Resources</div>
            <div class="modalMessage" style="font-size:1.2em;margin-bottom:1em;">via Vote.org</div>
            <a href="https://www.vote.org/am-i-registered-to-vote/" class="flex actionItem" style="flex-direction:row;text-align:center;" target="_blank">
                <img src="Question.png" />
                <div class="flex">
                    <div style="font-weight:bold;">CHECK YOUR REGISTRATION</div>
                    <div>Not sure if you’re registered to vote? Check and register here.</div>
                </div>
            </a>
            <a href="https://www.vote.org/register-to-vote/" class="flex actionItem" style="flex-direction:row;text-align:center;" target="_blank">
                <img src="Check.png" />
                <div class="flex">
                    <div style="font-weight:bold;">REGISTER TO VOTE</div>
                    <div>It takes less than 2 minutes to register.</div>
                </div>
            </a>
            <a href="https://www.vote.org/absentee-ballot/" class="flex actionItem" style="flex-direction:row;text-align:center;" target="_blank">
                <img src="Plane.png" />
                <div class="flex">
                    <div style="font-weight:bold;">VOTE BY MAIL</div>
                    <div>Can't vote in person on Election Day? Request an absentee ballot.</div>
                </div>
            </a>
            <a href="https://www.vote.org/polling-place-locator/" class="flex actionItem" style="flex-direction:row;text-align:center;" target="_blank">
                <img src="Map.png" style="align-self:baseline;"/>
                <div class="flex">
                    <div style="font-weight:bold;">POLLING PLACE LOCATOR</div>
                    <div>Need to find your polling place? View the list of state polling websites.</div>
                </div>
            </a>
        </div>
    </div>
    
    <!-- Page content -->
    <div id="ArticleContainer" class="healthyMargins" style="max-width:3000px; float:left;">
        <?$escapeCounter = 1000;
        $num = 0;
        while ($num < INITIAL_NUMBER_OF_ARTICLES && $escapeCounter > 0){
            if (generateArticle(-1, false, false, true)) $num++;
            $escapeCounter--;
        }
        // while ($num < INITIAL_NUMBER_OF_ARTICLE_SLOTS){
        //     // generateArticle(-1, false, true);
        //     $num++;
        // }
        if ($debug) print_r($_SESSION["Log"]);?>
      </div>
    
    <!-- End page content -->
    </div>
    
    
    <!-- Footer -->
    <footer style="position:fixed;z-index:200;bottom:0;left:0;right:0;text-align:center;background-color:rgba(.8,.8,.8,.7);color:white;padding:0.5em;">
        <div class="socialMedia">
            <a rel="external nofollow" class="twitter" href="https://twitter.com/intent/tweet/?text=Refresh%20your%20memory%20of%20the%20thousands%20of%20head-shaking%20moments%20Trump%20created%20since%20taking%20office%20%23WeDidntForget%20%23Election2020&amp;url=https%3A%2F%2Fwedidntforget.com" target="_blank" title="Share on Twitter"><i class="fab fa-twitter"></i></a><a rel="external nofollow" class="facebook" href="https://facebook.com/sharer/sharer.php?u=https%3A%2F%2Fwedidntforget.com" target="_blank" title="Share on Facebook"><i class="fab fa-facebook-f"></i></a><a rel="external nofollow" class="email" href="mailto:?subject=Refresh%20your%20memory%20of%20the%20thousands%20of%20head-shaking%20moments%20Trump%20created%20since%20taking%20office%20%23WeDidntForget%20%23Election2020&amp;body=https%3A%2F%2Fwedidntforget.com" target="_self" title="Share using Email"><i class="far fa-envelope"></i></a><a rel="external nofollow" class="linkedin" href="https://www.linkedin.com/shareArticle?mini=true&amp;url=https%3A%2F%2Fwedidntforget.com&amp;title=Refresh%20your%20memory%20of%20the%20thousands%20of%20head-shaking%20moments%20Trump%20created%20since%20taking%20office%20%23WeDidntForget%20%23Election2020&amp;summary=Refresh%20your%20memory%20of%20the%20thousands%20of%20head-shaking%20moments%20Trump%20created%20since%20taking%20office%20%23WeDidntForget%20%23Election2020&amp;source=https%3A%2F%2Fwedidntforget.com" target="_blank" title="Share on LinkedIn"><i class="fab fa-linkedin-in"></i></a><a rel="external nofollow" class="reddit" href="https://reddit.com/submit/?url=https%3A%2F%2Fwedidntforget.com&amp;resubmit=true&amp;title=Refresh%20your%20memory%20of%20the%20thousands%20of%20head-shaking%20moments%20Trump%20created%20since%20taking%20office%20%23WeDidntForget%20%23Election2020" target="_blank" title="Share on Reddit"><i class="fab fa-reddit"></i></a><a rel="external nofollow" class="whatsapp" href="whatsapp://send?text=Refresh%20your%20memory%20of%20the%20thousands%20of%20head-shaking%20moments%20Trump%20created%20since%20taking%20office%20%23WeDidntForget%20%23Election2020%20https%3A%2F%2Fwedidntforget.com" target="_blank" title="Share on WhatsApp"><i class="fab fa-whatsapp"></i></a><a rel="external nofollow" class="vote" href="https://www.vote.org" target="_blank" title="Vote!"><i class="fab fa-blank">VOTE</i></a><!-- href="javascript:void(0)" onclick="toggleModal()"-->
        </div>
        <div class="w3-hide-large w3-hide-medium" style="width:100%;height:0.1em;margin:0.2em 0.7em;background-color:#E6E4E4;"></div>
        <div class="l6 m12 credit">
          <span>Created by: </span><a href="https://www.fitzmaro.com" title="Fitz Maro" target="_blank" style="font-weight:bold;text-decoration:none;font-size:1.3em;">Fitz Maro</a><span> + </span>
          <a href="https://www.stinsonevolutions.ca" title="Stinson Evolutions" target="_blank" class="w3-hide-large w3-hide-medium"><img src="SE-logo-white-small.png" style="width:10em;"></a>
          <a href="https://www.stinsonevolutions.ca" title="Stinson Evolutions" target="_blank" class="w3-hide-small"><img src="SE-logo-white.png" style="width:15em;"></a>
        </div>
    </footer>
    
    </body>
    <script type="text/javascript">
    
        function toggleModal(){
            //console.log('toggle');
            if (!$('#MegaModal').is(':visible')){
                $('#MegaModal').show();
                $('#ActionItems').show();
            }
            else{
                $('#MegaModal').hide();
                $('#ActionItems').hide();
            }
            //console.log(document.getElementById('MegaModal').style.display);
        }
    
        var lastScroll = 0;
        var articleHeight = 0;
        var loadingMore = true;
        var loadCount = 0;
        var updateScheduled = false;
        //var Articles = <?=json_encode($_SESSION["Articles"])?>;
        //var UsedArticles = <?=json_encode($_SESSION["UsedArticles"])?>;
        //console.log(Articles);
        //console.log(UsedArticles);
    
        $(function(){
            // start update check loop
            articleHeight = $('.article').first().height();
            //console.log(articleHeight);
            loadingMore = false;
            checkForUpdate();
        });
        
        // Refresh the specified articles with random new ones (all if null)
        // startNum inclusive, endNum exclusive (where num = order in DOM)
        function refreshArticles(startNum, endNum){
        	// allow null/undefined for any parameter, specifying defaults if no value provided
        	startNum = typeof startNum !== 'undefined' && startNum != null && startNum > 0 ? startNum : 0;
        	endNum = typeof endNum !== 'undefined' && endNum != null && endNum > startNum ? endNum : Number.MAX_SAFE_INTEGER;
            $(".article").each(function(num){
                //console.log('a');
                if (num >= startNum && num < endNum){
                    var id = $(this).attr('id');
                    //console.log('b: '+id);
                    // var idVal = id.substr(id.indexOf('_')+1);
                    // console.log(id);
                    var newID = -1, tempID = -1, escapeCounter = 5000;
                    while (newID < 0 && escapeCounter > 0){
                        escapeCounter--;
                        tempID = Math.floor(Math.random() * Object.keys(Articles).length);
                        //console.log(Object.keys(Articles).length);
                        if (!(tempID in UsedArticles)){
                            newID = tempID;
                            UsedArticles[tempID] = Articles[tempID];
                            AddSession('UsedArticles', tempID, Articles[tempID]);
                        }
                    }
                    //console.log(newID);
                    if (newID > 0){
                        var article = Articles[tempID];
                        //console.log($(this));
                        $(this).attr('id', 'Article_'+newID);
                        $(this).find('.articleURL').first().attr("href", article[2]);
                        $(this).find('.articleTitle').first().html(article[1]);
                        $(this).find('.articleImage').first().attr("src", article[3]);
                        $(this).find('.articleImage').first().attr("alt", article[0]);
                    }
                }
            });
        }
        function SetSession(sessionsArray, callback){
        	$.ajax({        
               type: "POST",
               data: {'SetSession':1, ...sessionsArray},
               success: callback
            });
        }
        function AddSession(sessionName, sessionKey, sessionValue, callback){
        	$.ajax({        
               type: "POST",
               data: {
                   AddSession: 1,
                   SessionName: sessionName,
                   SessionKey: sessionKey,
                   SessionValue: sessionValue
               },
               success: callback
            });
        }
        
        function loadMoreArticles(num){
            //console.log('loading start!');
            $.ajax({
		       	type: "POST",
		       	data: {
			       LoadArticles: num
				},
				success: function(data){
                    if (data != null && data != ''){
                        $("#ArticleContainer").append(data);
                    }
                    loadCount+=num;
                }
		    });
            // setTimeout(function(){
            //     loadCount++;
            // },1000);
        }
        
        function checkForUpdate(){
            // check for when loading has finished
            if (loadingMore){
                if (loadCount >= <?=ARTICLE_UPDATE_AMOUNT?>){
                    loadingMore = false;
                }
            }
            // check if we want to load more now
            if (!loadingMore && updateScheduled){
                updateScheduled = false;
                loadingMore = true;
                loadCount = 0;
                loadMoreArticles(4);
            }
            setTimeout(function(){
                checkForUpdate();
            }, 200);
            // console.log(loadingMore + ' - ' + loadCount + ' - ' + updateScheduled);
        }
        
        $(window).scroll(function() {
            // console.log($(window).scrollTop() + $(window).height());
            // console.log($(document).height() - articleHeight * <?=ARTICLE_UPDATE_AMOUNT?>);
            // if scrolling downwards and near bottom of page, request an update
            if($(window).scrollTop() > lastScroll
                && $(window).scrollTop() + $(window).height() >= $(document).height() - articleHeight * <?=ARTICLE_UPDATE_AMOUNT?> - 5) {
                updateScheduled = true;
                // console.log("what gives?");
            }
            lastScroll = $(window).scrollTop();
        });
        
    </script>
    </html><?
}

// search for a random, unused article (to be safe, break after x tries)
function getRandomArticleID(){
    loadArticles();
    $id = -1;
    $numAttempts = 5000;
    while($numAttempts > 0 && $id < 0){
        $tempID = array_keys($_SESSION["Articles"])[random_int(0, count($_SESSION["Articles"])-1)];
        if (!array_key_exists($tempID, $_SESSION["UsedArticles"])){
            $id = $tempID;
            break;
        }
        $numAttempts--;
    }
    return $id;
}

// Source: https://stackoverflow.com/a/52218834
function getSiteOG( $url, $specificTags=0 ){
    $doc = new DOMDocument();
    @$doc->loadHTML('<?xml encoding="utf-8"?>'.file_get_contents($url));
    $res['title'] = $doc->getElementsByTagName('title')->item(0)->nodeValue;

    foreach ($doc->getElementsByTagName('meta') as $m){
        $tag = $m->getAttribute('name') ?: $m->getAttribute('property');
        if(in_array($tag,['description','keywords']) || strpos($tag,'og:')===0) $res[str_replace('twitter:','',str_replace('og:','',$tag))] = $m->getAttribute('content');
    }
    return $specificTags? array_intersect_key( $res, array_flip($specificTags) ) : $res;
}

function generateArticle($id = -1, $skipContainer = false, $onlyContainer = false){
    if ($id < 0) $id = getRandomArticleID();
    $article = $_SESSION["Articles"][$id];
    
    if (!empty($article)){
        $name = $article[0];
        $title = $article[1];
        $url = $article[2];
        $image = $article[3];
    }
    if (!empty($article) || $onlyContainer){
        if (!$skipContainer || $onlyContainer){?>
        <div id="Article_<?=$id?>" class="article w3-col l6 m12"><?
        }
        if (!$onlyContainer){?>
          <a class="articleURL" href="<?=$url?>" target="_blank">
              <div class="w3-display-container">
                <div class="articleAccent"></div>
                <div class="articleTitle"><?=htmlentities($title, ENT_QUOTES)?></div>
                <img class="articleImage" src="<?=$image?>" alt="<?=htmlentities($name, ENT_QUOTES)?>">
              </div>
          </a><?
          $_SESSION["UsedArticles"][$id] = $article;
        }
        if (!$skipContainer || $onlyContainer){?>
        </div><?
        }
        return true;
    }
    return false;
}

function getClient(){
    putenv('GOOGLE_APPLICATION_CREDENTIALS=fitz-1600288468840-01e8e722e842.json');
    $client = new Google_Client();
    $client->useApplicationDefaultCredentials();
    $client->addScope(Google_Service_Sheets::SPREADSHEETS_READONLY);
    // $client->addScope(Google_Service_Sheets::SPREADSHEETS);
    $client->setAccessType('offline');
    return $client;
}

function loadArticles(){
    global $client, $servername, $database, $username, $password;
    
    if (empty($_SESSION["UsedArticles"])) $_SESSION["UsedArticles"] = array();
    if (empty($_SESSION["BadURLs"])) $_SESSION["BadURLs"] = array();
    
    // load initial values from db
    if (empty($_SESSION["Articles"])){
        $_SESSION["Articles"] = array();
        $pdo = new PDO("mysql:host=$servername;dbname=$database;charset=utf8", $username, $password);
        $rows = $pdo->query("SELECT * FROM wtf_articles")->fetchAll();
        foreach ($rows as $row) {
            $_SESSION["Articles"][$row['id']] = array($row['outlet'], $row['title'], $row['url'], $row['image']);
        }
    }
}

function updateArticles($updateDB = false, $startRow = 2, $numRows = 4000){
    global $client;
    $_SESSION["AllArticleURLs"] = array();
    if (empty($_SESSION["BadURLs"])) $_SESSION["BadURLs"] = array();

    $sheets = new Google_Service_Sheets($client);
    // $spreadsheetId = "1Nzjgpi_dcIaADbEy4p3wXiNwwsW3NryrKH9z4_elo2w";
    $spreadsheetId = "1J81UKLpoNngdREocH-MtqGS0ZGpGXOWGO-B6eHR5CJA";
    $range = "Sheet1!A".$startRow.":G".($startRow+$numRows);
    $rows = $sheets->spreadsheets_values->get($spreadsheetId, $range, ['majorDimension' => 'ROWS']);
    $values = array_reverse($rows->getValues());
    
    if (empty($values)) {
        print "No data found.\n";
        exit;
    } else {
        foreach ($values as $row) {
            $rowNum = $row[0];
            $rowSummary = $row[1];
            $rowURL = $row[4];
            $rowDomain = $row[6];
            if ($rowNum && !empty($rowURL) && !in_array($rowURL, $_SESSION["BadURLs"])){
                $_SESSION["AllArticleURLs"][$rowNum] = array($rowDomain, $rowURL, $rowSummary);
                // if specified, grab metadata and add db entry if needed
                if ($updateDB) updateArticle($rowNum);
            }
        }
    }
    // print_r($_SESSION["AllArticleURLs"]);
    // exit;
}

// Search our Articles list for a match to the specified Sheets row and add new db entry if we don't already have it
// Assumes $_SESSION["Articles"] contains all current db entries.
// Returns true if we just added a new row, or false if no insert needed.
function updateArticle($num){
    $isSuccess = false;
    loadArticles();
    
    // for given url, brute force search existing Articles and insert grabbed metadata into db if no match
    $domain = $_SESSION["AllArticleURLs"][$num][0];
    $url = $_SESSION["AllArticleURLs"][$num][1];
    $summary = $_SESSION["AllArticleURLs"][$num][2];
    $foundMatch = false;
    foreach($_SESSION["Articles"] as $id=>$ExistingArticle){
        if (stripos($url, $ExistingArticle[2]) === 0){
            $foundMatch = true;
            break;
        }
    }
    if (!$foundMatch){
        /* Option 1: page parsing, grab og details */
        // $graph = OpenGraph::fetch($_SESSION["AllArticleURLs"][$num]);
        // if (empty($graph)){
        //     $_SESSION["BadURLs"][$num] = $_SESSION["AllArticleURLs"][$num];
        // }
        // else{
        //     foreach ($graph as $key => $value) {
        //         if ($key == "site_name") $name = $value;
        //         if ($key == "title") $title = $value;
        //         if ($key == "description") $description = $value;
        //         if ($key == "url") $url = $value;
        //         if ($key == "image") $image = $value;
        //     }
            // $image_src = $graph["image_src"];
            // $locale = $graph["locale"];
            // $type = $graph["type"];
        // }
        
        /* Option 2: og parsing with meta tags fallback */
        $tags = getSiteOG($url);
        $name = $tags['site_name'];
        $title = $tags['title'];
        $description = $tags['description'];
        // $name = utf8_decode($tags['site_name']);
        // $title = utf8_decode($tags['title']);
        // $description = utf8_decode($tags['description']);
        // $url = $tags['url'];
        $image = $tags['image'];
        
        /* Option 3: grab meta tags quickly (ie. twitter tags basically) */
        // $tags = get_meta_tags($_SESSION["AllArticleURLs"][$num][1]);
        // $name = $tags['twitter:site'];
        // if (empty($name)) $name = $tags['twitter:app:name:googleplay'];
        // $title = $tags['twitter:title'];
        // if (empty($title)) $title = $description;
        // $description = $tags['twitter:description'];
        // if (empty($description)) $description = $tags['description'];
        // $url = $tags['url'];
        // if (empty($url)) $url = $tags['twitter:domain'];
        // $image = $tags['twitter:image'];
        // $date = $tags['date'];
        
        if (empty($title)){
            if (!empty($summary)) $title = $summary;
            else if (!empty($description)) $title = $description;
        }
        if (empty($description)){
            if (!empty($title)) $description = $title;
            else if (!empty($summary)) $description = $summary;
        }
        
        if (!empty($title) && !empty($url) && !empty($image)){
            $id = saveArticleToDB($num, $name, $title, $url, $image, $domain, $summary);
            if ($id !== false){
                $isSuccess = true;
                $_SESSION["Articles"][$id] = array($name, $title, $url, $image, $domain, $summary);
            }
        }
        if (!$isSuccess){
            array_push($_SESSION["BadURLs"], $url);
        }
    }
    return $isSuccess;
}

function saveArticleToDB($num, $name, $title, $url, $image, $domain, $summary){
    global $servername, $database, $username, $password;
    $pdo = new PDO("mysql:host=$servername;dbname=$database;charset=utf8", $username, $password);
    $stmt = $pdo->prepare("INSERT INTO wtf_articles (id,num,outlet,title,url,image,domain,summary) SELECT NULL,?,?,?,?,?,?,? FROM (SELECT 1) sub WHERE NOT EXISTS (SELECT 1 FROM wtf_articles WHERE url = ?) LIMIT 1");
    // $stmt = $pdo->prepare("INSERT INTO wtf_articles (id,num,outlet,title,url,image) VALUES (NULL,?,?,?,?,?) ON DUPLICATE KEY UPDATE num = VALUES(num), outlet = VALUES(outlet), title = VALUES(title), url = VALUES(url), image = VALUES(image)");
    $stmt->execute(array($num, $name, $title, $url, $image, $domain, $summary, $url));
    // print_r($stmt->queryString);
    // print_r(array($id, $num, $name, $title, $url, $image, $domain, $summary, $url));
    // print utf8_encode($title);
    // print '<br/>';
    // print_r($pdo->errorInfo());
    // exit;
    $result = $stmt->closeCursor();
    return $pdo->lastInsertId();
}

// function getClient_OLD(){
//     /* Note: see here for setup instructions used as base for below:
//     https://github.com/googleapis/google-api-php-client */
//     $client = new Google_Client();
//     $client->setAuthConfig('config.json');
//     // $client->setAuthConfig('client_secret_223874304558-p7n3fq04aai0reqfaaql8p1d49rk86rk.apps.googleusercontent.com.json');
//     // $client->addScope('https://www.googleapis.com/auth/spreadsheets');
//     $client->setScopes(Google_Service_Sheets::SPREADSHEETS);
//     $client->setAccessType('offline');
    
//     if (isset($_GET['code'])) {
//         $_SESSION["GToken"] = $client->fetchAccessTokenWithAuthCode($_GET['code']);
//         header('Location: ' . 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
//         // print 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
//         // exit;
//     }
//     else if (empty($_SESSION["GToken"])){
//         // Your redirect URI can be any registered URI, but in this example
//         // we redirect back to this same page
//         $redirect_uri = 'https://stinsonevolutions.ca/TrumpsWTFs/';
//         $client->setRedirectUri($redirect_uri);
    
//         $auth_url = $client->createAuthUrl();
//         header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
//     }
//     else{
//         $client->setAccessToken($_SESSION["GToken"]);
//     }
    
//     return $client;
// }