<?php
/**
 * The main WCVendors Pro Dashboard class
 *
 * This is the main controller class for the dashboard, all actions are defined in this class.
 *
 * @package    WCVendors_Pro
 * @subpackage WCVendors_Pro/public
 */
use WC_Vendors\Classes\Front\WCV_Vendor_Controller;
/**
 * Class WCVendors_Pro_Dashboard
 */
class WCVendors_Pro_Dashboard { //phpcs:ignore

    /**
     * The ID of this plugin.
     *
     * @since    1.0.0
     * @access   private
     * @var      string $wcvendors_pro The ID of this plugin.
     */
    private $wcvendors_pro;

    /**
     * The version of this plugin.
     *
     * @since    1.0.0
     * @access   private
     * @var      string $version The current version of this plugin.
     */
    private $version;

    /**
     * Is the plugin in debug mode
     *
     * @since    1.0.0
     * @access   private
     * @var      bool $debug plugin is in debug mode
     */
    private $debug;

    /**
     * Is the plugin in debug mode
     *
     * @since    1.0.0
     * @access   private
     * @var      array $dashboard_pages an array of dashboard pages
     */
    private $dashboard_pages = array();

    /**
     * Is the plugin base directory
     *
     * @since    1.0.0
     * @access   private
     * @var      string $base_dir string path for the plugin directory
     */
    private $base_dir;

    /**
     * Initialize the class and set its properties.
     *
     * @since    1.0.0
     *
     * @param      string $wcvendors_pro The name of the plugin.
     * @param      string $version       The version of this plugin.
     * @param bool   $debug Is debug enabled.
     */
    public function __construct( $wcvendors_pro, $version, $debug ) {

        $this->wcvendors_pro = $wcvendors_pro;
        $this->version       = $version;
        $this->debug         = $debug;
        $this->base_dir      = plugin_dir_path( __DIR__ );
        add_filter( 'wcvendors_application_form', array( $this, 'show_application_form' ) );

        add_filter( 'wcv_dashboard_start_date_input', array( $this, 'dashboard_start_date_input' ) );
        add_filter( 'wcv_dashboard_end_date_input', array( $this, 'dashboard_end_date_input' ) );

        add_filter( 'wcv_order_start_date_input', array( $this, 'dashboard_start_date_input' ) );
        add_filter( 'wcv_order_end_date_input', array( $this, 'dashboard_end_date_input' ) );

        add_filter( 'wcv_commission_start_date_input', array( $this, 'dashboard_start_date_input' ) );
        add_filter( 'wcv_commission_end_date_input', array( $this, 'dashboard_end_date_input' ) );

        add_filter( 'wcvendors_datepicker_date_format', array( $this, 'change_datepicker_localization' ) );

        add_filter( 'wcvendors_table_columns_label_recent_order_class', '__return_empty_string' );
        add_filter( 'wcvendors_table_columns_label_recent_product_class', '__return_empty_string' );
        add_filter( 'wcvendors_table_recent_order_class', array( $this, 'dashboard_table_class' ) );
        add_filter( 'wcvendors_table_recent_product_class', array( $this, 'dashboard_table_class' ) );
        add_filter( 'wcvendors_dashboard_should_show_ratings', array( $this, 'should_show_ratings' ) );

        add_action( 'init', array( $this, 'modify_date_input' ) );
    }

