<?php

require_once(dirname(__FILE__) . '/Idno/start.php');

include 'HTML-To-Markdown.php';

function init() {
	$this->garray['data'] = array();
	$this->garray['data']['posts'] = array();
	$this->garray['data']['tags'] = array();
	$this->garray['data']['posts_tags'] = array();
	$this->garray['data']['users'] = array();
}

function populate_meta() {
	$this->garray['meta'] = array(
		'exported_on' 	=> date( 'r' ),
		'version'		=> '000',
	);
}

function tags() {
	$all_tags = get_tags();

	if ( ! empty( $all_tags ) ) {
		foreach ( $all_tags as $tag ) {
			$this->garray['data']['tags'][] = array(
				'id' => intval( $tag->term_id ),
				'name' => $tag->name,
				'slug' => $tag->slug,
				'description' => $tag->description,
			);
		}
	}

	// cleanup
	unset( $all_tags );
	unset( $tag );
}

// TODO modifier ça pour Known !
// https://github.com/idno/Known/blob/master/Idno/Common/Entity.php
function posts() {
	
	$posts = Idno\Common\Entity::getFromAll([], [], 99999);
	$slug_number = 0;
	$_post_tags = [];

	foreach(posts as $post) {
		global $post;
		$posts->the_post();

		$post->post_markdown = new HTML_To_Markdown( apply_filters( 'the_content', $post->post_content ) );

		$tags = get_the_tags();
		if ( ! empty( $tags ) ) {
			foreach ( $tags as $tag ) {
				$_post_tags[] = array(
					'tag_id' => intval( $tag->term_id ),
					'post_id' => intval( $post->ID )
				);
			}
		}

		$s = $this->map_status( $post->post_status );

		$image_id = get_post_thumbnail_id( $post->ID );
		if ( $image_id !== '' ) {
			$image = wp_get_attachment_image_src( $image_id, 'full' );
		}

		$this->garray['data']['posts'][] = array(
			//'id'			=> intval( $post->ID ),
			'title'			=> substr( ( empty( $post->title ) ) ? '(no title)' : $post->post_title, 0, 150 ),
			'slug'			=> substr( ( empty( $post->post_name ) ) ? 'temp-slug-' . $slug_number : $post->post_name, 0, 150 ),
			'markdown'		=> $post->post_markdown->output(),
			'html'			=> apply_filters( 'the_content', $post->post_content ),
			'image'			=> ( $image_id ) ? $image[0] : null,
			'featured'		=> 0,
			'page'			=> ( $post->post_type === 'page' ) ? 1 : 0,
			'status'		=> substr( $s, 0, 150 ),
			'language'		=> substr( 'en_US', 0, 6 ),
			'meta_title'	=> null,
			'meta_description'	=> null,
			'author_id'		=> $this->_safe_author_id( $post->post_author ),
			'created_at'	=> $this->_get_json_date( $post->post_date ),
			'created_by'	=> 1,
			'updated_at'	=> $this->_get_json_date( $post->post_modified ),
			'updated_by'	=> 1,
			'published_at'	=> ($s !== 'draft') ? $this->_get_json_date( $post->post_date ) : '',
			'published_by'	=> 1,
		);

		$slug_number += 1;
	}

	$this->garray['data']['posts_tags'] = $_post_tags;

	// cleanup
	unset( $posts_args );
	unset( $posts );
	unset( $slug_number );
	unset( $_post_tags );
	unset( $tags );
	unset( $tag );
	unset( $s );
}

function populate_data() {
	if ( $this->garray !== null ) {
		return;
	}

	$this->garray = array();

	// preps the structure
	init();

	// attaches metadata
	meta();

	// attaches tags
	tags();

	// populates posts
	posts();
}

/**
 * Sends necessary headers and whatnot to allow to download file
 * @return bin file
 */
public function download_file() {

	// Ensure the user accessing the function actually has permission to do this
	if ( ! current_user_can('export') ) {
		wp_die( "<p>You are not allowed to do that.</p>", 'Permission error' );
	}

	$this->populate_data();

	$upload_dir = wp_upload_dir();
	$filedir = $upload_dir['path'];
	$filename = 'wp2ghost_export_' . time() . '.json';

	if ( ! is_writable( $filedir ) ) {
		wp_die( "<p>Uploads directory is not writable, can't save the Ghost json file :/</p><p>Generated by the Ghost plugin version {$this->version}.</p>", 'Directory not writable' );
	}

	$handle = fopen( $filedir . '/' . $filename, 'w' );
	$content = $this->get_json( $this->garray );
	fwrite( $handle, $content );
	fclose( $handle );

	header( 'Content-Description: File Transfer' );
	header( 'Content-Type: application/octet-stream' );
	header( 'Content-Disposition: attachment; filename='.$filename );
	header( 'Content-Transfer-Encoding: binary' );
	header( 'Expires: 0' );
	header( 'Cache-Control: must-revalidate' );
	header( 'Pragma: public' );
	header( 'Content-Length: ' . filesize( $filedir . '/' . $filename ) );

	flush();
	readfile( $filedir . '/' . $filename );
	exit;
}