<?php

class BWFCRM_Templates {

	/** return single template or all templates json data
	 *
	 * @param null $template_id
	 *
	 * @return false|mixed|string|void
	 */
	public static function get_json( $template_id = null ) {
		global $wpdb;

		$tempate_table = $wpdb->prefix . 'bwfan_templates';
		$query         = "SELECT `subject`, `template`, `type`,`title`,`mode`,`data` FROM $tempate_table WHERE 1 = 1 AND `canned` = 1 ";

		if ( is_array( $template_id ) && ! empty( $template_id ) ) {
			$template_id = array_values( $template_id );
			$template_id = implode( ', ', $template_id );
			$query       .= " AND `ID` IN ( " . $template_id . " ) ";
		} else if ( absint( $template_id ) > 0 ) {
			$query .= " AND `ID` = %d ";
			$query = $wpdb->prepare( $query, $template_id );
		}

		$templates = $wpdb->get_results( $query, ARRAY_A );

		return wp_json_encode( $templates );
	}

	public static function import( $file_data ) {
		$template_id = 0;
		foreach ( $file_data as $data ) {
			if ( empty( $data['template'] ) ) {
				continue;
			}

			$create_time   = current_time( 'mysql', 1 );
			$template_data = [
				'title'      => $data['title'],
				'template'   => $data['template'],
				'subject'    => $data['subject'],
				'type'       => intval( $data['type'] ) > 0 ? intval( $data['type'] ) : 1,
				'mode'       => intval( $data['mode'] ) > 0 ? intval( $data['mode'] ) : 1,
				'canned'     => 1,
				'created_at' => $create_time,
				'updated_at' => $create_time,
				'data'       => BWFAN_Common::is_json( $data['data'] ) ? $data['data'] : wp_json_encode( $data['data'] ),
			];

			$template_id = BWFAN_Model_Templates::bwfan_create_new_template( $template_data );
		}

		return $template_id;
	}
}
