<?php
// IMPORTANT:
// If you define the constant K_TCPDF_EXTERNAL_CONFIG, all the following settings will be ignored.
// If you use the tcpdf_autoconfig.php, then you can overwrite some values here.

/**
 * Installation path (/var/www/tcpdf/).
 * By default it is automatically calculated but you can also set it as a fixed string to improve performances.
 */
//define ('K_PATH_MAIN', '');

/**
 * URL path to tcpdf installation folder (https://localhost/tcpdf/).
 * By default it is automatically set but you can also set it as a fixed string to improve performances.
 */
//define ('K_PATH_URL', '');

/**
 * Path for PDF fonts.
 * By default it is automatically set but you can also set it as a fixed string to improve performances.
 */
//define ('K_PATH_FONTS', K_PATH_MAIN.'fonts/');

/**
 * Default images directory.
 * By default it is automatically set but you can also set it as a fixed string to improve performances.
 */
//define ('K_PATH_IMAGES', '');

/**
 * Deafult image logo used be the default Header() method.
 * Please set here your own logo or an empty string to disable it.
 */
//define ('PDF_HEADER_LOGO', '');

/**
 * Header logo image width in user units.
 */
//define ('PDF_HEADER_LOGO_WIDTH', 0);

/**
 * Cache directory for temporary files (full path).
 */
//define ('K_PATH_CACHE', '/tmp/');

/**
 * Generic name for a blank image.
 */
define ('K_BLANK_IMAGE', '_blank.png');

/**
 * Page format.
 */
define ('PDF_PAGE_FORMAT', 'A4');

/**
 * Page orientation (P=portrait, L=landscape).
 */
define ('PDF_PAGE_ORIENTATION', 'P');

/**
 * Document creator.
 */
define ('PDF_CREATOR', 'TCPDF');

/**
 * Document author.
 */
define ('PDF_AUTHOR', 'TCPDF');

/**
 * Header title.
 */
define ('PDF_HEADER_TITLE', strip_tags( $survey_exp['name'] ) );

/**
 * Header description string.
 */
define ('PDF_HEADER_STRING', strip_tags( get_option('setting_pdf_header') ) );

/**
 * Document unit of measure [pt=point, mm=millimeter, cm=centimeter, in=inch].
 */
define ('PDF_UNIT', 'mm');

/**
 * Header margin.
 */
define ('PDF_MARGIN_HEADER', 5);

/**
 * Footer margin.
 */
define ('PDF_MARGIN_FOOTER', 10);

/**
 * Top margin.
 */
define ('PDF_MARGIN_TOP', 27);

/**
 * Bottom margin.
 */
define ('PDF_MARGIN_BOTTOM', 25);

/**
 * Left margin.
 */
define ('PDF_MARGIN_LEFT', 15);

/**
 * Right margin.
 */
define ('PDF_MARGIN_RIGHT', 15);

/**
 * Default main font name.
 */
 if ( get_option('setting_pdf_font') != '' ) {
	 $def_font = get_option('setting_pdf_font');
 }
 else {
	 $def_font = 'dejavusans';
 }
define ('PDF_FONT_NAME_MAIN', $def_font);

/**
 * Default main font size.
 */
define ('PDF_FONT_SIZE_MAIN', 10);

/**
 * Default data font name.
 */
define ('PDF_FONT_NAME_DATA', $def_font);

/**
 * Default data font size.
 */
define ('PDF_FONT_SIZE_DATA', 8);

/**
 * Default monospaced font name.
 */
define ('PDF_FONT_MONOSPACED', $def_font);

/**
 * Ratio used to adjust the conversion of pixels to user units.
 */
define ('PDF_IMAGE_SCALE_RATIO', 1.25);

/**
 * Magnification factor for titles.
 */
define('HEAD_MAGNIFICATION', 1.1);
/**
 * Height of cell respect font height.
 */
define('K_CELL_HEIGHT_RATIO', 1.25);
/**
 * Title magnification respect main font size.
 */
define('K_TITLE_MAGNIFICATION', 1.3);
/**
 * Reduction factor for small font.
 */
define('K_SMALL_RATIO', 2/3);
/**
 * Set to true to enable the special procedure used to avoid the overlappind of symbols on Thai language.
 */
define('K_THAI_TOPCHARS', true);
/**
 * If true allows to call TCPDF methods using HTML syntax
 * IMPORTANT: For security reason, disable this feature if you are printing user HTML content.
 */
define('K_TCPDF_CALLS_IN_HTML', false);
/**
 * If true and PHP version is greater than 5, then the Error() method throw new exception instead of terminating the execution.
 */
