<?php
/**
 * Total Processing Gateway Logger - Order Metabox
 * 
 * Displays gateway logs in order edit page
 *
 * @package TotalProcessing
 * @subpackage Gateway_Logger
 */

if (!defined('ABSPATH')) {
    exit;
}

class TP_Logs_Metabox {
    
    /**
     * Allowed gateways that support logging
     */
    private static $allowed_gateways = ['wc_tpapv2'];
    
    /**
     * Initialize metabox hooks
     */
    public static function init() {
        // Add metabox for both CPT and HPOS
        add_action('add_meta_boxes', [__CLASS__, 'add_metabox'], 10, 2);
        add_action('add_meta_boxes_woocommerce_page_wc-orders', [__CLASS__, 'add_metabox_hpos']);
        
        // AJAX handlers
        add_action('wp_ajax_tp_load_order_logs', [__CLASS__, 'ajax_load_logs']);
        add_action('wp_ajax_tp_clear_order_logs', [__CLASS__, 'ajax_clear_logs']);
        
        // Enqueue scripts
        add_action('admin_enqueue_scripts', [__CLASS__, 'enqueue_scripts']);
    
        // Hide metabox by default
        add_filter('default_hidden_meta_boxes', [__CLASS__, 'hide_metabox_by_default'], 10, 2);
    }
    
    /**
     * Add metabox (CPT)
     *
     * @param string $post_type
     * @param WP_Post|WC_Order $post_or_order
     */
    public static function add_metabox($post_type, $post_or_order) {
        if ($post_type !== 'shop_order') {
            return;
        }
        
        $order = $post_or_order instanceof WP_Post ? wc_get_order($post_or_order->ID) : $post_or_order;
        
        if (!$order || !self::should_show_metabox($order)) {
            return;
        }
        
        add_meta_box(
            'tp_gateway_logs',
            '🔍 Gateway Transaction Logs',
            [__CLASS__, 'render_metabox'],
            'shop_order',
            'normal',
            'default'
        );
    }
    
    /**
     * Add metabox (HPOS)
     */
    public static function add_metabox_hpos() {
        global $post, $theorder;
        
        $order = $theorder ?? ($post ? wc_get_order($post->ID) : null);
        
        if (!$order || !self::should_show_metabox($order)) {
            return;
        }
        
        add_meta_box(
            'tp_gateway_logs',
            '🔍 Gateway Transaction Logs',
            [__CLASS__, 'render_metabox'],
            'woocommerce_page_wc-orders',
            'normal',
            'default'
        );
    }
    
    /**
     * Check if metabox should be shown
     *
     * @param WC_Order $order
     * @return bool
     */
    private static function should_show_metabox($order) {
        $payment_method = $order->get_payment_method();
        return in_array($payment_method, self::$allowed_gateways);
    }
    
    /**
     * Render metabox content
     *
     * @param WP_Post|WC_Order $post_or_order
     */
    public static function render_metabox($post_or_order) {
        $order = $post_or_order instanceof WP_Post ? wc_get_order($post_or_order->ID) : $post_or_order;
        $order_id = $order->get_id();
        
        include dirname(__FILE__) . '/views/metabox-content.php';
    }
    
    /**
     * AJAX: Load order logs
     */
    public static function ajax_load_logs() {
        check_ajax_referer('tp_order_logs', 'nonce');
        
        if (!current_user_can('edit_shop_orders')) {
            wp_send_json_error(['message' => 'Permission denied.']);
        }
        
        $order_id = isset($_POST['order_id']) ? absint($_POST['order_id']) : 0;
        $offset = isset($_POST['offset']) ? absint($_POST['offset']) : 0;
        $filter = isset($_POST['filter']) ? sanitize_text_field($_POST['filter']) : '';
        
        if (!$order_id) {
            wp_send_json_error(['message' => 'Invalid order ID.']);
        }

        $order = wc_get_order( $order_id );

        $checkout_id = $order->get_meta('_applepay_checkout_id', true);
        
        $args = [
            'order_id' => $order_id,
            'checkout_id' => $checkout_id,
            'limit' => 20,
            'offset' => $offset,
        ];
        
        if (!empty($filter) && $filter !== 'all') {
            $args['log_level'] = $filter;
        }
        
        $logs = TP_Gateway_Logger::get_logs($args);
        $total_count = TP_Gateway_Logger::get_logs_count(['order_id' => $order_id]);
        
        $html = '';
        if (!empty($logs)) {
            foreach ($logs as $log) {
                $html .= self::render_log_entry($log);
            }
        } else {
            $html = '<div class="tp-log-empty">No logs found for this order.</div>';
        }
        
        wp_send_json_success([
            'html' => $html,
            'total' => $total_count,
            'loaded' => $offset + count($logs),
            'has_more' => ($offset + count($logs)) < $total_count
        ]);
    }
    
