<?php
require_once ('../../../../wp-load.php');
require_once ('../includes/utils.inc.php');

if ( !current_user_can('edit_pages') ) {
	wp_die( __('You are not allowed to edit this item.') );
}

mb_regex_encoding('UTF-8');
mb_internal_encoding("UTF-8");
$book_id = (int)$_POST['book_id'];
$bind = $_POST['bind'];
$size = $_POST['size'];
$css = $_POST['css'];
$title = get_cat_name($book_id);

if ($bind == 'right') {
	$bind = 'right-side';
}
else {
	$bind = 'left-side';
}

$site = home_url();
$dir = pripre_get_base_dir();

$copper = pripre_get_copper();
$copper->property("output.print-mode", $bind);
$copper->set_continuous(TRUE);

header("Content-Type: application/pdf");
header("Content-Disposition:  attachment");
//header("Content-Type: text/plain");

include ("../includes/copper-common.inc.php");
switch($size) {
	case '46':
		$copper->property("output.page-width", "127mm");
		$copper->property("output.page-height", "188mm");
		break;
	case 'B6':
		$copper->property("output.page-width", "128mm");
		$copper->property("output.page-height", "182mm");
		break;
	case 'A5':
		$copper->property("output.page-width", "148mm");
		$copper->property("output.page-height", "210mm");
		break;
	case 'A6':
		$copper->property("output.page-width", "105mm");
		$copper->property("output.page-height", "148mm");
		break;
	case 'Shinsho':
		$copper->property("output.page-width", "103mm");
		$copper->property("output.page-height", "182mm");
		break;
}

global $wpdb;
$sql = "SELECT p.post_date,p.id,p.post_title,p.post_content
        FROM {$wpdb->prefix}term_relationships AS t
        INNER JOIN {$wpdb->prefix}posts AS p ON p.id=t.object_id
        WHERE t.term_taxonomy_id=$book_id";
$entries = $wpdb->get_results($sql, ARRAY_A);
pripre_sort_bookposts($book_id, $entries);

for ($i = 0; $i < 2; ++$i) {
	$copper->property("processing.middle-pass", $i == 0 ? "true" : "false");
	foreach ($entries as $entry) {
	    $id = $entry['id'];
	    $title = $entry['post_title'];
	    $content = $entry['post_content'];
	    $template = get_post_custom_values('pripre_entry_style', $id);
	    if (empty($template)) {
	    	$template = "plain";
	    }
	    else {
	    	$template = $template[0];
	    }
	     
	    $copper->start_resource("style.css", array('encoding' => 'UTF-8'));
	    include ("$dir/templates/book/$template/style.css");
	    $copper->end_resource();
	     
	    $contents_template = "$dir/templates/book/$template/entry.php";
		$copper->start_main(".", array('encoding' => 'UTF-8'));
	    include("$dir/templates/html.php");
		$copper->end_main();
	}
}

$copper->join();
$copper->close();
?>