define('K_TCPDF_THROW_EXCEPTION_ERROR', true);
/**
 * Default timezone for datetime functions
 */
define('K_TIMEZONE', 'UTC');

// Include the main TCPDF library (search for installation path).
require_once( str_replace( "modules", "", dirname( __FILE__ ) ) . "lib" . MSDIRS . "tcpdf_min" . MSDIRS . "tcpdf.php" );

// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

// set document information
$pdf->SetCreator( PDF_CREATOR );
$pdf->SetAuthor( 'Pantherius' );
$pdf->SetTitle( strip_tags( $survey_exp['name'] ) );
$pdf->SetSubject( esc_html__( 'Generated by ', MODAL_SURVEY_TEXT_DOMAIN ) . ' Modal Survey');
$pdf->SetKeywords( 'PDF, survey, poll, feedback, vote, user voice' );

// set default header data
$pdf->SetHeaderData( PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE, PDF_HEADER_STRING, array( 0, 0, 0 ), array( 0, 0, 0 ) );
$pdf->setFooterData( array( 0, 0, 0 ), array( 0, 0, 0 ) );

// set header and footer fonts
$pdf->setHeaderFont( array( PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN, '', false ) );
$pdf->setFooterFont( array( PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA, '', false ) );
// Set font
// dejavusans is a UTF-8 Unicode font, if you only need to
// print standard ASCII chars, you can use core fonts like
// helvetica or times to reduce file size.
$pdf->setFont( PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN, '', false );
//$pdf->SetFont('helvetica', '', 14, '', true);

// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

// set margins
$pdf->SetMargins( PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT );
$pdf->SetHeaderMargin( PDF_MARGIN_HEADER );
$pdf->SetFooterMargin( PDF_MARGIN_FOOTER );

// set auto page breaks
$pdf->SetAutoPageBreak( TRUE, PDF_MARGIN_BOTTOM );

// set image scale factor
$pdf->setImageScale( PDF_IMAGE_SCALE_RATIO );

// set some language-dependent strings (optional)
if ( @file_exists( str_replace( array( "\\", "/" ), array( MSDIRS, MSDIRS ), dirname( __FILE__ ) ) . MSDIRS . 'lang' . MSDIRS . 'eng.php' ) ) {
    require_once( str_replace( array( "\\", "/" ), array( MSDIRS, MSDIRS ), dirname( __FILE__ ) ) . MSDIRS . 'lang' . MSDIRS . 'eng.php' );
    $pdf->setLanguageArray( $l );
}

// ---------------------------------------------------------

// set default font subsetting mode
$pdf->setFontSubsetting( true );

// Add a page
// This method has several options, check the source code documentation for more information.
$pdf->AddPage();

// set text shadow effect
$pdf->setTextShadow( array( 'enabled'=>true, 'depth_w'=>0, 'depth_h'=>0, 'color'=>array( 196, 196, 196 ), 'opacity'=>1, 'blend_mode'=>'Normal' ) );

$cpdf_iexp = array();