    /**
     * Modify date input format from d/m/Y to Y-m-d
     *
     * @since 1.0.0
     */
    public function modify_date_input() {

        $date_format = self::get_date_format();

        if ( 'd/m/Y' !== $date_format['format'] ) {
            return;
        }

        $post_date_keys = array(
            '_wcv_order_start_date_input',
            '_wcv_order_end_date_input',
            '_wcv_dashboard_start_date_input',
            '_wcv_dashboard_end_date_input',
            '_wcv_commission_start_date_input',
            '_wcv_commission_end_date_input',
        );

        foreach ( $post_date_keys as $post_date_key ) {
            if ( isset( $_POST[ $post_date_key ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing
                $dm                      = DateTime::createFromFormat( 'd/m/Y', $_POST[ $post_date_key ] ); //phpcs:ignore
                if ( false !== $dm ) {
                    $_POST[ $post_date_key ] = $dm->format( 'Y-m-d' );
                }
            }
        }
    }

    /**
     * Provide quick links on the dashboard to reduce click through
     *
     * @since    1.1.5
     * @version  1.8.4 - Added can submit handler
     * @version  1.9.2 - Added quick links filter
     *
     * @param array $quick_links the quick links array.
     * @return array $quick_links the quick links array.
     */
    public function get_dashboard_quick_links( $quick_links ) {

        $coupons_disabled = wc_string_to_bool( get_option( 'wcvendors_shop_coupon_management_cap', 'no' ) );
        $product_ids      = WCV_Vendor_Controller::get_products_by_id( get_current_user_id() );

        if ( empty( $product_ids ) ) {
            $coupons_disabled = true;
        }
        if ( ! wc_coupons_enabled() ) {
            $coupons_disabled = true;
        }

        if ( ! $coupons_disabled ) {
            $quick_links['shop_coupon'] = array(
                'url'   => WCV_Vendor_Dashboard::get_dashboard_page_url( 'shop_coupon/edit' ),
                'label' => __( 'Add coupon', 'wcvendors-pro' ),
            );
        }

        return $quick_links;
    }

    /**
     * Get usage stats array.
     *
     * @since 1.9.2
     *
     * @param array $stats the usage stats array.
     *
     * @return array $stats the usage stats array.
     */
    public function get_dashboard_usage_stats( $stats ) {
        $user_id = get_current_user_id();
        $limits  = WCVendors_Pro_Upload_Limits::get_instance( $user_id );

        $stats = array();
        if ( wc_string_to_bool( get_option( 'wcvendors_dashboard_show_disk_usage', 'no' ) ) ) {
            $disk_limit = $limits->format_disk_size( $limits->get_disk_usage_limit() );
            $disk_usage = $limits->format_disk_usage_size( $limits->get_disk_usage() );

            $stats['disk-limit'] = array(
                'usage'    => $disk_usage,
                'limit'    => $disk_limit,
                'over'     => $limits->disk_limit_reached(),
                'icon'     => 'wcv-icon-hdd',
                'template' => '%s / %s',
            );
        }
        if ( wc_string_to_bool( get_option( 'wcvendors_dashboard_show_files_usage', 'no' ) ) ) {
            $files_limit = $limits->get_files_count_limit();
            $files_limit = 0 === $files_limit ? __( 'Unlimited', 'wcvendors-pro' ) : $files_limit;
            $files       = $limits->get_media();
            $files_usage = ! empty( $files ) ? count( $files ) : 0;

            $stats['file-limit'] = array(
                'usage'    => $files_usage,
                'limit'    => $files_limit,
                'over'     => $limits->files_limit_reached(),
                'icon'     => 'wcv-icon-file-alt',
                /* translators: %1$s file usage, %2$s file limit */
                'template' => __( '%1$s / %2$s files', 'wcvendors-pro' ),
            );
        }

        /**
         * Hook to this filter to change the stat buttons.
         */
        return apply_filters( 'wcvendors_dashboard_usage_stats', $stats, $user_id );
    }

    /**
     * Available dashboard urls for front end functionality
     *
     * @since    1.0.0
     * @version  1.8.4 - added can submit handler.
     * @version  1.9.2 - added dashboard urls filter.
     *
     * @param array $dashboard_pages the dashboard pages.
     */
    public function get_dashboard_pages( $dashboard_pages ) {

        $can_export_commissions = wc_string_to_bool( get_option( 'wcvendors_capability_commission_export', 'no' ) );

        $dashboard_pages['rating'] = array(
            'slug'    => 'rating',
            'id'      => 'rating',
            'label'   => __( 'Ratings', 'wcvendors-pro' ),
            'actions' => array(),
        );

        $dashboard_pages['commission'] = array(
            'slug'    => 'commission',
            'id'      => 'commission',
            'label'   => __( 'Commission', 'wcvendors-pro' ),
            'actions' => array(),
        );

        if ( 'yes' === get_option( 'woocommerce_enable_coupons' ) ) {
            $add_coupon_url                 = self::get_dashboard_page_url( 'shop_coupon/edit' );
            $dashboard_pages['shop_coupon'] = array(
                'slug'        => 'shop_coupon',
                'id'          => 'shop_coupon',
                'label'       => __( 'Coupons', 'wcvendors-pro' ),
                'actions'     => array(
                    'edit'   => __( 'Edit', 'wcvendors-pro' ),
                    'delete' => __( 'Delete', 'wcvendors-pro' ),
                ),
                'after_label' => array(
                    '<a href="' . esc_url( $add_coupon_url ) . '" class="wcv-button button quick-link-btn">',
                    __( 'Add Coupon', 'wcvendors-pro' ),
                    '</a>',
                ),
            );

        }

        if ( $can_export_commissions ) {
            $dashboard_pages['commission']['after_label'] = array(
                '<a href="' . esc_url( add_query_arg( 'wcv_export_commission', 'true' ) ) . '" class="wcv-button wcv-button-link">',
                wp_kses( wcv_get_icon( 'wcv-icon wcv-icon-20 wcv-icon-middle', 'wcv-icon-export' ), wcv_allowed_html_tags() ),
                '<strong class="vertical-middle">' . esc_attr__( 'Export Commission', 'wc-vendors' ) . '</strong>',
                '</a>',
            );
        }

        return $dashboard_pages;
    }

    /**
     * Load the commission table
     *
     * @since    1.8.4
     */
    public function load_commission_page() {
        $wcvendors_pro_commission_download_controller = new WCVendors_Pro_Commission_Download_Controller( $this->wcvendors_pro, $this->version, $this->debug );
        $wcvendors_pro_commission_download_controller->display();
    }

    /**
     * Load the ratings page
     *
     * @since    1.0.0
     */
    public function load_rating_page() {
        $wcvendors_pro_rating_controller = new WCVendors_Pro_Ratings_Controller( $this->wcvendors_pro, $this->version, $this->debug );
        $wcvendors_pro_rating_controller->display();
    }

    /**
     * Load page
     *
     * @param object $object_to_check the object to check.
     */
    public function load_page( $object_to_check ) {
        switch ( $object_to_check ) {
            case 'commission':
                $this->load_commission_page();
                break;
            case 'rating':
                $this->load_rating_page();
                break;
        }
    }

    /**
     * Should show ratings
     *
     * @param bool $should_show should show.
     * @return bool should show.
     *
     * @version 1.9.4
     */
    public function should_show_ratings( $should_show ) {
        $should_show = ! wc_string_to_bool( get_option( 'wcvendors_ratings_management_cap', 'no' ) );
        return $should_show;
    }

    /**
     * Show get application form
     *
     * @since    1.8.7.1
     * @version 1.8.7.2
     * @version 1.9.8 - Added allow registration option check.
     *
     * @param string $form_html The form HTML.
     * @return string The form HTML.
     */
    public function show_application_form( $form_html ) {
        $allow_registration = wc_string_to_bool( get_option( 'wcvendors_vendor_allow_registration', 'no' ) );

        if ( ! $allow_registration ) {
            return $form_html;
        }

        ob_start();
        include_once apply_filters( 'wcvendors_pro_dashboard_open_path', 'partials/wcvendors-pro-dashboard-open.php' );
        $vendor_signup_notice = get_option( 'wcvendors_vendor_signup_notice', '' );

        // Load the new sign up form template.
        wc_get_template(
            'vendor-signup-form.php',
            array(
                'vendor_signup_notice' => $vendor_signup_notice,
                'shipping_details'     => array(),
            ),
            'wc-vendors/front/',
            $this->base_dir . '/templates/front/'
        );
        include_once apply_filters( 'wcvendors_pro_dashboard_close_path', 'partials/wcvendors-pro-dashboard-close.php' );
        $form_html = ob_get_clean();

        return $form_html;
    }

    /**
     * Check if a page is disabled and return if it is
     *
     * @since    1.3.0
     * @version  1.5.0
     * @version  1.9.2 - Added page_disabled filter.
     *
     * @param bool   $disabled      is the page disabled.
     * @param string $current_page  the current page.
     */
    public function page_disabled( $disabled, $current_page ) {

        switch ( $current_page ) {
            case 'commission':
                $disabled = wc_string_to_bool( get_option( 'wcvendors_commission_management_cap', 'no' ) );
                break;
            case 'shop_coupon':
                $disabled = wc_string_to_bool( get_option( 'wcvendors_shop_coupon_management_cap', 'no' ) );
                break;
            case 'rating':
                $disabled = wc_string_to_bool( get_option( 'wcvendors_ratings_management_cap', 'no' ) );
                break;
        }

        return $disabled;
    }

    /**
     * Check if the the vendors access has been disabled
     *
     * @since  1.4.0
     * @access public
     */
    public function lock_new_products_notice() {

        $lock_new_products         = ( 'yes' === get_user_meta( get_current_user_id(), '_wcv_lock_new_products_vendor', true ) ) ? true : false;
        $lock_new_products_notice  = get_user_meta( get_current_user_id(), '_wcv_lock_new_products_vendor_msg', true );
        $lock_edit_products        = ( 'yes' === get_user_meta( get_current_user_id(), '_wcv_lock_edit_products_vendor', true ) ) ? true : false;
        $lock_edit_products_notice = get_user_meta( get_current_user_id(), '_wcv_lock_edit_products_vendor_msg', true );
        $notice                    = '';

        if ( $lock_new_products ) {
            $notice .= $lock_new_products_notice;
        }
        if ( $lock_edit_products ) {
            $notice .= ' ' . $lock_edit_products_notice;
        }

        if ( $lock_new_products || $lock_edit_products ) {

            wc_get_template(
                'dashboard-notice.php',
                array(
                    'vendor_dashboard_notice' => $notice,
                    'notice_type'             => 'error',
                ),
                'wc-vendors/dashboard/',
                $this->base_dir . '/templates/dashboard/'
            );
        }
    }

    /**
     * Update disk and file usage after deleting or adding media file
     *
     * @since 1.8.5
     * @param int $post_id the post id of the media file.
     */
    public function update_disk_usage_status( $post_id ) {
        $author = get_post_field( 'post_author', $post_id );

        if ( ! WCV_Vendors::is_vendor( $author ) ) {
            return;
        }

        delete_transient( 'wcv_user_media_' . $author );
        delete_transient( 'wcv_user_disk_usage_' . $author );
    }

    /**
     * Generate the page URL based on the dashboard page id set in options
     *
     * @since   1.9.2
     * @version 1.9.2
     *
     * @param string $page page type to output.
     */
    public static function get_dashboard_page_url( $page = '' ) {

        return WCV_Vendor_Dashboard::get_dashboard_page_url( $page );
    }

    /**
     * Check object permission to see if the vendor owns the object (this is to stop people messing with URLs)
     *
     * @since  1.9.2
     *
     * @param    string $object_to_check the object type to test.
     * @param    int    $object_id  object id to check.
     */
    public static function check_object_permission( $object_to_check, $object_id ) {
        return WCV_Vendor_Dashboard::check_object_permission( $object_to_check, $object_id );
    }

    /**
     * Template base dir for Pro pages
     *
     * @param string $base_dir the base directory.
     * @param string $object_to_check the object type to test.
     */
    public function get_template_base_dir( $base_dir, $object_to_check ) {

        $pro_dasboard_page = array( 'commission', 'rating', 'shop_coupon' );

        if ( in_array( $object_to_check, $pro_dasboard_page, true ) ) {
            $base_dir = $this->base_dir . 'templates/dashboard/';
        }

        return $base_dir;
    }

    /**
     * Check if the current page is a dashboard page
     *
     * @since      1.9.2
     * @access     public
     * @deprecated 1.9.2
     * @param int $page_id the page id to check.
     * @return bool returns if the page id passed is a dashboard page.
     */
    public static function is_dashboard_page( $page_id ) {
        return wcv_is_dashboard_page( $page_id );
    }

    /**
     * Change pro dashboard page id to new page id
     *
     * @param int $value the page id to check.
     *
     * @since 1.9.4
     * @return int returns the new page id.
     */
    public function pro_dashboard_redirect( $value ) {
        $wcv_dashboard_page_id = get_option( 'wcvendors_vendor_dashboard_page_id' );

        if ( $wcv_dashboard_page_id && is_page( $wcv_dashboard_page_id ) ) {
            $value = $wcv_dashboard_page_id;
        }

        return $value;
    }

    /**
     * Get date format and pattern for the date picker
     */
    public static function get_date_format() {
        $date_format = get_option( 'wcvendors_dashboard_date_format', 'Y-m-d' );
        $placeholder = str_replace( array( 'd', 'm', 'Y' ), array( 'DD', 'MM', 'YYYY' ), $date_format );
        $pattern     = '^';
        $pattern    .= str_replace( array( 'd', 'm', 'Y' ), array( '(0[1-9]|[12][0-9]|3[01])', '(0[1-9]|1[0-2])', '\d{4}' ), $date_format );
        $pattern     = str_replace( '/', '\/', $pattern );
        $pattern    .= '$';

        $date_format_args = array(
            'format'      => $date_format,
            'placeholder' => $placeholder,
            'pattern'     => $pattern,
        );

        return apply_filters( 'wcvendors_dashboard_date_format_args', $date_format_args );
    }

    /**
     * Filter the start date input field
     *
     * @param array $field The field configuration.
     */
    public function dashboard_start_date_input( $field ) {
        $date_format        = self::get_date_format();
        $object             = get_query_var( 'object' );
        $default_start_date = strtotime( '-1 month' );
        $date_value         = WC()->session->get( 'wcv_dashboard_start_date', $default_start_date );
        switch ( $object ) {
            case 'order':
                $date_value = WC()->session->get( 'wcv_order_start_date', $default_start_date );
                break;
            case 'commission':
                $date_value = WC()->session->get( 'wcv_commission_start_date', $default_start_date );
                break;
        }
        $new_date = new DateTime();
        $new_date->setTimestamp( $date_value );
        $field['value']                        = $new_date->format( $date_format['format'] );
        $field['placeholder']                  = $date_format['placeholder'];
        $field['custom_attributes']['pattern'] = $date_format['pattern'];

        return $field;
    }

    /**
     * Filter the end date input field
     *
     * @param array $field The field configuration.
     */
    public function dashboard_end_date_input( $field ) {
        $date_format      = self::get_date_format();
        $object           = get_query_var( 'object' );
        $default_end_date = strtotime( 'now' );
        $date_value       = WC()->session->get( 'wcv_dashboard_end_date', $default_end_date );
        switch ( $object ) {
            case 'order':
                $date_value = WC()->session->get( 'wcv_order_end_date', $default_end_date );
                break;
            case 'commission':
                $date_value = WC()->session->get( 'wcv_commission_end_date', $default_end_date );
                break;
        }
        $new_date = new DateTime();
        $new_date->setTimestamp( $date_value );
        $field['value']                        = $new_date->format( $date_format['format'] );
        $field['placeholder']                  = $date_format['placeholder'];
        $field['custom_attributes']['pattern'] = $date_format['pattern'];

        return $field;
    }

    /**
     * Change the date format for the datepicker
     *
     * @param string $format The date format.
     */
    public function change_datepicker_localization( $format ) {
        $format = self::get_date_format()['format'];

        return $format;
    }

    /**
     *  Change the class of the table
     *
     * @since    1.9.4
     *
     * @param     string $css_class Class output.
     *
     * @return   string $css_class    filtered class
     */
    public function dashboard_table_class( $css_class ) {
        $css_class = 'wcv-dashboard-table has-background';
        return $css_class;
    }
}
