<?php

defined('APP_NAME') or die(header('HTTP/1.0 403 Forbidden'));

/*
* @author Balaji
* @name: Rainbow PHP Framework
* @copyright © 2017 ProThemes.Biz
*
*/

//Default Page Title
$pageTitle = $lang['2']; //'Blog';
$des = $keyword = '';

function getBlogPosts($con, $offset, $per_page){
    $row = mysqliPreparedQuery($con, "select * from blog_content WHERE post_enable='on' ORDER BY id *1 DESC LIMIT ?, ?",'ss',array($offset,$per_page),false); 
    return $row;
}

function getBlogPostsCat($con, $offset, $per_page, $categoryName){
    $row = mysqliPreparedQuery($con, "select * from blog_content WHERE category=? AND post_enable='on' ORDER BY id *1 DESC LIMIT ?, ?",'sss',array($categoryName,$offset,$per_page),false); 
    return $row;
}

function getBlogRelatedPosts($con, $baseURL, $no_image_path, $blogPostID, $count=4){
    $relatedBlogPosts = '';
    $result = mysqli_query($con, "SELECT * FROM blog_content WHERE post_enable='on' ORDER BY RAND() LIMIT ". $count);
    while ($row = mysqli_fetch_array($result)) {
        if($blogPostID != $row['id']){
            $postTitle = truncate($row['post_title'],10,20);
            $featuredImage = trim($row['featured_image']) == '' ? $no_image_path: trim($row['featured_image']);
            if(filter_var($row['post_enable'], FILTER_VALIDATE_BOOLEAN)){
                $relatedBlogPosts .= '<div class="col-md-3 relatedPostsHead">
                <div class="thumbnail"> 
                <a href="'.createLink('blog/'.$row['post_url'],true).'"><img alt="'.$row['post_title'].'" src="'. $baseURL. 'core/library/imagethumb.php?w=180&=180&src='.$featuredImage .'" class=""><div class="relTitle">'.$postTitle.'</div></a> 
                </div>
               </div>';
            }
        }
    }
    return $relatedBlogPosts;
}

//Load Blog Settings
$result = mysqli_query($con, "SELECT * FROM blog where id='1'");
$row = mysqli_fetch_array($result);
$des = shortCodeFilter($row['meta_des']);
$keyword = shortCodeFilter($row['meta_tags']);
$per_page = (int)Trim($row['maximum_posts']);
$post_length = (int)Trim($row['truncate']);
$no_image_path = $row['no_image'];
$default_posted_by = shortCodeFilter($row['posted_by']);
$discuss_id = htmlspecialchars_decode($row['discuss_id']);
$showComment = filter_var($row['show_comment'], FILTER_VALIDATE_BOOLEAN);
$showRelated = filter_var($row['show_related'], FILTER_VALIDATE_BOOLEAN);
$blogEnable = filter_var($row['blog_enable'], FILTER_VALIDATE_BOOLEAN);
$relatedArr = dbStrToArr($row['related_data']);
$enable_related = filter_var($relatedArr[0], FILTER_VALIDATE_BOOLEAN); 
$related_count = $relatedArr[1];

if(!$blogEnable){
    header('Location: '. createLink('',true));
    echo '<meta http-equiv="refresh" content="1;url='.createLink('',true).'">';
    die();
}

$blogPosts = false;   

