<?php
/**
 * Total Processing Gateway Logger - Settings Integration
 * 
 * Adds logging settings to gateway configuration
 *
 * @package TotalProcessing
 * @subpackage Gateway_Logger
 */

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

class TP_Logs_Settings {
    
    /**
     * Initialize settings hooks
     */
    public static function init() {
        add_action('init', [__CLASS__, 'schedule_cleanup']);
        add_action('tp_gateway_logs_cleanup', [__CLASS__, 'run_cleanup']);
        add_action('wp_ajax_tp_purge_gateway_logs', [__CLASS__, 'ajax_purge_logs']);
    }
    
    /**
     * Get logging settings fields
     *
     * @param string $gateway_id Gateway ID
     * @return array
     */
    public static function get_settings_fields($gateway_id) {
        $stats = TP_Gateway_Logger_Table::get_gateway_stats($gateway_id);
        $table_stats = TP_Gateway_Logger_Table::get_table_stats();
        
        return [
            'gateway_logs_section_title' => [
                'title' => 'Gateway Logging Settings',
                'type' => 'title',
                'description' => 'Configure transaction logging for debugging and troubleshooting.',
            ],
            
            'gateway_logging_enabled' => [
                'title' => 'Enable Gateway Logging',
                'label' => 'Enable transaction logging',
                'type' => 'checkbox',
                'description' => 'Logs critical payment events to database for troubleshooting. <strong>Enabled by default.</strong>',
                'default' => 'yes',
                'class' => 'wppd-ui-toggle',
            ],
            
            'gateway_log_retention' => [
                'title' => 'Automatic Log Cleanup',
                'type' => 'select',
                'description' => 'Logs older than this period are <strong>automatically deleted daily at 3 AM</strong> to prevent database growth.',
                'default' => '30',
                'options' => [
                    '7' => 'Delete after 7 days',
                    '14' => 'Delete after 14 days',
                    '30' => 'Delete after 30 days (Recommended)',
                    '60' => 'Delete after 60 days',
                    '90' => 'Delete after 90 days',
                    '0' => 'Never delete (Not recommended)',
                ],
                'desc_tip' => false,
            ],
            
            'gateway_logs_info' => [
                'type' => 'title',
                'description' => self::get_stats_html($gateway_id, $stats, $table_stats),
            ],
            
            'gateway_logs_purge' => [
                'title' => 'Manual Purge',
                'type' => 'tp_purge_button',
                'description' => 'Immediately delete all logs for this gateway (ignores retention setting)',
                'gateway_id' => $gateway_id,
            ],
            
            'gateway_logs_section_end' => [
                'type' => 'sectionend',
            ],
        ];
    }
    
    /**
     * Get statistics HTML
     *
     * @param string $gateway_id Gateway ID
     * @param array $stats Gateway stats
     * @param array $table_stats Table stats
     * @return string
     */
    private static function get_stats_html($gateway_id, $stats, $table_stats) {
        $settings = get_option('woocommerce_' . $gateway_id . '_settings', []);
        $retention = isset($settings['gateway_log_retention']) ? (int)$settings['gateway_log_retention'] : 30;
        
        $html = '<div class="notice notice-info inline" style="margin: 10px 0;">';
        $html .= '<p><strong>📊 Current Statistics:</strong></p>';
        $html .= '<ul style="list-style: disc; margin-left: 20px;">';
        $html .= '<li><strong>Total Logs:</strong> ' . number_format($stats['total']) . ' ';
        $html .= '(<span style="color:#d63638;">' . $stats['errors'] . ' errors</span>, ';
        $html .= '<span style="color:#dba617;">' . $stats['warnings'] . ' warnings</span>, ';
        $html .= '<span style="color:#2271b1;">' . $stats['info'] . ' info</span>, ';
        $html .= '<span style="color:#00a32a;">' . $stats['success'] . ' success</span>)</li>';
        
        if ($table_stats['oldest_log']) {
            $oldest_date = new DateTime($table_stats['oldest_log']);
            $html .= '<li><strong>Oldest Log:</strong> ' . $oldest_date->format('F j, Y g:i A') . '</li>';
        }
        
        $html .= '<li><strong>Retention Period:</strong> ' . ($retention > 0 ? $retention . ' days' : 'Forever (not recommended)') . '</li>';
        $html .= '<li><strong>Database Size:</strong> ' . number_format($table_stats['size_mb'], 2) . ' MB</li>';
        $html .= '</ul>';
        $html .= '<p><em>💡 Automatic cleanup runs daily at 3:00 AM server time.</em></p>';
        $html .= '</div>';
        
        return $html;
    }
    
