/**
 * wpv_create_content_template
 *
 * Creates a new Content Template given a title and an optional suffix.
 *
 * Consider using WPV_Content_Template::create_new directly.
 *
 * @note Used by Layouts plugin.
 *
 * @param string $title
 * @param string $suffix
 * @param bool $force Whether to force the creation of the Template by incremental numbers added to the title in case it is already in use
 * @param string $content
 *
 * @return array {
 *     'success' => (int) The ID of the CT created
 *      'error' => (string) Error message
 *      'title' => (string) The title of the CT created or the one that made this fail
 *
 * @since 1.7
 */
function wpv_create_content_template( $title, $suffix = '', $force = true, $content = '' ) {

	$real_suffix = '';
	if ( ! empty( $suffix ) ) {
		$real_suffix = ' - ' . $suffix;
	}
    $template_title = $title . $real_suffix;

    $result = array();

    if( $force ) {
        $ct = WPV_Content_Template::create( $template_title, true );
    } else {

        if( WPV_Content_Template::is_name_used( $template_title ) ) {
            $result['error'] = __( 'A Content Template with that title already exists. Please use another title.', 'wpv-views' );
            $result['title'] = $template_title;
            return $result;
        }

        $ct = WPV_Content_Template::create( $template_title, false );
    }

    if( null == $ct ) {
        $return['title'] = $template_title;
        $return['error'] = __( 'An error occurred while creating a Content Template.', 'wpv-views' );
    } else {

        $return['title'] = $ct->title;

        try {
            $ct->content_raw = $content;
            $return['success'] = $ct->id;
        } catch( Exception $e ) {
            $return['error'] = __( 'An error occurred while creating a Content Template.', 'wpv-views' );
        }

    }

    return $return;
}