<?php

/**
 * The public-facing functionality of the plugin.
 *
 * @link       http://wordpress-print-posts.db-dzine.de
 * @since      1.0.0
 *
 * @package    WordPress_Print_Posts
 * @subpackage WordPress_Print_Posts/public
 */

/**
 * The public-facing functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    WordPress_Print_Posts
 * @subpackage WordPress_Print_Posts/public
 * @author     Daniel Barenkamp <contact@db-dzine.de>
 */
class WordPress_Print_Posts_Public {

	/**
	 * The ID of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $plugin_name    The ID of this plugin.
	 */
	private $plugin_name;

	/**
	 * The version of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $version    The current version of this plugin.
	 */
	private $version;

	/**
	 * options of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      array    $options
	 */
	private $options;

	/**
	 * Post URL
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $post_url
	 */
	private $post_url;

	/**
	 * Post
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      object    $post
	 */
	private $post;

	/**
	 * Data
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      mixed    $data
	 */
	private $data;

	/**
	 * Initialize the class and set its properties.
	 *
	 * @since    1.0.0
	 * @param      string    $plugin_name       The name of the plugin.
	 * @param      string    $version    The version of this plugin.
	 */
	public function __construct( $plugin_name, $version ) 
	{

		$this->plugin_name = $plugin_name;
		$this->version = $version;
		$this->data = new stdClass;

	}

	/**
	 * Register the stylesheets for the public-facing side of the site.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_styles() 
	{

		global $wordpress_print_posts_options;

		$this->options = $wordpress_print_posts_options;

		wp_enqueue_style( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'css/wordpress-print-posts-public.css', array(), $this->version, 'all' );
		wp_enqueue_style( 'font-awesome', plugin_dir_url( __FILE__ ) . 'css/font-awesome-4.7.0/css/font-awesome.min.css', array(), '4.7.0', 'all' );
		
	}

	/**
	 * Register the JavaScript for the public-facing side of the site.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_scripts() 
	{

		global $wordpress_print_posts_options;

		$this->options = $wordpress_print_posts_options;

		$customJS = $this->get_option('customJS');
		if(empty($customJS))
		{
			return false;
		}

		file_put_contents( dirname(__FILE__)  . '/js/wordpress-print-posts-custom.js', $customJS);

		wp_enqueue_script( $this->plugin_name.'-custom', plugin_dir_url( __FILE__ ) . 'js/wordpress-print-posts-custom.js', array( 'jquery' ), $this->version, true );
	}

	/**
	 * Gets options
	 *
	 * @since    1.0.0
	 */
    private function get_option($option)
    {
    	if(!is_array($this->options)) {
    		return false;
    	}
    	
    	if(!array_key_exists($option, $this->options))
    	{
    		return false;
    	}
    	return $this->options[$option];
    }
	
	/**
	 * Inits the print posts
	 *
	 * @since    1.0.0
	 */
    public function initWordPress_Print_Posts()
    {

		global $wordpress_print_posts_options;

		$this->options = $wordpress_print_posts_options;

		if (!$this->get_option('enable'))
		{
			return false;
		}

		// Enable User check
		if($this->get_option('enableLimitAccess'))
		{
			$roles = $this->get_option('role');
			if(empty($roles)) {
				$roles[] = 'administrator';
			}

			$currentUserRole = $this->get_user_role();

			if(!in_array($currentUserRole, $roles))
			{
				return FALSE;
			}
		}

		$actual_link = 'http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://' . "{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";

		if( strpos($actual_link, '?') === FALSE ){ 
			$this->post_url = $actual_link . '?';
		} else {
		 	$this->post_url = $actual_link . '&';
		}

		$iconPosition = $this->get_option('iconPosition');

		switch ($iconPosition) {
			case 'before_content':
				add_filter( 'the_content', array($this, 'show_before'), 90);
				break;
			case 'after_content':
				add_filter( 'the_content', array($this, 'show_after'), 90);
				break;
			default:
				break;
		}

		add_action( $iconPosition, array($this, 'show_print_links'), 90 );

		if(isset($_GET['print-posts']))
		{
			add_action("wp", array($this, 'watch'));
		}
    }

	public function register_widget()
	{
		register_widget( 'WordPress_Print_Posts_Widget' );
	}

    public function show_before($content, $id = null)
    {
    	$queried_object = get_queried_object();
    	$queried_id = $queried_object->ID;

    	if( ($id !== null) && ($id !== $queried_id)) {
    		return $content;
    	}

    	if( (is_single() || is_page()) && !is_singular('product') ) {
    		$content = $this->show_print_links()  . $content;
    	}

    	return $content;
    }

    public function show_after($content, $id = null) 
    {    	
    	$queried_object = get_queried_object();
    	$queried_id = $queried_object->ID;

    	if( ($id !== null) && ($id !== $queried_id)) {
    		return $content;
    	}

    	if(is_single()) {
    		$content = $content . $this->show_print_links();
    	}

    	return $content;
    }