if($pointOut == ''){
   //No Blog URL Found

   $blogPosts = true; 
      
   $resVal = mysqli_query($con, "SELECT * FROM blog_content WHERE post_enable='on'");
   $totalrecords = mysqli_num_rows($resVal);
   if (isset($_GET['page'])){
        $pagenumber = intval($_GET['page']);
        $page = $pagenumber -1;
   }else{
        $pagenumber = '1';
        $page = 0;
   }
   $offset = $per_page * $page;
   
   $page_url = createLink('blog',true);
   $page_p_url = createLink('blog&page=[p]',true);
   
   $rsd = getBlogPosts($con,$offset,$per_page);
   
}elseif($pointOut == 'category'){
    //Blog Category Found
    
    $blogPosts = true; 
    $routePath = escapeTrim($con,$args[0]); 
    $categoryName = $routePath;
    
    if($categoryName == '' || $categoryName == null){
        header('Location: '. createLink('blog',true));
        echo '<meta http-equiv="refresh" content="1;url='.createLink('blog',true).'">';
        die();
    }
    
    $row = mysqliPreparedQuery($con, "SELECT * FROM blog_content where category=? AND post_enable='on'",'s',array($categoryName),false); 
    $totalrecords = count($row);
              
    if (isset($_GET['page'])){
        $pagenumber = intval($_GET['page']);
        $page = $pagenumber -1;
    }else{
        $pagenumber = '1';
        $page = 0;
    }
    $offset = $per_page * $page;
   
    $page_url = createLink('blog/category/'.$categoryName,true);
    $page_p_url = createLink('blog/category/'.$categoryName.'&page=[p]'.$categoryName,true);
   
    $categoryName = str_replace('-',' ',$categoryName);
    $pageTitle = ucwords($categoryName);
    
    $rsd = getBlogPostsCat($con,$offset,$per_page,$categoryName);
    
} else{
    //Blog URL Found

    $data = mysqliPreparedQuery($con, "SELECT * FROM blog_content WHERE post_url=?",'s',array($pointOut));  

    if($data !== false){
        $blogPostID = $data['id'];
        $discuss_id = str_replace(array('PAGE_URL','PAGE_IDENTIFIER'), array("'".$currentLink."'", "'".$blogPostID."'"), $discuss_id);
        $post_title = shortCodeFilter($data['post_title']);
        $posted_by = shortCodeFilter($data['posted_by']);
        $posted_date = $data['date'];
        $category = shortCodeFilter($data['category']);
        $featured_image = $data['featured_image'];
        $meta_des = shortCodeFilter($data['meta_des']);
        $meta_tags = shortCodeFilter($data['meta_tags']);
        $post_url = $data['post_url'];
        $blogpageview = (int)trim($data['pageview']);
        $post_allow_comment = filter_var($data['allow_comment'], FILTER_VALIDATE_BOOLEAN);
        $post_enable = filter_var($data['post_enable'], FILTER_VALIDATE_BOOLEAN);
        $post_content = shortCodeFilter(htmlspecialchars_decode($data['post_content']));
        $controller = 'blog_view';
       
        if($data['access'] == 'registered'){
            if(!isset($_SESSION['username']))
                $post_enable = false;
        }
        
        if($data['lang'] != 'all' && $data['lang'] != ACTIVE_LANG)
            $post_enable = false;
            
        if(!$post_enable){
            require_once (CON_DIR . 'error.php');
        }else{
            $blogpageview = $blogpageview+1;    
            updateToDbPrepared($con,'blog_content', array('pageview' => $blogpageview), array('id' => $blogPostID));
            
            if($enable_related)
                $relatedBlogPosts = getBlogRelatedPosts($con, $baseURL, $no_image_path, $blogPostID, $related_count);            
        }
    } else {
        require_once (CON_DIR . 'error.php');
    }
    
    $posted_date_raw = date_create($posted_date);
    $post_month = date_format($posted_date_raw,'M');
    $post_day = date_format($posted_date_raw,'j');
    
    $pageTitle = $post_title;
    $des = $meta_des;
    $keyword = $meta_tags;
}

if($blogPosts){
    $pg = new blogPagination();
    $pg->pagenumber = $pagenumber;
    $pg->pagesize = $per_page;
    $pg->totalrecords = $totalrecords;
    $pg->showfirst = true;
    $pg->showlast = true;
    $pg->paginationcss = 'pagination-normal';
    $pg->paginationstyle = 0;
    $pg->defaultUrl = $page_url;
    $pg->paginationUrl = $page_p_url;
}

?>