<?php

namespace WDevs\CustomerOrderExport\Public;

use WDevs\CustomerOrderExport\Helper;
use WDevs\CustomerOrderExport\Clients\GoogleDriveClient;
use WDevs\CustomerOrderExport\Channels\GoogleDriveChannel;
use WDevs\CustomerOrderExport\Channels\ChannelFactory;
/**
 * The public-facing functionality of the plugin.
 *
 * @link       https://wijnberg.dev
 * @since      1.0.0
 *
 * @package    CustomerOrderExport
 * @subpackage CustomerOrderExport/public
 */
/**
 * The public-facing functionality of the plugin.
 *
 * Defines the plugin name, version, and hooks for the customer account functionality.
 *
 * @package    CustomerOrderExport
 * @subpackage CustomerOrderExport/public
 * @author     Wijnberg Developments <contact@wijnberg.dev>
 */
class CustomerOrderExportPublic {
    use Helper;
    /**
     * The ID of this plugin.
     *
     * @since    1.0.0
     * @access   private
     * @var      string $plugin_name The ID of this plugin.
     */
    private $plugin_name;

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

    /**
     * The endpoint name for the customer account page.
     *
     * @since    1.0.0
     */
    const ACCOUNT_ENDPOINT = 'wdevs-order-export-channels';

    /**
     * The nonce field name for channel forms.
     *
     * @since    1.0.0
     */
    const CHANNEL_NONCE_FIELD = 'wdevs_coe_edit_channel_nonce';

    /**
     * Initialize the class and set its properties.
     *
     * @param string $plugin_name The name of the plugin.
     * @param string $version The version of this plugin.
     *
     * @since    1.0.0
     */
    public function __construct( $plugin_name, $version ) {
        $this->plugin_name = $plugin_name;
        $this->version = $version;
    }

    /**
     * Add our endpoint to WooCommerce's query vars.
     *
     * @param array $query_vars WooCommerce query vars.
     *
     * @return array Modified query vars.
     * @since    1.0.0
     */
    public function register_account_endpoint( $query_vars ) {
        $query_vars[self::ACCOUNT_ENDPOINT] = self::ACCOUNT_ENDPOINT;
        return $query_vars;
    }

    /**
     * Add the export channels menu item to the customer account menu.
     *
     * @param array $items The existing menu items.
     *
     * @return array The modified menu items.
     * @since    1.0.0
     */
    public function add_account_menu_item( $items ) {
        if ( !$this->is_account_tab_enabled() ) {
            return $items;
        }
        // Insert before logout if it exists
        $logout = null;
        if ( isset( $items['customer-logout'] ) ) {
            $logout = $items['customer-logout'];
            unset($items['customer-logout']);
        }
        $items[self::ACCOUNT_ENDPOINT] = __( 'Export Channels', 'orderbridge-for-woocommerce' );
        // Re-add logout if it existed
        if ( $logout !== null ) {
            $items['customer-logout'] = $logout;
        }
        return $items;
    }

    /**
     * Render the export channels account page content.
     *
     * @since    1.0.0
     */
    public function render_account_page() {
        if ( !$this->is_account_tab_enabled() ) {
            wc_print_notice( __( 'Export channels are not available.', 'orderbridge-for-woocommerce' ), 'error' );
            return;
        }
        // Check if we're viewing a specific channel
        global $wp;
        $channel_slug = ( isset( $wp->query_vars[self::ACCOUNT_ENDPOINT] ) ? sanitize_text_field( $wp->query_vars[self::ACCOUNT_ENDPOINT] ) : '' );
        if ( $channel_slug ) {
            // Render individual channel configuration page
            $this->render_channel_edit_page( $channel_slug );
        } else {
            // Render channel overview page
            $this->render_channels_overview();
        }
    }

    /**
     * Render the channels overview page
     *
     * @since 1.0.0
     */
    private function render_channels_overview() {
        // Prepare view data
        $view_data = [];
        $view_data['endpoint'] = self::ACCOUNT_ENDPOINT;
        $google_drive_channel = ChannelFactory::get_channel_by_slug( GoogleDriveChannel::get_slug() );
        if ( $google_drive_channel ) {
            $view_data['channels'][] = $google_drive_channel;
        }
        include_once plugin_dir_path( __FILE__ ) . 'partials/section-wdevs-customer-order-export-channels.php';
    }

