<?php

class NBSmartInvoice_Rewrites {

    public function __construct() {
        add_action( 'init', array( $this, 'register_rule' ) );
        add_filter( 'query_vars', array( $this, 'register_query_var' ) );
        add_filter( 'template_include', array( $this, 'download_template' ) );
    }

    function register_rule() {
        add_rewrite_endpoint( 'nb_smartinvoice', EP_PAGES );
        add_rewrite_rule( 'nb_invoice/confirm/?$', 'index.php?nb_smartinvoice=$matches[1]', 'top' );
    }

    public function resolve_wc_query_conflict( $query_vars ) {
        global $post;

        $dashboard = dokan_get_option( 'dashboard', 'dokan_pages', 0 );

        if ( ! empty( $post->ID ) && $post->ID === absint( $dashboard ) ) {
            unset( $query_vars['orders'] );
            unset( $query_vars['edit-account'] );
        }

        return $query_vars;
    }

    function register_query_var( $vars ) {
        $vars[] = 'nb_smartinvoice';
        return $vars;
    }

    function download_template( $template ) {
        global $wp_query;

        if( isset($wp_query->query['nb_smartinvoice']) ) {
            do_action('nb_smartinvoice_download');
            die();
        }

        return $template;
    }
}

new NBSmartInvoice_Rewrites();