<?php

/**
 * Custom Class for Woocommerce Settings
 *
 * @link       https://www.wpsaad.com
 * @since      1.0.0
 *
 * @package    ODDW
 * @subpackage ODDW/admin
 */
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
class ODDW_WooCommerce_Settings {
    /**
     * Bootstraps the class and hooks required actions & filters.
     */
    public static function init() {
        add_action( 'admin_menu', __CLASS__ . '::register_admin_menu' );
        add_action( 'admin_init', __CLASS__ . '::maybe_redirect_legacy_settings_url' );
        // Add custom type for the test SMS button.
        add_action(
            'woocommerce_admin_field_custom_type',
            __CLASS__ . '::output_custom_type',
            10,
            1
        );
        add_action( 'admin_enqueue_scripts', __CLASS__ . '::enqueue_admin_assets' );
    }

    /**
     * Defines the tabs for the settings page.
     */
    public static function get_settings_tabs() {
        $tabs = array(
            'general' => __( 'General', 'orders-delivery-drivers-for-woocommerce' ),
            'pages'   => __( 'Pages', 'orders-delivery-drivers-for-woocommerce' ),
        );
        return apply_filters( 'oddw_settings_tabs', $tabs );
    }

    /**
     * Registers the admin menu and submenu.
     */
    public static function register_admin_menu() {
        $capability = apply_filters( 'oddw_settings_capability', 'manage_woocommerce' );
        add_menu_page(
            __( 'Delivery Drivers', 'orders-delivery-drivers-for-woocommerce' ),
            __( 'Delivery Drivers', 'orders-delivery-drivers-for-woocommerce' ),
            $capability,
            'oddw-settings',
            array(__CLASS__, 'render_settings_page'),
            'dashicons-location-alt',
            56
        );
        add_submenu_page(
            'oddw-settings',
            __( 'Settings', 'orders-delivery-drivers-for-woocommerce' ),
            __( 'Settings', 'orders-delivery-drivers-for-woocommerce' ),
            $capability,
            'oddw-settings',
            array(__CLASS__, 'render_settings_page')
        );
    }