    /**
     * Render the channel edit page
     *
     * @param string $channel_slug The channel slug
     *
     * @since 1.0.0
     */
    private function render_channel_edit_page( $channel_slug ) {
        // Only allow specific channels on account page
        $channel = ChannelFactory::get_channel_by_slug( $channel_slug );
        if ( !$channel ) {
            // Unknown or not allowed channel, redirect to overview
            wp_safe_redirect( wc_get_endpoint_url( self::ACCOUNT_ENDPOINT ) );
            exit;
        }
        // Prepare view data
        $view_data = [];
        $view_data['endpoint'] = self::ACCOUNT_ENDPOINT;
        $view_data['channel'] = $channel;
        $view_data['nonce_field'] = self::CHANNEL_NONCE_FIELD;
        include plugin_dir_path( __FILE__ ) . 'partials/section-wdevs-customer-order-export-channel-edit.php';
    }

    /**
     * Set the page title for the export channels endpoint.
     *
     * @param string $title The current title.
     *
     * @return string The modified title.
     * @since    1.0.0
     */
    public function set_account_page_title( $title ) {
        return __( 'Export Channels', 'orderbridge-for-woocommerce' );
    }

    /**
     * Enqueue styles for the account page.
     *
     * @since    1.0.0
     */
    public function enqueue_styles() {
        if ( is_wc_endpoint_url( self::ACCOUNT_ENDPOINT ) ) {
            wp_enqueue_style(
                $this->plugin_name . '-account',
                plugin_dir_url( __FILE__ ) . 'css/wdevs-customer-order-export-account.css',
                array(),
                $this->version,
                'all'
            );
        }
    }

    /**
     * Enqueue scripts for the account page.
     *
     * @since    1.0.0
     */
    public function enqueue_scripts() {
        if ( is_wc_endpoint_url( self::ACCOUNT_ENDPOINT ) ) {
            // Enqueue main account page scripts
            $script_asset = (require plugin_dir_path( dirname( __FILE__ ) ) . 'build/wdevs-coe-public.asset.php');
            $public_handle = $this->plugin_name . '-account';
            wp_enqueue_script(
                $public_handle,
                plugin_dir_url( dirname( __FILE__ ) ) . 'build/wdevs-coe-public.js',
                array_merge( $script_asset['dependencies'], ['jquery'] ),
                $script_asset['version'],
                true
            );
            // Localize account page scripts with clean data
            wp_localize_script( $public_handle, 'wdceoAccount', [
                'messages' => [
                    'copied'             => __( 'Copied!', 'orderbridge-for-woocommerce' ),
                    'copy_failed'        => __( 'Copy failed', 'orderbridge-for-woocommerce' ),
                    'disconnect_confirm' => __( 'Are you sure you want to disconnect Google Drive?', 'orderbridge-for-woocommerce' ),
                ],
            ] );
        }
    }

    /**
     * Get channel slug from WordPress query vars or URL parsing
     *
     * First tries to get the channel slug from WordPress query variables.
     * If that fails (common with OAuth callbacks), falls back to parsing the URL directly.
     *
     * @return string Channel slug or empty string if not found
     * @since    1.0.0
     */
    private function get_channel_slug_from_url() {
        global $wp;
        // First try: WordPress query variables (most reliable)
        $channel_slug = ( isset( $wp->query_vars[self::ACCOUNT_ENDPOINT] ) ? sanitize_text_field( $wp->query_vars[self::ACCOUNT_ENDPOINT] ) : '' );
        if ( !empty( $channel_slug ) ) {
            return $channel_slug;
        }
        // Fallback: Parse from URL directly (for OAuth callbacks and edge cases)
        return '';
    }