// Set some content to print
$html = '<h1 style="width: 100%; text-align: center;text-decoration:none;background-color:#fff;color:black;">' . strip_tags( $survey_exp[ 'name' ] ) .'<br><small>' . esc_html__( 'Generated: ', MODAL_SURVEY_TEXT_DOMAIN ) . ' ' . $survey_exp[ 'export_time' ] . '</small></h1>';
//include logo
//$html .= '<div style="width: 100%;text-align:center;"><img src="https://0.s3.envato.com/files/151863974/thumbnail.png"></div>';
if ( $personal ) {
	$cpdf_iexp = get_option( 'setting_custom_individual_export' );
	if ( ! is_array( $cpdf_iexp ) ) {
		$cpdf_iexp = array();
	}
	$html .= '<h3 style="width: 100%; text-align: center;text-decoration:none;background-color:#fff;color:black;">' . ( $survey_exp[ 'user_details' ]->name ? $survey_exp[ 'user_details' ]->name : esc_html__( 'Anonymous', MODAL_SURVEY_TEXT_DOMAIN ) ) . '</h3>';
}
else {
	$cpdf_iexp = array( "totalvotes", "otheranswers" );
}
$legend = "";
if ( isset( $_REQUEST[ 'chart' ] ) ) {
	if ( ! empty( $_REQUEST[ 'chart' ] ) ) {
		$chart = json_decode( stripslashes( $_REQUEST[ 'chart' ] ) );
	}
}
if ( isset( $_REQUEST[ 'legend' ] ) ) {
	if ( ! empty( $_REQUEST[ 'legend' ] ) ) {
		$legend = json_decode( stripslashes( $_REQUEST[ 'legend' ] ) );
	}
}
if ( isset( $_REQUEST[ 'pchart' ] ) ) {
	if ( ! empty( $_REQUEST[ 'pchart' ] ) ) {
		$pchart = json_decode( stripslashes( $_REQUEST[ 'pchart' ] ) );
	}
}
// Print text using writeHTMLCell()
$pdf->writeHTMLCell( 0, 0, 0, 100, $html, 0, 2, false, true, 'center' );
if ( $personal ) {
	$pdf->AddPage();
	$html = '<h3 style="text-decoration:none;background-color:#fff;color:black;text-align:left;width:100%;">' . esc_html__( 'Participants Details', MODAL_SURVEY_TEXT_DOMAIN ) . '<br><br><br></h3>';
	$timertd = "";
	if ( $survey_exp[ 'user_details' ]->alltimer > 0 ) {
		$timertd = '<td>' . esc_html__( 'Time Required', MODAL_SURVEY_TEXT_DOMAIN ) . ': ' . $survey_exp[ 'user_details' ]->alltimer . '' . esc_html__( 'sec', MODAL_SURVEY_TEXT_DOMAIN ) . '</td>';
	}
	$html .= '<table><tr><td>' . esc_html__( 'User ID', MODAL_SURVEY_TEXT_DOMAIN ) . ': ' . $survey_exp[ 'user_details' ]->autoid . '</td>' . $timertd . '</tr></table>';
	if ( $survey_exp[ 'user_details' ]->allscore != "" ) {
		$showtotalscore = esc_html__( 'Total Score', MODAL_SURVEY_TEXT_DOMAIN ) . ': ' . $survey_exp[ 'user_details' ]->allscore;
	}
	else {
		$showtotalscore = "";		
	}
	$html .= '<br><br><table><tr><td>' . esc_html__( 'Name', MODAL_SURVEY_TEXT_DOMAIN ) . ': ' . ( $survey_exp[ 'user_details' ]->name ? $survey_exp[ 'user_details' ]->name : esc_html__( 'Anonymous', MODAL_SURVEY_TEXT_DOMAIN ) ) . '</td><td>' . $showtotalscore . '</td></tr></table>';
	$html .= '<br><br><table><tr><td>' . esc_html__( 'Username', MODAL_SURVEY_TEXT_DOMAIN ) . ': ' . ( $survey_exp[ 'user_details' ]->username ? $survey_exp[ 'user_details' ]->username : esc_html__( 'Not Specified', MODAL_SURVEY_TEXT_DOMAIN ) ) . '</td></tr></table>';
	$html .= '<br><br><table><tr><td>' . esc_html__( 'Email', MODAL_SURVEY_TEXT_DOMAIN ) . ': ' . $survey_exp[ 'user_details' ]->email . '</td></tr></table>';
	$html .= '<br><br><table><tr><td>' . esc_html__( 'Date', MODAL_SURVEY_TEXT_DOMAIN ) . ': ' . $survey_exp[ 'user_details' ]->created . '</td></tr></table>';
	if ( ! empty( $survey_exp[ 'user_details' ]->custom ) ) {
		foreach ( unserialize( $survey_exp[ 'user_details' ]->custom ) as $muc_index=>$muc ) {
			$html .= '<br><br><table><tr><td>' . ucfirst( strtolower( $muc_index ) ) . ': ' . $muc . '</td></tr></table>';			
		}
	}
	$html .= '<br><br><table><tr><td><small><i>' . esc_html__( 'Participant answers marked with stars: *', MODAL_SURVEY_TEXT_DOMAIN ) . '</i></small></td></tr></table>';
	if ( isset( $pchart ) && ! empty( $pchart ) ) {
		$html .= '<p></p><p></p><p></p><p></p><p></p><p></p><table><tr><td><h3 style="text-decoration:none;background-color:#fff;color:black;text-align:center;">' . esc_html__( 'Personal Chart', MODAL_SURVEY_TEXT_DOMAIN ) . '</h3></td><td><h3 style="text-decoration:none;background-color:#fff;color:black;text-align:center;">' . esc_html__( 'Global Chart', MODAL_SURVEY_TEXT_DOMAIN ) . '</h3></td></tr><tr><td><img src="' . $pchart[ 0 ] . '"></td><td><img src="' . $pchart[ 1 ] . '"></td></tr></table>';
	}
	$pdf->writeHTML( $html, true, false, false, false, '' );
}