    /**
     * Render custom purge button field
     *
     * @param string $key Field key
     * @param array $data Field data
     * @return string
     */
    public static function render_purge_button($key, $data) {
        $field_key = $data['field_key'] ?? $key;
        $gateway_id = $data['gateway_id'] ?? '';
        
        ob_start();
        ?>
        <tr valign="top">
            <th scope="row" class="titledesc">
                <label for="<?php echo esc_attr($field_key); ?>"><?php echo esc_html($data['title']); ?></label>
            </th>
            <td class="forminp">
                <button 
                    type="button" 
                    class="button button-secondary tp-purge-gateway-logs-btn" 
                    data-gateway-id="<?php echo esc_attr($gateway_id); ?>"
                    style="color: #d63638; border-color: #d63638;">
                    🗑️ Purge All Logs
                </button>
                <p class="description"><?php echo wp_kses_post($data['description']); ?></p>
                
                <script type="text/javascript">
                jQuery(document).ready(function($) {
                    $('.tp-purge-gateway-logs-btn').on('click', function(e) {
                        e.preventDefault();
                        
                        if (!confirm('⚠️ Are you sure you want to delete ALL logs for this gateway?\n\nThis action cannot be undone.')) {
                            return;
                        }
                        
                        var $btn = $(this);
                        var gatewayId = $btn.data('gateway-id');
                        
                        $btn.prop('disabled', true).text('Purging...');
                        
                        $.ajax({
                            url: ajaxurl,
                            type: 'POST',
                            data: {
                                action: 'tp_purge_gateway_logs',
                                gateway_id: gatewayId,
                                nonce: '<?php echo wp_create_nonce('tp_purge_logs'); ?>'
                            },
                            success: function(response) {
                                if (response.success) {
                                    alert('✅ ' + response.data.message);
                                    location.reload();
                                } else {
                                    alert('❌ ' + response.data.message);
                                    $btn.prop('disabled', false).text('🗑️ Purge All Logs');
                                }
                            },
                            error: function() {
                                alert('❌ An error occurred. Please try again.');
                                $btn.prop('disabled', false).text('🗑️ Purge All Logs');
                            }
                        });
                    });
                });
                </script>
            </td>
        </tr>
        <?php
        return ob_get_clean();
    }
    
    /**
     * Schedule cleanup cron job
     */
    public static function schedule_cleanup() {
        if (!wp_next_scheduled('tp_gateway_logs_cleanup')) {
            wp_schedule_event(strtotime('03:00:00'), 'daily', 'tp_gateway_logs_cleanup');
        }
    }
    
    /**
     * Run cleanup for all gateways
     */
    public static function run_cleanup() {
        $gateways = ['wc_tpapv2']; // Add other TP gateways here
        
        foreach ($gateways as $gateway_id) {
            $settings = get_option('woocommerce_' . $gateway_id . '_settings', []);
            
            // Skip if logging disabled
            if (empty($settings['gateway_logging_enabled']) || $settings['gateway_logging_enabled'] !== 'yes') {
                continue;
            }
            
            // Get retention period (default 30 days)
            $retention_days = isset($settings['gateway_log_retention']) ? (int)$settings['gateway_log_retention'] : 30;
            
            // Skip if set to "Forever" (0)
            if ($retention_days === 0) {
                continue;
            }
            
            // Delete old logs
            $deleted = TP_Gateway_Logger::cleanup_old_logs($gateway_id, $retention_days);
            
            if ($deleted > 0) {
                error_log("TP Gateway Logs: Deleted {$deleted} old logs for {$gateway_id} (older than {$retention_days} days)");
            }
        }
    }
    
    /**
     * AJAX handler for manual log purge
     */
    public static function ajax_purge_logs() {
        check_ajax_referer('tp_purge_logs', 'nonce');
        
        if (!current_user_can('manage_woocommerce')) {
            wp_send_json_error(['message' => 'Permission denied.']);
        }
        
        $gateway_id = isset($_POST['gateway_id']) ? sanitize_text_field($_POST['gateway_id']) : '';
        
        if (empty($gateway_id)) {
            wp_send_json_error(['message' => 'Invalid gateway ID.']);
        }
        
        $deleted = TP_Gateway_Logger::delete_gateway_logs($gateway_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.']);
        }
    }
}

// Initialize
TP_Logs_Settings::init();
