<?php

class HappyForms_Exporter_CSV {

	public $form_id;
	public $filename;

	public function __construct( $form_id, $filename ) {
		$this->form_id = $form_id;
		$this->filename = $filename;
	}

	public function export( $activity_ids = array() ) {
		global $wpdb;

		$form = happyforms_get_form_controller()->get( $this->form_id );

		if ( ! $form ) {
			$error = __( 'Form not found', 'happyforms' );
			return new WP_Error( $error );
		}

		$controller = happyforms_get_message_controller();
		$messages = (
			empty( $activity_ids ) ? 
			$controller->get_by_form( $this->form_id ) :
			$controller->get( $activity_ids )
		);
		$parts = array_filter( $form['parts'], 'happyforms_csv_is_part_visible' );
		$part_ids = wp_list_pluck( $parts, 'id' );
		$parts = array_combine( $part_ids, $parts );
		$headers = array();
		$rows = array();

		// CSV part value formatting
		add_filter( 'happyforms_get_csv_value', array( $this, 'get_csv_value' ), 10, 4 );

		foreach ( $parts as $part_id => $part ) {
			$headers[$part_id] = happyforms_get_csv_header( $part );
		}

		$headers = apply_filters( 'happyforms_csv_headers', $headers, $form );

		foreach( $messages as $message ) {
			$row = array();

			foreach( $headers as $part_id => $header ) {
				$value = $message['parts'][$part_id];
				$part = $parts[$part_id];
				$row[] = happyforms_get_csv_value( $value, $message, $part, $form );
			}

			$rows[] = $row;
		}

		// Append tracking numbers if needed
		if ( intval( $form['unique_id'] ) ) {
			$headers[] = __( 'Identifier', 'happyforms' );

			foreach( $rows as $r => $row ) {
				$row[] = $messages[$r]['tracking_id'];
				$rows[$r] = $row;
			}
		}

		$headers[] = __( 'Submission date and time', 'happyforms' );

		foreach( $rows as $r => $row ) {
			$date = get_the_date( 'm/d/Y', $messages[$r]['ID'] );
			$time = get_the_time( get_option( 'time_format' ), $messages[$r]['ID'] );
			$date = $date . ' ' . $time;
			$row[] = $date;
			$rows[$r] = $row;
		}

		$output = fopen( 'php://output', 'w' );
		header( 'Content-Description: File Transfer' );
		header( 'Content-Disposition: attachment; filename=' . $this->filename );
		header( 'Content-Type: text/csv; charset=' . get_option( 'blog_charset' ), true );

		do_action( 'happyforms_csv_export_before', $output );

		fputcsv( $output, array_values( $headers ) );

		foreach( $rows as $row ) {
			fputcsv( $output, array_values( $row ) );
		}

		exit();
	}

	public function get_csv_value( $value, $message, $part, $form ) {
		switch( $part[ 'type' ] ) {
			case 'table':
				$value = str_replace( '<br>', "\n", $value );
				$value = strip_tags( $value );
				break;
			default:
				break;
		}

		return $value;
	}

}