    /**
     * Process channel form submissions and OAuth callbacks.
     *
     * @since    1.0.0
     */
    public function process_channel_form() {
        // Only process on our endpoint
        if ( !is_wc_endpoint_url( self::ACCOUNT_ENDPOINT ) ) {
            return;
        }
        // User must be logged in
        if ( !is_user_logged_in() ) {
            wp_safe_redirect( wc_get_endpoint_url( self::ACCOUNT_ENDPOINT ) );
            exit;
        }
        $channel_slug = $this->get_channel_slug_from_url();
        // If no channel slug, we're on overview page - nothing to process
        if ( empty( $channel_slug ) ) {
            return;
        }
        // Get channel instance - we always need a channel from this point
        $channel = ChannelFactory::get_channel_by_slug( $channel_slug );
        if ( !$channel ) {
            wp_safe_redirect( wc_get_endpoint_url( self::ACCOUNT_ENDPOINT ) );
            exit;
        }
        // Handle OAuth callbacks (GET requests with action=oauth_callback)
        if ( isset( $_GET['action'] ) && sanitize_text_field( wp_unslash( $_GET['action'] ) ) === 'oauth_callback' ) {
            $result = $channel->handle_oauth_callback();
            // Add success/error notice
            if ( isset( $result['success'] ) && $result['success'] ) {
                wc_add_notice( $result['message'], 'success' );
            } else {
                wc_add_notice( $result['message'] ?? __( 'OAuth callback failed.', 'orderbridge-for-woocommerce' ), 'error' );
            }
            wp_safe_redirect( wc_get_endpoint_url( self::ACCOUNT_ENDPOINT, $channel_slug ) );
            exit;
        }
        // Handle disconnect actions (GET requests with action=disconnect_*)
        if ( isset( $_GET['action'] ) && strpos( sanitize_text_field( wp_unslash( $_GET['action'] ) ), 'disconnect_' ) === 0 ) {
            $result = $channel->process_account_form( [] );
            // Add success/error notice
            if ( isset( $result['success'] ) && $result['success'] ) {
                wc_add_notice( $result['message'], 'success' );
            } else {
                wc_add_notice( $result['message'] ?? __( 'Disconnect failed.', 'orderbridge-for-woocommerce' ), 'error' );
            }
            wp_safe_redirect( wc_get_endpoint_url( self::ACCOUNT_ENDPOINT, $channel_slug ) );
            exit;
        }
        // Only process POST requests for form submissions
        if ( 'POST' !== sanitize_text_field( wp_unslash( $_SERVER['REQUEST_METHOD'] ?? '' ) ) || empty( $_POST ) ) {
            return;
        }
        $action = ( isset( $_POST['action'] ) ? sanitize_text_field( wp_unslash( $_POST['action'] ) ) : '' );
        if ( 'edit_channel' === $action ) {
            // Verify nonce
            if ( !isset( $_POST[self::CHANNEL_NONCE_FIELD] ) ) {
                wp_safe_redirect( wc_get_endpoint_url( self::ACCOUNT_ENDPOINT ) );
                exit;
            }
            $nonce_value = sanitize_text_field( wp_unslash( $_POST[self::CHANNEL_NONCE_FIELD] ) );
            $nonce_action = 'wdevs_coe_edit_channel_' . $channel_slug;
            if ( !wp_verify_nonce( $nonce_value, $nonce_action ) ) {
                wp_safe_redirect( wc_get_endpoint_url( self::ACCOUNT_ENDPOINT ) );
                exit;
            }
            // Sanitize all POST data
            $sanitized_post = [];
            foreach ( $_POST as $key => $value ) {
                if ( is_array( $value ) ) {
                    $sanitized_post[sanitize_key( $key )] = array_map( 'sanitize_text_field', array_map( 'wp_unslash', $value ) );
                } else {
                    $sanitized_post[sanitize_key( $key )] = sanitize_text_field( wp_unslash( $value ) );
                }
            }
            $channel->process_account_form( $sanitized_post );
            wp_safe_redirect( wc_get_endpoint_url( self::ACCOUNT_ENDPOINT, $channel_slug ) );
            exit;
        }
    }

    /**
     * Check if the customer account tab should be enabled.
     *
     * @return bool True if the tab should be enabled, false otherwise.
     * @since    1.0.0
     */
    public function is_account_tab_enabled() {
        //if ( wdevs_coe_fs()->can_use_premium_code__premium_only() ) {
        $google_drive_channel = ChannelFactory::get_channel_by_slug( GoogleDriveChannel::get_slug() );
        if ( $google_drive_channel && $google_drive_channel->is_enabled() ) {
            return true;
        }
        //}
        return false;
    }

}