    /**
     * AJAX: Clear order logs
     */
    public static function ajax_clear_logs() {
        check_ajax_referer('tp_order_logs', 'nonce');
        
        if (!current_user_can('edit_shop_orders')) {
            wp_send_json_error(['message' => 'Permission denied.']);
        }
        
        $order_id = isset($_POST['order_id']) ? absint($_POST['order_id']) : 0;
        
        if (!$order_id) {
            wp_send_json_error(['message' => 'Invalid order ID.']);
        }
        
        $deleted = TP_Gateway_Logger::delete_order_logs($order_id);
        
        if ($deleted !== false) {
            wp_send_json_success([
                'message' => sprintf('Successfully deleted %d log entries.', $deleted)
            ]);
        } else {
            wp_send_json_error(['message' => 'Failed to delete logs.']);
        }
    }
    
    /**
     * Render single log entry
     *
     * @param object $log
     * @return string
     */
    private static function render_log_entry($log) {
        $level_class = 'tp-log-' . $log->log_level;
        $level_icon = self::get_level_icon($log->log_level);
        $level_label = ucfirst($log->log_level);
        
        $time = new DateTime($log->created_at);
        $time_ago = human_time_diff(strtotime($log->created_at), current_time('timestamp')) . ' ago';
        $time_exact = $time->format('F j, Y g:i:s A');
        
        $log_data = !empty($log->log_data) ? json_decode($log->log_data, true) : null;
        
        ob_start();
        ?>
        <div class="tp-log-entry <?php echo esc_attr($level_class); ?>">
            <div class="tp-log-header">
                <span class="tp-log-level">
                    <?php echo $level_icon; ?> <?php echo esc_html($level_label); ?>
                </span>
                <span class="tp-log-time" title="<?php echo esc_attr($time_exact); ?>">
                    <?php echo esc_html($time_ago); ?>
                </span>
            </div>
            
            <div class="tp-log-message">
                <?php echo esc_html($log->message); ?>
            </div>
            
            <?php if ($log->transaction_id || $log->checkout_id): ?>
            <div class="tp-log-meta">
                <?php if ($log->transaction_id): ?>
                <span class="tp-log-meta-item">
                    <strong>Transaction ID:</strong> <code><?php echo esc_html($log->transaction_id); ?></code>
                </span>
                <?php endif; ?>
                
                <?php if ($log->checkout_id): ?>
                <span class="tp-log-meta-item">
                    <strong>Checkout ID:</strong> <code><?php echo esc_html($log->checkout_id); ?></code>
                </span>
                <?php endif; ?>
            </div>
            <?php endif; ?>
            
            <?php if ($log_data && !empty($log_data)): ?>
            <div class="tp-log-data-toggle">
                <a href="#" class="tp-toggle-data">📦 Show Data</a>
            </div>
            <div class="tp-log-data" style="display: none;">
                <pre><?php echo esc_html(json_encode($log_data, JSON_PRETTY_PRINT)); ?></pre>
            </div>
            <?php endif; ?>
            
            <?php if ($log->stack_trace): ?>
            <div class="tp-log-data-toggle">
                <a href="#" class="tp-toggle-stack">📍 Show Stack Trace</a>
            </div>
            <div class="tp-log-stack" style="display: none;">
                <pre><?php echo esc_html($log->stack_trace); ?></pre>
            </div>
            <?php endif; ?>
        </div>
        <?php
        return ob_get_clean();
    }
    
    /**
     * Get level icon
     *
     * @param string $level
     * @return string
     */
    private static function get_level_icon($level) {
        $icons = [
            'error' => '🔴',
            'warning' => '⚠️',
            'info' => 'ℹ️',
            'success' => '✅'
        ];
        
        return $icons[$level] ?? '•';
    }
    
    /**
     * Enqueue scripts and styles
     *
     * @param string $hook
     */
    public static function enqueue_scripts($hook) {
        if (!in_array($hook, ['post.php', 'woocommerce_page_wc-orders'])) {
            return;
        }
        
        global $post, $theorder;
        $order = $theorder ?? ($post ? wc_get_order($post->ID) : null);
        
        if (!$order || !self::should_show_metabox($order)) {
            return;
        }
        
        wp_enqueue_style(
            'tp-gateway-logs',
            TOTALPROCESSING_PAYMENTGATEWAY_PLUGIN_BASEURL . 'includes/logger/admin/assets/css/tp-gateway-logs.css',
            [],
            TP_APPLEPAY_VERSION
        );
        
        wp_enqueue_script(
            'tp-gateway-logs',
            TOTALPROCESSING_PAYMENTGATEWAY_PLUGIN_BASEURL . 'includes/logger/admin/assets/js/tp-gateway-logs.js',
            ['jquery'],
            TP_APPLEPAY_VERSION,
            true
        );
        
        wp_localize_script('tp-gateway-logs', 'tpLogsData', [
            'ajaxurl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('tp_order_logs'),
            'order_id' => $order->get_id(),
        ]);
    }

    /**
     * Hide metabox by default in Screen Options
     *
     * @param array $hidden Array of hidden metaboxes
     * @param WP_Screen $screen Current screen
     * @return array
     */
    public static function hide_metabox_by_default($hidden, $screen) {
        // For CPT orders
        if ($screen->id === 'shop_order') {
            $hidden[] = 'tp_gateway_logs';
        }
    
        // For HPOS orders
        if ($screen->id === 'woocommerce_page_wc-orders') {
            $hidden[] = 'tp_gateway_logs';
        }
    
        return $hidden;
    }
}

// Initialize
TP_Logs_Metabox::init();