    public function show_print_links()
    {
    	global $post;

    	$apply = true;

		$excludePostCategories = $this->get_option('excludePostCategories');
		if(!empty($excludePostCategories)) 
		{
			if($this->excludePostCategories()) {
				$apply = false;
			}
		}

		$excludePosts = $this->get_option('excludePosts');
		if(!empty($excludePosts)) 
		{

			if($this->excludePosts()) {
				$apply = false;
			}
		}

		$iconPostTypes = $this->get_option('iconPostTypes');
		if(!in_array($post->post_type, $iconPostTypes)) {
			$apply = false;
		}

		if(!$apply) {
			return false;
		}

    	$html = '<div class="wordpress-print-posts link-wrapper">';

    	if($this->get_option('iconDisplay') == "horizontal") {
    		$html .= $this->get_pdf_link();
    		$html .= $this->get_word_link();
    		$html .= $this->get_print_link();
    	}
    	if($this->get_option('iconDisplay') == "vertical") {
    		$html .= '<ul class="fa-ul">';
    		
			  $html .= '<li>' . $this->get_pdf_link() .'</li>';
			  $html .= '<li>' . $this->get_word_link() .'</li>';
			  $html .= '<li>' . $this->get_print_link() .'</li>';
			$html .= '</ul>';
		}
    	
    	$html .= '</div>';
    	return $html;
    }

    public function show_print_links_shortcode($atts = array())
    {
        $args = shortcode_atts(array(
            'post' => '',
            'pdf' => 'yes',
            'word' => 'yes',
            'print' => 'yes',
        ), $atts);

        if(!empty($args['post'])) {
        	$post_url = get_permalink($args['post']);
        	if(!empty($post_url)) {
        		$this->post_url = $post_url . '?';
        	}
        }
        $showPDF = $args['pdf'];
        $showWord = $args['word'];
        $showPrint = $args['print'];
        

    	$html = '<div class="wordpress-print-posts link-wrapper">';

    	if($this->get_option('iconDisplay') == "horizontal") {
    		if($showPDF == "yes") {
    			$html .= $this->get_pdf_link(true);
    		}
    		if($showWord == "yes") {
    			$html .= $this->get_word_link(true);
			}
			if($showPrint == "yes") {
    			$html .= $this->get_print_link(true);
			}
    	}
    	if($this->get_option('iconDisplay') == "vertical") {
    		$html .= '<ul class="fa-ul">';
    		if($showPDF == "yes") {
					$html .= '<li>' . $this->get_pdf_link(true) .'</li>';
				}
				if($showWord == "yes") {
					$html .= '<li>' . $this->get_word_link(true) .'</li>';
				}
				if($showPrint == "yes") {
					$html .= '<li>' . $this->get_print_link(true) .'</li>';
				}
			$html .= '</ul>';
		}
    	
    	$html .= '</div>';

    	return $html;
	}

    private function get_pdf_link($shortcode = false)
    {
    	if((!$this->get_option('enablePDF')) && $shortcode == false) return FALSE;
    	
    	return '<a href="'.$this->post_url.'print-posts=pdf'.'" target="_blank"><i class="fa fa-file-pdf-o ' . $this->get_option('iconSize') . '"></i></a>';
    }

    private function get_word_link($shortcode = false)
    {
    	if(!$this->get_option('enableWord') && $shortcode == false) return FALSE;

    	return '<a href="'.$this->post_url.'print-posts=word'.'" target="_blank"><i class="fa fa-file-word-o ' . $this->get_option('iconSize') . '"></i></a>';
    }

    private function get_print_link($shortcode = false)
    {
    	if(!$this->get_option('enablePrint') && $shortcode == false) return FALSE;

    	return '<a href="#"
    	onclick="print(); return false;" target="_blank"><i class="fa fa-print ' . $this->get_option('iconSize') . '"></i></a>
    	<script>
			function print() {
				var w = window.open("'.$this->post_url.'print-posts=print");
			}
    	</script>';
    }

    public function watch()
    {
    	$this->setup_data();

		if($_GET['print-posts'] == "pdf")
		{
			try {
				$this->init_pdf();
	    	} catch (Exception $e) {
	    		echo $e->getMessage();
	    		die();
	    	}
		}
		if($_GET['print-posts'] == "word")
		{
			$this->init_word();
		}
		if($_GET['print-posts'] == "print")
		{
			$this->init_print();
		}
	}