    /**
     * Renders the settings page with a tabbed interface.
     */
    public static function render_settings_page() {
        $capability = apply_filters( 'oddw_settings_capability', 'manage_woocommerce' );
        if ( !current_user_can( $capability ) ) {
            wp_die( esc_html__( 'Sorry, you are not allowed to access this page.', 'orders-delivery-drivers-for-woocommerce' ) );
        }
        $tabs = self::get_settings_tabs();
        $current_tab = ( isset( $_GET['tab'] ) ? sanitize_key( $_GET['tab'] ) : 'general' );
        if ( !array_key_exists( $current_tab, $tabs ) ) {
            $current_tab = 'general';
        }
        if ( isset( $_POST['oddw_settings_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['oddw_settings_nonce'] ) ), 'oddw_save_settings' ) ) {
            // If saving pages tab, validate uniqueness of selected pages
            if ( 'pages' === $current_tab && function_exists( 'oddw_is_page_id_unique' ) ) {
                $dashboard = ( isset( $_POST['oddw_settings_dashboard_page_id'] ) ? absint( $_POST['oddw_settings_dashboard_page_id'] ) : 0 );
                $monitor = ( isset( $_POST['oddw_settings_monitor_page_id'] ) ? absint( $_POST['oddw_settings_monitor_page_id'] ) : 0 );
                $app = ( isset( $_POST['oddw_settings_application_page_id'] ) ? absint( $_POST['oddw_settings_application_page_id'] ) : 0 );
                $errors = array();
                if ( $dashboard && !oddw_is_page_id_unique( $dashboard, 'dashboard' ) ) {
                    $errors[] = esc_html__( 'Selected Dashboard page is already assigned to another plugin page.', 'orders-delivery-drivers-for-woocommerce' );
                }
                if ( $monitor && !oddw_is_page_id_unique( $monitor, 'monitor' ) ) {
                    $errors[] = esc_html__( 'Selected Monitor page is already assigned to another plugin page.', 'orders-delivery-drivers-for-woocommerce' );
                }
                if ( $app && !oddw_is_page_id_unique( $app, 'application' ) ) {
                    $errors[] = esc_html__( 'Selected Application page is already assigned to another plugin page.', 'orders-delivery-drivers-for-woocommerce' );
                }
                if ( !empty( $errors ) ) {
                    foreach ( $errors as $err ) {
                        echo '<div class="notice notice-error is-dismissible"><p>' . esc_html( $err ) . '</p></div>';
                    }
                } else {
                    self::update_settings( $current_tab );
                    echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Settings saved.', 'orders-delivery-drivers-for-woocommerce' ) . '</p></div>';
                }
            } else {
                self::update_settings( $current_tab );
                echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Settings saved.', 'orders-delivery-drivers-for-woocommerce' ) . '</p></div>';
            }
        }
        $go_pro = ' | <a href="https://wpsaad.com/wp-plugins/orders-delivery-drivers-for-woocommerce-pro/" target="_blank" style="font-weight:700;">' . __( 'Go Pro', 'orders-delivery-drivers-for-woocommerce' ) . '</a>';
        $box_style = 'padding:10px; background:#fff; border:1px solid #ddd; border-radius:4px; text-align:center; margin:5px;';
        echo '<div class="wrap woocommerce">';
        echo '<div class="oddfw-settings-header" style="' . $box_style . '"><h2 style="font-weight: 600; font-size: 1.5em;">' . esc_html__( 'Orders Delivery Drivers for WooCommerce', 'orders-delivery-drivers-for-woocommerce' ) . '</h2>';
        echo '<h3 style="font-weight: 600; font-size: 1.2em;">' . __( 'Brought to you by', 'orders-delivery-drivers-for-woocommerce' ) . ' <a href="https://www.wpsaad.com" target="_blank">WPSAAD</a>' . $go_pro . '</h3></div>';
        // Output Tab Navigation
        echo '<h2 class="nav-tab-wrapper wp-clearfix">';
        foreach ( $tabs as $tab_key => $tab_label ) {
            $active = ( $current_tab === $tab_key ? 'nav-tab-active' : '' );
            $url = admin_url( 'admin.php?page=oddw-settings&tab=' . $tab_key );
            echo '<a href="' . esc_url( $url ) . '" class="nav-tab ' . esc_attr( $active ) . '">' . esc_html( $tab_label ) . '</a>';
        }
        echo '</h2>';
        echo '<form method="post" id="mainform" action="" enctype="multipart/form-data" style="margin-top:20px;">';
        wp_nonce_field( 'oddw_save_settings', 'oddw_settings_nonce' );
        woocommerce_admin_fields( self::get_settings( $current_tab ) );
        submit_button( __( 'Save changes', 'orders-delivery-drivers-for-woocommerce' ) );
        echo '</form>';
        echo '</div>';
    }

    /**
     * Saves settings for the current tab.
     */
    public static function update_settings( $tab = 'general' ) {
        woocommerce_update_options( self::get_settings( $tab ) );
    }

    /**
     * Returns the array of settings for WooCommerce based on the active tab.
     */
    public static function get_settings( $tab = 'general' ) {
        $settings = array();
        switch ( $tab ) {
            case 'pages':
                $settings = array(
                    'pages_title'      => array(
                        'name' => __( 'Pages', 'orders-delivery-drivers-for-woocommerce' ),
                        'type' => 'title',
                        'desc' => __( 'Manage pages that render plugin shortcodes. Generated pages are created on activation if not present.', 'orders-delivery-drivers-for-woocommerce' ),
                        'id'   => 'oddw_settings_pages_title',
                    ),
                    'dashboard_page'   => array(
                        'name'    => __( 'Driver Dashboard page', 'orders-delivery-drivers-for-woocommerce' ),
                        'type'    => 'select',
                        'id'      => 'oddw_settings_dashboard_page_id',
                        'options' => ( function_exists( 'oddw_get_pages_options' ) ? oddw_get_pages_options() : array() ),
                        'desc'    => __( 'Select a page that will display the driver dashboard shortcode.', 'orders-delivery-drivers-for-woocommerce' ),
                    ),
                    'monitor_page'     => array(
                        'name'    => __( 'Orders monitor page (premium)', 'orders-delivery-drivers-for-woocommerce' ),
                        'type'    => 'select',
                        'id'      => 'oddw_settings_monitor_page_id',
                        'options' => ( function_exists( 'oddw_get_pages_options' ) ? oddw_get_pages_options() : array() ),
                        'desc'    => __( 'Select a page that will display the orders monitor shortcode (premium).', 'orders-delivery-drivers-for-woocommerce' ),
                    ),
                    'application_page' => array(
                        'name'    => __( 'Driver application page (premium)', 'orders-delivery-drivers-for-woocommerce' ),
                        'type'    => 'select',
                        'id'      => 'oddw_settings_application_page_id',
                        'options' => ( function_exists( 'oddw_get_pages_options' ) ? oddw_get_pages_options() : array() ),
                        'desc'    => __( 'Select a page that will display the driver application form shortcode (premium).', 'orders-delivery-drivers-for-woocommerce' ),
                    ),
                    'pages_end'        => array(
                        'type' => 'sectionend',
                        'id'   => 'oddw_settings_pages_end',
                    ),
                );
                break;
            case 'general':
                $settings = array(
                    'section_title'              => array(
                        'name' => __( 'General Settings', 'orders-delivery-drivers-for-woocommerce' ),
                        'type' => 'title',
                        'id'   => 'oddw_settings_section_title',
                    ),
                    'dispatch_phone_number'      => array(
                        'name'              => __( 'Dispatch phone number', 'orders-delivery-drivers-for-woocommerce' ),
                        'type'              => 'text',
                        'custom_attributes' => array(
                            'size' => 15,
                        ),
                        'desc'              => __( 'Allow your drivers to call if they have questions about an order.', 'orders-delivery-drivers-for-woocommerce' ),
                        'id'                => 'oddw_settings_dispatch_phone_number',
                    ),
                    'google_maps_api_key'        => array(
                        'name'              => __( 'Google Maps API key', 'orders-delivery-drivers-for-woocommerce' ),
                        'type'              => 'text',
                        'custom_attributes' => array(
                            'size' => 50,
                        ),
                        'desc'              => __( 'Add a map to the order directions for your drivers. A Google Maps API key is required.', 'orders-delivery-drivers-for-woocommerce' ),
                        'id'                => 'oddw_settings_google_maps_api_key',
                    ),
                    'driver_ratings'             => array(
                        'name'    => __( 'Driver ratings', 'orders-delivery-drivers-for-woocommerce' ),
                        'type'    => 'select',
                        'desc'    => __( 'Add driver details with delivery star ratings to order details page.', 'orders-delivery-drivers-for-woocommerce' ),
                        'id'      => 'oddw_settings_driver_ratings',
                        'css'     => 'min-width: 100px;',
                        'options' => array(
                            'yes' => 'Yes',
                            'no'  => 'No',
                        ),
                    ),
                    'driver_phone_number'        => array(
                        'name'    => __( 'Driver phone number', 'orders-delivery-drivers-for-woocommerce' ),
                        'type'    => 'select',
                        'desc'    => __( 'Add a button for customers to call driver in the driver details.', 'orders-delivery-drivers-for-woocommerce' ),
                        'id'      => 'oddw_settings_driver_phone_number',
                        'css'     => 'min-width: 100px;',
                        'options' => array(
                            'yes' => 'Yes',
                            'no'  => 'No',
                        ),
                    ),
                    'customer_ofd_notifications' => array(
                        'name'    => __( 'Customer notifications', 'orders-delivery-drivers-for-woocommerce' ),
                        'type'    => 'select',
                        'desc'    => __( 'Email/SMS customer when order is marked out for delivery.', 'orders-delivery-drivers-for-woocommerce' ),
                        'id'      => 'oddw_settings_customer_ofd_notifications',
                        'css'     => 'min-width: 100px;',
                        'options' => array(
                            'yes' => 'Yes',
                            'no'  => 'No',
                        ),
                        'default' => 'no',
                    ),
                    'section_end'                => array(
                        'type' => 'sectionend',
                        'id'   => 'oddw_settings_section_end',
                    ),
                );
                break;
        }
        return apply_filters( 'oddw_woocommerce_settings', $settings, $tab );
    }

    public static function output_custom_type( $value ) {
        $allowed = array(
            'button' => array(
                'type'  => true,
                'name'  => true,
                'class' => true,
                'id'    => true,
            ),
            'input'  => array(
                'type'  => true,
                'name'  => true,
                'value' => true,
                'id'    => true,
            ),
            'p'      => array(
                'class' => true,
                'style' => true,
            ),
            'div'    => array(
                'id'    => true,
                'class' => true,
                'style' => true,
            ),
        );
        echo wp_kses( $value['desc'], $allowed );
    }

    public static function enqueue_admin_assets( $hook ) {
        if ( 'toplevel_page_oddw-settings' !== $hook ) {
            return;
        }
    }

    public static function maybe_redirect_legacy_settings_url() {
        if ( !is_admin() ) {
            return;
        }
        $page = (string) filter_input( INPUT_GET, 'page', FILTER_SANITIZE_SPECIAL_CHARS );
        $tab = (string) filter_input( INPUT_GET, 'tab', FILTER_SANITIZE_SPECIAL_CHARS );
        if ( 'wc-settings' === sanitize_key( $page ) && 'orders-delivery-drivers-for-woocommerce' === sanitize_key( $tab ) ) {
            wp_safe_redirect( admin_url( 'admin.php?page=oddw-settings' ) );
            exit;
        }
    }

    private static function get_test_sms_last_notice_html() {
        $n = get_transient( 'oddw_test_sms_notice' );
        return ( $n ? '<p class="description">' . esc_html( $n['message'] ) . '</p>' : '' );
    }

}

ODDW_WooCommerce_Settings::init();
/**
 * Driver Login Redirect
 */
add_filter(
    'woocommerce_login_redirect',
    function ( $redirect, $user ) {
        if ( !is_a( $user, 'WP_User' ) ) {
            return $redirect;
        }
        if ( 'driver' == $user->roles[0] && url_to_postid( $redirect ) != wc_get_page_id( 'checkout' ) ) {
            return apply_filters( 'oddw_driver_dashboard_login_redirect', get_permalink( wc_get_page_id( 'myaccount' ) ) . '/driver-dashboard/' );
        }
        return $redirect;
    },
    10,
    2
);
/**
 * Address Formatting for Maps
 */
add_filter( 'woocommerce_order_formatted_shipping_address', function ( $address ) {
    if ( is_array( $address ) ) {
        unset($address['first_name'], $address['last_name']);
    }
    return $address;
} );