How to create a custom WordPress page with my plugin?

function to create a page and if we want to link a template to that page

if (! function_exists('create_page')) {
    function create_page($title, $template = 0){
        $a = get_page_by_title( $title, 'post' );
        if ($a == null || $a->post_status == 'trash') {
            $page = array(
               'post_type'     => 'page',
               'post_title'    => $title,
               'post_status'   => 'publish'
             );
            $post_id = wp_insert_post( $page );
            update_post_meta($post_id, '_wp_page_template', $template);
            echo '<a style="color:green;">page '.$title.' created.</a><br>';
        } else {
            echo 'page '.$title.' already exists!<br>';
        }
    }
}

then can be called like this

create_page('my_custom_page');

if there is a template to the page, we can call the function like this:

create_page('my_custom_page','folder/mycustom_template');