	public function setup_data()
	{
    	global $post, $wpdb;

    	// default Variables
		$this->data->blog_name = get_bloginfo('name');
		$this->data->blog_description  = get_bloginfo('description');

		$this->data->ID = $post->ID;
		$this->post = $post;

		$this->data->post_author = $this->post->post_author;
		$this->data->post_date = $this->post->post_date;

		// post variables
		$this->data->title = apply_filters('wordpress_print_posts_title', $this->post->post_title);
		$this->data->short_description = do_shortcode($this->post->post_excerpt);
		if($this->get_option('showExcerptStripImages')) {
			$this->post->post_excerpt = preg_replace("/<img[^>]+\>/i", "", $this->post->post_excerpt); 	
		}

		$this->data->cat_count =  get_the_terms( $this->data->ID, 'category' );
		if(!empty($this->data->cat_count)) {
			$this->data->cat_count = count($this->data->cat_count);
		}

		$this->data->tag_count = get_the_tags( $this->data->ID );
		if(!empty($this->data->tag_count)) {
			$this->data->tag_count = count($this->data->tag_count);
		}

		// Description
		if(class_exists('WPBMap') && $this->get_option('visualComposerSupport')) {
			WPBMap::addAllMappedShortcodes();
		}

		$this->data->description = str_replace("/></p>\n<p>", '/>', wpautop( do_shortcode($this->post->post_content) ) );
		if($this->get_option('showDescriptionStripImages')) {
			$this->post->description = preg_replace("/<img[^>]+\>/i", "", $this->post->description); 	
		}

		$this->data->categories = get_the_term_list( $this->data->ID, 'category', '<b>' . _n( 'Category:', 'Categories:', $this->data->cat_count, 'wordpress-print-posts' ) . '</b> ', ', ', '' );
		$this->data->tags = get_the_tag_list( '<b>' . _n( 'Tag:', 'Tags:', $this->data->tag_count, 'wordpress-print-posts' ) . '</b> ', ', ', '', $this->data->ID);

		if ( has_post_thumbnail($this->post->ID)) { 
			$thumbnail = wp_get_attachment_image_src( get_post_thumbnail_id($this->post->ID), 'shop_single' ); 
			$this->data->src = $thumbnail[0];
		} else { 
			$this->data->src = plugin_dir_url( __FILE__ ) . 'img/placeholder.png';
		}

	    $sql = "SELECT DISTINCT meta_key
                    FROM " . $wpdb->postmeta . "
                    INNER JOIN  " . $wpdb->posts . " 
                    ON post_id = ID
                    WHERE post_type <> 'product' AND post_type <> 'product_variation'
                    ORDER BY meta_key ASC";

	    $meta_keys = (array) $wpdb->get_results( $sql, 'ARRAY_A' );
	    $meta_keys_to_exclude = array('_crosssell_ids', '_children', '_default_attributes', '_height', '_length', '_max_price_variation_id', '_max_regular_price_variation_id', '_max_sale_price_variation_id', '_max_variation_price', '_max_variation_regular_price', '_max_variation_sale_price', '_min_price_variation_id', '_min_regular_price_variation_id', '_min_sale_price_variation_id', '_min_variation_price', '_min_variation_regular_price', '_min_variation_sale_price', '_price', '_post_attributes', '_post_image_gallery', '_sku', '_regular_price', '_sale_price', '_sale_price_dates_from', '_sale_price_dates_to', '_sku', '_upsell_ids', '_thumbnail_id', '_weight', '_width');

	    $temp = array();
	    foreach ($meta_keys as $key => $meta_key) {
	        $meta_key = preg_replace('/[^\w-]/', '', $meta_key['meta_key']);

	        if(in_array($meta_key, $meta_keys_to_exclude) || (substr( $meta_key, 0, 7 ) === "_oembed") || (!$this->get_option('showCustomMetaKey_' . $meta_key)) ) {
	            continue;
	        }
	        
	        $temp[] = array (
	        	'key' => $meta_key,
	        	'before' => $this->get_option('showCustomMetaKeyText_' . $meta_key),
	        	'value' => get_post_meta( $this->data->ID, $meta_key, true),
        	);

	    }

	    $this->data->meta_keys = $temp;

		return TRUE;
	}

    public function init_pdf()
    {
    	if(!class_exists('\Mpdf\Mpdf')) return FALSE;

		require_once(plugin_dir_path( dirname( __FILE__ ) ) . 'fonts/customFonts.php');

    	$headerTopMargin = $this->get_option('headerTopMargin');
    	$footerTopMargin = $this->get_option('footerTopMargin');

		$defaultFontConfig = (new Mpdf\Config\FontVariables())->getDefaults();
		$fontData = $defaultFontConfig['fontdata'];

		$mpdfConfig = array(
			'mode' => 'utf-8', 
			'format' => 'A4',    // format - A4, for example, default ''
			'default_font_size' => 0,     // font size - default 0
			'default_font' => '',    // default font family
			'margin_left' => 0,    	// 15 margin_left
			'margin_right' => 0,    	// 15 margin right
			'margin_top' => $headerTopMargin,     // 16 margin top
			'margin_bottom' => $footerTopMargin,    	// margin bottom
			'margin_header' => 0,     // 9 margin header
			'margin_footer' => 0,     // 9 margin footer
			'orientation' => 'P',  	// L - landscape, P - portrait
			'tempDir' => dirname( __FILE__ ) . '/../cache/',
			'tempDir' => plugin_dir_path( dirname( __FILE__ ) ) . 'cache/',
			'fontDir' => array(
				plugin_dir_path( dirname( __FILE__ ) ) . 'vendor/mpdf/mpdf/ttfonts/',
				plugin_dir_path( dirname( __FILE__ ) ) . 'fonts/',
			),
		    'fontdata' => array_merge($fontData, $customFonts),
		);
		$mpdf = new \Mpdf\Mpdf($mpdfConfig);	
		
		if($this->get_option('debugMPDF')) {
			$mpdf->debug = true;
			$mpdf->debugfonts = true;
			$mpdf->showImageErrors = true;
		}

		$css = $this->build_CSS();

		if($this->get_option('enableHeader'))
		{
			$header = $this->get_header();
			$mpdf->SetHTMLHeader($header);
		}

		if($this->get_option('enableFooter'))
		{
			$footer = $this->get_footer();
			$mpdf->SetHTMLFooter($footer);
		}

		$layout = $this->get_option('layout');
		$order = $this->get_option('informationOrder');
		$enabledBlocks = $order['enabled'];
		unset($enabledBlocks['placebo']);

		if($layout == 1)
		{
			$html = $this->get_first_layout();
		}
		if($layout == 2)
		{
			$html = $this->get_second_layout();
		}

		$skipNextPagebreak = false;
		foreach ($enabledBlocks as $key => $value) {
			$temp = explode('-', $key);
			$block = $temp[0];

			if($block == "pagebreak" && $skipNextPagebreak == true){
				$skipNextPagebreak = false;
				continue;
			} else {
				$skipNextPagebreak = false;
			}

			$func = 'get_'.$block;
			
			$return = call_user_func(array($this, $func));
			if($return === false){
				$skipNextPagebreak = true;
			} else {
				$html .= $return;
			}

		}

		$filename = $this->escape_filename($this->data->title);

		if($this->get_option('debugMode')) {
			echo $header;
			echo $css.$html;
			echo $footer;
			die();
		}

		$html = apply_filters('wordpress_print_posts_html', $html, $this->data);

		$mpdf->useAdobeCJK = true;
		$mpdf->autoScriptToLang = true;
		$mpdf->autoLangToFont = true;
		$mpdf->WriteHTML($css.$html);

		$dest = 'I';
		if($this->get_option('PDFDownload')) {
			$dest = 'D';
		}

		$mpdf->Output($filename.'.pdf', $dest);
		exit;
    }