$qid = 0;
	foreach ( $survey_exp[ 'questions' ] as $qkey=>$questions ) {
		$html = '
		<h3 style="text-decoration:none;background-color:#fff;color:black;">' . nl2br( $questions[ 'name' ] );
		if ( in_array( "totalvotes", $cpdf_iexp ) ) {
			$qtimer = "";
			if ( $survey_exp[ 'user_details' ]->timer[ $qkey ] > 0 ) {
				$qtimer = "<br>" . esc_html__( 'Time', MODAL_SURVEY_TEXT_DOMAIN ) . ": " . $survey_exp[ 'user_details' ]->timer[ $qkey ] . esc_html__( 'sec', MODAL_SURVEY_TEXT_DOMAIN );
			}
			$html .= '<br><small style="font-weight: normal;">' . esc_html__( 'Total votes:', MODAL_SURVEY_TEXT_DOMAIN ) . ' ' . $questions[ 'count' ] . $qtimer . '</small></h3>';
		}
		else {
			$html .= '</h3>';			
		}
		$selected = false;
		foreach ( $questions as  $key=>$answer ) {
			if ( is_numeric( $key ) ) {
				if ( $answer[ 'count' ] > 1 ) {
					$vtstring = esc_html__( 'votes', MODAL_SURVEY_TEXT_DOMAIN );
				}
				else {
					$vtstring = esc_html__( 'vote', MODAL_SURVEY_TEXT_DOMAIN );
				}
				$marker = "";
				$aoptions = unserialize( $answer[ 'aoptions' ] );
				if ( $personal ) {
					if ( in_array( $key, $user_votes[ $qkey ] ) ) {
						$marker = "* ";
						$selected = true;
						if ( $aoptions[ 0 ] == "open" ) {
							$opan = explode( "|", $user_votes[ $qkey ][ 0 ] );
							if ( isset( $opan[ 1 ] ) ) {
								$answer[ 'answer' ] = esc_html__( 'Other', MODAL_SURVEY_TEXT_DOMAIN ) . ": " . $opan[ 1 ];
							}
						}
					}
				}
				if ( $aoptions[ 4 ] != "" ) {
					$score = ", " . esc_html__( 'Score', MODAL_SURVEY_TEXT_DOMAIN ) . ": " . $aoptions[ 4 ];
				}
				else {
					$score = "";
				}
				if ( in_array( "totalvotes", $cpdf_iexp ) ) {
					$current_vote = '
					<p style="text-decoration:none;background-color:#fff;color:black;">' . ( in_array( "otheranswers", $cpdf_iexp ) ? $marker : "" ) . $key . '. ' . ( isset( $legend[ $qid ][ $key - 1 ]) ? $legend[ $qid ][ $key - 1 ] : '' ) . ' ' . $answer[ 'answer' ] . ' <br><small>' . $answer[ 'count' ] . ' ' . $vtstring . ', ' . $answer[ 'percentage' ] . '% ' . esc_html__( 'of total votes', MODAL_SURVEY_TEXT_DOMAIN ) . $score . '</small> </p>';
				}
				else {
					$current_vote = '
					<p style="text-decoration:none;background-color:#fff;color:black;">' . ( in_array( "otheranswers", $cpdf_iexp ) ? $marker : "" ) . $key . '. ' . ( isset( $legend[ $qid ][ $key - 1 ]) ? $legend[ $qid ][ $key - 1 ] : '' ) . ' ' . $answer[ 'answer' ] . '<br><small>' . $score . '</small> </p>';					
				}
				if ( in_array( "otheranswers", $cpdf_iexp ) ) {
					$html .= $current_vote;
				}
				else {
					if ( $marker != "" ) {
						$html .= $current_vote;
					}
				}
			}
		}
		if ( ! in_array( "otheranswers", $cpdf_iexp ) && $selected == false ) {
			$html = "";
		}
		if ( isset( $chart[ $qid ] ) ) {
			$html .= '<div style="width:100%;text-align:center;"><img src="' . $chart[ $qid ] . '"></div>';
		}
		if ( ! empty( $html ) ) {
			$pdf->AddPage();
			$pdf->writeHTML( $html, true, false, false, false, '' );
		}
		$qid++;
	}
// ---------------------------------------------------------

// Close and output PDF document
// This method has several options, check the source code documentation for more information.

//============================================================+
// END OF FILE
//============================================================+
	$path = str_replace( array( "\\", "/" ), array( MSDIRS, MSDIRS ), dirname( __FILE__ ) ) . MSDIRS . ".." . MSDIRS . "exports" . MSDIRS . $survey_exp[ 'id' ] . ".pdf";

if ( file_exists( $path ) ) {
	unlink( $path );
}
try {
	$pdf->Output( $path, 'F' );
	$result = "success";
}
catch ( Exception $e ) {
	$result = esc_html__( 'Write error', MODAL_SURVEY_TEXT_DOMAIN );
}
?>