    public function init_word()
    {
		global $post;

		$css = $this->build_CSS();

		if($this->get_option('enableHeader'))
		{
			$header = $this->get_header();
		}

		if($this->get_option('enableFooter'))
		{
			$footer = $this->get_footer();
		}

		$layout = $this->get_option('layout');
		$order = $this->get_option('informationOrder');
		$enabledBlocks = $order['enabled'];
		unset($enabledBlocks['placebo']);
		
		if($layout == 1)
		{
			$html = $this->get_first_layout();
		}
		if($layout == 2)
		{
			$html = $this->get_second_layout();
		}
		if($layout == 3)
		{
			$html = $this->get_third_layout();
		}

		foreach ($enabledBlocks as $key => $value) {
			$temp = explode('-', $key);
			$block = $temp[0];

			$func = 'get_'.$block;
			$html .= call_user_func(array($this, $func));

		}

		$filename = $this->escape_filename($this->data->title);

		header("Content-type: application/vnd.ms-word");
		header("Content-Disposition: attachment;Filename=" . $filename . ".doc");

		echo "<html>";
		echo $css;
		echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">";
		echo "<body>";
		echo $header;
		echo $html;
		echo $footer;
		echo "</body>";
		echo "</html>";
    }

    public function init_print()
    {

		$css = $this->build_CSS();

		if($this->get_option('enableHeader'))
		{
			$header = $this->get_header();
		}

		if($this->get_option('enableFooter'))
		{
			$footer = $this->get_footer();
		}

		$layout = $this->get_option('layout');
		$order = $this->get_option('informationOrder');
		$enabledBlocks = $order['enabled'];
		unset($enabledBlocks['placebo']);
		
		if($layout == 1)
		{
			$html = $this->get_first_layout();
		}
		if($layout == 2)
		{
			$html = $this->get_second_layout();
		}
		if($layout == 3)
		{
			$html = $this->get_third_layout();
		}

		foreach ($enabledBlocks as $key => $value) {
			$temp = explode('-', $key);
			$block = $temp[0];

			$func = 'get_'.$block;
			$html .= call_user_func(array($this, $func));

		}
		$pagebreak_css = '<style>
								@media print {
				    				.page-break {display:block; page-break-after: always;}
				    				.frame { padding: 0; }
							}
							</style>';
		$print_js = '
				<script>
				var w = window;
				var d = document;

				var printAndClose = function () {
					if (w.document.readyState == "complete") {
						clearInterval(sched);
						setTimeout(function() {
							w.focus();
							w.print();
							w.close();
						},
						500);
					}
				};
      			var sched = setInterval(printAndClose, 200);
      			</script>';
		$css = $css.$pagebreak_css.$print_js;
		echo $css.$header.$html.$footer;
		exit();
    }

    public function build_CSS()
    {
    	$layout = $this->get_option('layout');
    	$backgroundColor = $this->get_option('backgroundColor');

    	// Font
    	$textAlign = $this->get_option('textAlign') ? $this->get_option('textAlign') : 'left';

    	$textColor = $this->get_option('textColor');
    	$linkColor = $this->get_option('linkColor');

    	$fontFamily = $this->get_option('fontFamily') ? $this->get_option('fontFamily') : 'dejavusans';
    	$fontSize = $this->get_option('fontSize') ? $this->get_option('fontSize') : '11';

    	$fontLineHeight =  $this->get_option('fontLineHeight') ? $this->get_option('fontLineHeight') : $fontSize + 6; 

    	$fontSize = intval($fontSize);
    	$fontLineHeight = intval($fontLineHeight);

    	// Heading Fonts
    	$headingAlign = $this->get_option('headingAlign') ? $this->get_option('headingAlign') : 'center';
    	
    	$headingFontFamily = $this->get_option('headingFontFamily') ? $this->get_option('headingFontFamily') : 'dejavusans';
    	$headingFontSize = $this->get_option('headingFontSize') ? $this->get_option('headingFontSize') : '16';
    	$headingLineHeight =  $this->get_option('headingLineHeight') ? $this->get_option('headingLineHeight') : $headingFontSize + 6; 

    	$headingFontSize = intval($headingFontSize);
    	$headingLineHeight = intval($headingLineHeight);

    	$headingFontSizeH2 = $headingFontSize - 2;
    	$headingFontSizeH3 = $headingFontSize - 4;
    	$headingFontSizeH4 = $headingFontSize - 6;
    	$headingFontSizeH5 = $headingFontSize - 8;
    	$headingFontSizeH6 = $headingFontSize - 10;

    	$headingLineHeightH2 = $headingLineHeight - 2;
    	$headingLineHeightH3 = $headingLineHeight - 4;
    	$headingLineHeightH4 = $headingLineHeight - 6;
    	$headingLineHeightH5 = $headingLineHeight - 8;
    	$headingLineHeightH6 = $headingLineHeight - 10;   
		$css = '
		<head>
			<style media="all">';

		if(!empty($backgroundColor)) {
			$css .= 'body { background-color: ' . $backgroundColor . ';}';
		}
		if(!empty($textColor)) {
			$css .= 'body { color: ' . $textColor . ';}';
		}
		if(!empty($linkColor)) {
			$css .= 'a, a:hover { color: ' . $linkColor . ';}';
		}

		$css .= '.title td, .description td, .frame, body { text-align: ' . $textAlign . '; }';

		$css .= '
				body, table { font-family: ' . $fontFamily . ', sans-serif; font-size: ' . $fontSize . 'pt; line-height: ' . $fontLineHeight . 'pt; } 
				p { margin-bottom: 10px; margin-top: 0; }
				.pagebreak { display: none; }
				.posted-by-on { font-size: ' . ( $fontSize - 2) . 'pt; margin-top: 0px; font-style: italic; text-align: ' . $headingAlign . ';}
				 .frame { width:100%; padding: 10px 25px; }
				h1,h2,h3,h4,h5,h6 { font-family: ' . $headingFontFamily . ', sans-serif; margin-bottom: 10px; margin-top: 20px; text-align: ' . $headingAlign . '; }
				h1 { font-size: ' . $headingFontSize . 'pt; text-transform:uppercase; line-height: ' . $headingLineHeight . 'pt;}
				h2 { font-size: ' . $headingFontSizeH2 . 'pt; line-height: ' . $headingLineHeightH2 . 'pt;}
				h3 { font-size: ' . $headingFontSizeH3 . 'pt; line-height: ' . $headingLineHeightH3 . 'pt;}
				h4 { font-size: ' . $headingFontSizeH4 . 'pt; line-height: ' . $headingLineHeightH4 . 'pt;}
				h5 { font-size: ' . $headingFontSizeH5 . 'pt; line-height: ' . $headingLineHeightH5 . 'pt;}
				h6 { font-size: ' . $headingFontSizeH6 . 'pt; line-height: ' . $headingLineHeightH6 . 'pt;}
				.alignright { float:right; margin: 0 0 10px 20px;}
				.alignleft { float: left; margin: 0 20px 10px 0; }
				.aligncenter { display: block; margin: 0 auto; text-align center; }
				.attributes { width: 100%; }
				.attributes th { width:33%; text-align:left; padding-top:5px; padding-bottom: 5px;}
				.attributes td { width:66%; text-align:left; }
				.meta { font-size: 10pt; }
				.title { width: 100%; }
				.title td { padding-bottom: 10px; padding-top: 40px; }
				td.post-title { padding-bottom: 30px; }
				blockquote { border-left: 5px solid #eaeaea; font-style: italic; padding-left: 10px; margin-left: 20px; }
				.vc_row, .vc_col-sm-12 {
					width: 100%;
				}
				.vc_column-inner  {
					padding: 10px;
				}
				.wpb_column {
					float: left;
				}
				.vc_col-sm-1 {
					width: 8%;
				}
				.vc_col-sm-2 {
					width: 16%;
				}
				.vc_col-sm-3 {
					width: 24%;
				}
				.vc_col-sm-4 {
					width: 32%;
				}
				.vc_col-sm-5 {
					width: 40%;
				}
				.vc_col-sm-6 {
					width: 45%;
				}
				.vc_col-sm-7 {
					width: 56%;
				}
				.vc_col-sm-8 {
					width: 64%;
				}
				.vc_col-sm-9 {
					width: 72%;
				}
				.vc_col-sm-10 {
					width: 80%;
				}
				.vc_col-sm-11 {
					width: 88%;
				}
				';



		$customCSS = $this->get_option('customCSS');
		if(!empty($customCSS))
		{
			$css .= $customCSS;
		}

		$css .= '
			</style>

		</head>';

		return $css;
    }

    public function get_header()
    {
    	$headerBackgroundColor = $this->get_option('headerBackgroundColor');
    	$headerTextColor = $this->get_option('headerTextColor');
    	$headerLayout = $this->get_option('headerLayout');
    	$this->get_option('headerHeight') ? $headerHeight = $this->get_option('headerHeight') : $headerHeight = 'auto';
		$headerVAlign = $this->get_option('headerVAlign');

    	$topLeft = $this->get_option('headerTopLeft');
    	$topMiddle = $this->get_option('headerTopMiddle');
    	$topRight = $this->get_option('headerTopRight');

    	$headerTextAfterHeader = $this->get_option('headerTextAfterHeader');

    	$header = "";

    	if($headerLayout == "oneCol")
    	{
			$header .= '
			<table class="header frame" width="100%" style="vertical-align: bottom; font-size: 9pt; background-color: ' . $headerBackgroundColor . '; color: ' . $headerTextColor . ';">
				<tr>
					<td height="' . $headerHeight . '" valign="' . $headerVAlign . '" width="100%" style="text-align: center;">' . $this->get_header_footer_type($topLeft, 'headerTopLeft') . '</td>
				</tr>
			</table>';
    	} elseif($headerLayout == "threeCols") {
			$header .= '
			<table class="header frame" width="100%" style="vertical-align: bottom; font-size: 9pt; background-color: ' . $headerBackgroundColor . '; color: ' . $headerTextColor . ';">
				<tr>
					<td height="' . $headerHeight . '" valign="' . $headerVAlign . '" width="33%" style="text-align: left;">' . $this->get_header_footer_type($topLeft, 'headerTopLeft') . '</td>
					<td height="' . $headerHeight . '" valign="' . $headerVAlign . '" width="33%" style="text-align: center;">' . $this->get_header_footer_type($topMiddle, 'headerTopMiddle') . '</td>
					<td height="' . $headerHeight . '" valign="' . $headerVAlign . '" width="33%" style="text-align: right;">' . $this->get_header_footer_type($topRight, 'headerTopRight') . '</td>
				</tr>
			</table>';
		} else {
			$header .= '
			<table class="header frame" width="100%" style="vertical-align: bottom; font-size: 9pt; background-color: ' . $headerBackgroundColor . '; color: ' . $headerTextColor . ';">
				<tr>
					<td height="' . $headerHeight . '" valign="' . $headerVAlign . '" width="50%" style="text-align: left;">' . $this->get_header_footer_type($topLeft, 'headerTopLeft') . '</td>
					<td height="' . $headerHeight . '" valign="' . $headerVAlign . '" width="50%" style="text-align: right;">' . $this->get_header_footer_type($topRight, 'headerTopRight') . '</td>
				</tr>
			</table>';
		}


    	if(!empty($headerTextAfterHeader)) {
			$header .= '
			<table class="after-header frame" width="100%" style="vertical-align: bottom; font-size: 9pt;">
				<tr>
					<td width="100%" style="text-align: center; padding-bottom: 40px;">' . $headerTextAfterHeader . '</td>
				</tr>
			</table>';
		}


		return $header;
    }

    public function get_footer()
    {
    	$footerBackgroundColor = $this->get_option('footerBackgroundColor');
    	$footerTextColor = $this->get_option('footerTextColor');
    	$footerLayout = $this->get_option('footerLayout');
    	$this->get_option('footerHeight') ? $footerHeight = $this->get_option('footerHeight') : $footerHeight = 'auto';
		$footerVAlign = $this->get_option('footerVAlign');

    	$topLeft = $this->get_option('footerTopLeft');
    	$topRight = $this->get_option('footerTopRight');
    	$topMiddle = $this->get_option('footerTopMiddle');

    	$foooterTextBeforeFooter = $this->get_option('foooterTextBeforeFooter');
    	
    	$footer = "";

    	if(!empty($foooterTextBeforeFooter)) {
    		$footer .= '
    		<table class="pre-footer frame" width="100%" style="vertical-align: bottom; font-size: 9pt;">
				<tr>
					<td width="100%" style="text-align: center;">' . $foooterTextBeforeFooter . '</td>
				</tr>
			</table>';
    	}

    	if($footerLayout == "oneCol")
    	{
			$footer .= '
			<table class="footer frame" width="100%" style="vertical-align: bottom; font-size: 9pt; background-color: ' . $footerBackgroundColor . '; color: ' . $footerTextColor . ';">
				<tr>
					<td height="' . $footerHeight . '" valign="' . $footerVAlign . '" width="100%" style="text-align: center;">' . $this->get_header_footer_type($topLeft, 'footerTopLeft') . '</td>
				</tr>
			</table>';
    	} elseif($footerLayout == "threeCols") {
			$footer .= '
			<table class="footer frame" width="100%" style="vertical-align: bottom; font-size: 9pt; background-color: ' . $footerBackgroundColor . '; color: ' . $footerTextColor . ';">
				<tr>
					<td height="' . $footerHeight . '" valign="' . $footerVAlign . '" width="33%" style="text-align: left;">' . $this->get_header_footer_type($topLeft, 'footerTopLeft') . '</td>
					<td height="' . $footerHeight . '" valign="' . $footerVAlign . '" width="33%" style="text-align: center;">'. $this->get_header_footer_type($topMiddle, 'footerTopMiddle') . '</td>
					<td height="' . $footerHeight . '" valign="' . $footerVAlign . '" width="33%" style="text-align: right;">' . $this->get_header_footer_type($topRight, 'footerTopRight') . '</td>
				</tr>
			</table>';
		} else {
			$footer .= '
			<table class="footer frame" width="100%" style="vertical-align: bottom; font-size: 9pt; background-color: ' . $footerBackgroundColor . '; color: ' . $footerTextColor . ';">
				<tr>
					<td height="' . $footerHeight . '" valign="' . $footerVAlign . '" width="50%" style="text-align: left;">' . $this->get_header_footer_type($topLeft, 'footerTopLeft') . '</td>
					<td height="' . $footerHeight . '" valign="' . $footerVAlign . '" width="50%" style="text-align: right;">' . $this->get_header_footer_type($topRight, 'footerTopRight') . '</td>
				</tr>
			</table>';
		}

		return $footer;
    }

    private function get_header_footer_type($type, $position)
    {

    	switch ($type) {
    		case 'text':
    			return wpautop($this->get_option($position.'Text'));
    			break;
    		case 'bloginfo':
    			return $this->data->blog_name.'<br/>'.$this->data->blog_description;
    			break;
    		case 'pagenumber':
    			if($_GET['print-posts'] == "pdf") {
    				return __( 'Page:', 'wordpress-print-posts').' {PAGENO}';
    			} else {
    				return '';
    			}
    			break;
    		case 'postinfo':
    			return $this->data->title.'<br/>'.get_permalink();
    			break;
    		case 'image':
    			$image = $this->get_option($position.'Image');
    			$imageSrc = $image['url'];
    			$imageHTML = '<img src="' . $image['url'] . '">';
    			return $imageHTML;
    			break;
    		case 'exportinfo':
    			return date('d.m.y');
    			break;
			case 'qr':
				return '<barcode code="' . get_permalink($this->data->ID) . '" type="QR" class="barcode" size="0.8" error="M" />';
				break;
    		default:
    			return '';
    			break;
    	}
    }

    public function get_first_layout()
    {
    	$showImage = $this->get_option('showImage');
    	$showImageSize = $this->get_option('showImageSize');
		$showTitle = $this->get_option('showTitle');
		$showDate = $this->get_option('showDate');
		$showAuthor = $this->get_option('showAuthor');
		$showExcerpt = $this->get_option('showExcerpt');
		$showCategories = $this->get_option('showCategories');
		$showTags = $this->get_option('showTags');
		$showQR = $this->get_option('showQR');
		$showMetaFreetext = $this->get_option('showMetaFreetext');
		$metaFreeText = $this->get_option('metaFreeText');

		$featured_image = '<img width="' . $showImageSize . 'px" src="' . $this->data->src . '">';


		$html = '<div class="frame">';

		if($showImage) {
			$html .= '<div class="featured-image" style="width: 47%; float:left; text-align:left;">'.$featured_image.'</div>';
		}
			$html .= '<div class="post-info" style="width: 47%; float:left; padding: 0 0 10px 30px;">';

		if($showTitle) {
			$html .= '<h1 class="post-title" style="margin-bottom: 0; margin-top: 0;">' . $this->data->title.'</h1>';
		}
		$html .= '<div class="posted-by-on">';
		if($showDate ) {
			$html .= __( 'Posted on ', 'wordpress-print-posts' ) . mysql2date( get_option( 'date_format' ), $this->data->post_date );
		}
		if($showAuthor ) {
			$html .= __( ' by ', 'wordpress-print-posts' ) . get_the_author_meta('display_name', $this->data->post_author);
		}
		$html .= '</div>';
		if($showExcerpt) {
			$html .=  '<div class="post-short-description" style="margin-top:20px;">' . $this->data->short_description . '<br/></div>';
		}
		if($showMetaFreetext && !empty($metaFreeText)) {
			$html .= wpautop($metaFreeText).'<br/>';
		}
		if($showQR) {
			$html .= '<barcode code="' . get_permalink($this->data->ID) . '" type="QR" class="barcode" size="1.0" error="M" />';
		}

		$html .= '<hr style="color: #555555" />';

		if($showCategories) {
			$html .= '<p class="post-categories">' . $this->data->categories.'</p>';
		}
		if($showTags) {
			$html .= '<p class="post-tags">' . $this->data->tags.'</p>';
		}
	 	if(is_array($this->data->meta_keys)) {
	 		$html .= '<p>';
	 		foreach ( $this->data->meta_keys as $meta_key){
	 			if(empty($meta_key['value'])) {
	 				continue;
	 			}
	 			$html .= '<b class="meta_key ' . $meta_key['key'] . '">' . $meta_key['before'] . '</b>: ' . $meta_key['value'] . '<br/>';
	 		}
	 		$html .= '</p>';
	 	}
					
		$html .= '</div>
		</div>';

		return $html;
    }

    public function get_second_layout()
    {
    	$showImage = $this->get_option('showImage');
    	$showImageSize = $this->get_option('showImageSize');
		$showTitle = $this->get_option('showTitle');
		$showDate = $this->get_option('showDate');
		$showAuthor = $this->get_option('showAuthor');
		$showExcerpt = $this->get_option('showExcerpt');
		$showCategories = $this->get_option('showCategories');
		$showTags = $this->get_option('showTags');
		$showQR = $this->get_option('showQR');
		$showMetaFreetext = $this->get_option('showMetaFreetext');
		$metaFreeText = $this->get_option('metaFreeText');

		$featured_image = '<img width="' . $showImageSize . 'px" src="' . $this->data->src . '" >';

		$html = '<div class="frame">';
		if($showTitle) {
			$html .= '<h1 style="margin-bottom: 5px;">' . $this->data->title . '</h1>';
		}
		$html .= '<div class="posted-by-on">';
		if($showDate ) {
			$html .= __( 'Posted on ', 'wordpress-print-posts' ) . mysql2date( get_option( 'date_format' ), $this->data->post_date );
		}
		if($showAuthor ) {
			$html .= __( ' by ', 'wordpress-print-posts' ) . get_the_author_meta('display_name', $this->data->post_author);
		}
		$html .= '</div>';
		if($showImage) {
			$html .= '
				<div class="featured-image" style="background-color: #EEEEEE; text-align:center; margin: 20px 0px;">'
					. $featured_image .
				'</div>';
		}	
		$html .= '</div>';

		$html .= '<div class="frame">';

		if($showExcerpt) {
			$html .= '<div class="post-short-description">' . $this->data->short_description . '<br/></div>';
		}

		if($showMetaFreetext && !empty($metaFreeText)) {
			$html .= wpautop($metaFreeText);
		}

		$html .= '<p class="meta">';
		if($showCategories) {
			$html .= ' <span class="post-categories">' . $this->data->categories . '</span>';
		}
		if($showCategories && $showTags) {
			$html .= '<br/>';
		}
		if($showTags) {
			$html .= '<span class="post-tags">' . $this->data->tags. '</span>';
		}
		$html .= '</p>';

	 	if(is_array($this->data->meta_keys)) {
	 		$html .= '<p>';
	 		foreach ( $this->data->meta_keys as $meta_key){
	 			$html .= '<b>' . $meta_key['before'] . '</b>: ' . $meta_key['value'];
	 		}
	 		$html .= '</p>';
	 	}

		$html .= '</div>';

		if($showQR) {
			$html .= '<div class="qr-code-container">
						<div class="qr-code">
							<barcode code="' . get_permalink($this->data->ID) . '" type="QR" class="barcode" size="1.0" error="M" />
						</div>
					</div>';
		}
					
		return $html;
	}

	public function get_pagebreak()
	{
		$html = '<div class="page-break"></div><pagebreak />';
		return $html;
	}

    public function get_description()
    {
    	if(!$this->get_option('showDescription')) return FALSE;

    	if(empty($this->data->description)) return FALSE;

    	ob_start();

    	if($this->get_option('removeShortcodes')) {
			$description = preg_replace("/\[[^\]]+\]/", '', $this->data->description);
		} else {
			$description = $this->data->description;
		}
			
		echo '<div class="frame">' . $description . '</div>';

		return ob_get_clean();
    }

    public function get_comments()
    {
    	if ( ! comments_open() ) {
			return;
		}

		$comments = get_comments(array(
			'post_id' => $this->data->ID,
			'status' => 'approve' //Change this to the type of comments to be displayed
		));

		ob_start();

		?>
		<table class="frame title comments-title">
			<tr>
				<td>
					<h2>
					<?php
						if(empty($comments))
						{
							echo '<p class="wordpress-nocomments">'. __( 'There are no comments yet.', 'wordpress-print-posts' ) .'</p>';
						} 
						elseif ( get_option( 'wordpress_enable_comment_rating' ) === 'yes' && ( $count = count($comments)) )
						{
							echo sprintf( _n( '%s comment for %s', '%s comments for %s', $count, 'wordpress-print-posts' ), $count, get_the_title() );
						}
						else {
							echo __( 'Comments', 'wordpress-print-posts' );
						}
					?>
					</h2>
				</td>
			</tr>
		</table>
		<table class="frame comments" style="vertical-align: top;">
		<?php

		foreach ($comments as $comment) {
			$rating   = intval( get_comment_meta( $comment->comment_ID, 'rating', true ) );

		?>
			<tr class="comment_container">

				<td class="avatar" style="padding-bottom: 50px;">
					<?php echo get_avatar( $comment, apply_filters( 'wordpress_comment_gravatar_size', '60' ), '' ); ?>
				</td>

				<td class="comment-text" style="text-align: left;" valign="top">

					<p class="meta">
						<strong itemprop="author"><?= $comment->comment_author ?></strong> &ndash; <time itemprop="datePublished"><?php echo $comment->comment_date ?></time>	
					</p>

					<p><?= $comment->comment_content; ?></p>

				</td>
			</tr>
			<?php
		}

		?>
		</table>
		<?php
		return ob_get_clean();
    }

    private function escape_filename($file)
    {
		// everything to lower and no spaces begin or end
		$file = strtolower(trim($file));

		// adding - for spaces and union characters
		$find = array(' ', '&', '\r\n', '\n', '+',',');
		$file = str_replace ($find, '-', $file);

		//delete and replace rest of special chars
		$find = array('/[^a-z0-9\-<>]/', '/[\-]+/', '/<[^>]*>/');
		$repl = array('', '-', '');
		$file = preg_replace ($find, $repl, $file);

		return $file;
    }

	/**
	 * Exclude Post categories
	 *
	 * @since    1.1.8
	 */
    public function excludePostCategories()
    {
    	global $post;

		$excludePostCategories = $this->get_option('excludePostCategories');
		$excludePostCategoriesRevert = $this->get_option('excludePostCategoriesRevert');

		$terms = get_the_terms( $post->ID, 'category' );
		if($terms)
		{
			foreach ($terms as $term)
			{
				if($excludePostsRevert) {
					if(!in_array($term->term_id, $excludePostCategories))
					{
						return TRUE;

					}
				} else {
					if(in_array($term->term_id, $excludePostCategories))
					{
						return TRUE;

					}
				}
			}
		}
    }

	/**
	 * Exclude Posts
	 *
	 * @since    1.1.8
	 */
    public function excludePosts()
    {
    	global $post;

		$excludePosts = $this->get_option('excludePosts');
		$excludePostsRevert = $this->get_option('excludePostsRevert');
		if($excludePostsRevert) {
			if(!in_array($post->ID, $excludePosts))
			{
				return TRUE;
			}
		} else {
			if(in_array($post->ID, $excludePosts))
			{
				return TRUE;
			}
		}
    }

	/**
	 * Return the current user role
	 *
	 * @since    1.0.0
	 */
	private function get_user_role()
	{
		global $current_user;

		$user_roles = $current_user->roles;
		$user_role = array_shift($user_roles);

		return $user_role;
	}
}