<?php
/**
 * PHP Support Redirect Integration
 * For WordPress, Laravel, or any PHP-based system
 */

class SupportRedirect
{
    private $systemUrl;
    private $tenantSlug;
    private $timeout;
    private $maxRetries;

    public function __construct($systemUrl, $tenantSlug, $options = [])
    {
        $this->systemUrl = rtrim($systemUrl, '/');
        $this->tenantSlug = $tenantSlug;
        $this->timeout = $options['timeout'] ?? 30;
        $this->maxRetries = $options['max_retries'] ?? 3;
    }

    /**
     * Redirect user to support system
     */
    public function redirect($email, $name, $extraData = [])
    {
        // Validate input
        if (!$this->validateEmail($email)) {
            throw new InvalidArgumentException('Invalid email format');
        }

        if (empty(trim($name))) {
            throw new InvalidArgumentException('Name is required');
        }

        $userData = array_merge([
            'email' => trim($email),
            'name' => trim($name)
        ], $extraData);

        $attempts = 0;
        $lastError = null;

        while ($attempts < $this->maxRetries) {
            try {
                $response = $this->makeRequest($userData);

                if ($response['redirect']) {
                    header('Location: ' . $response['url']);
                    exit;
                }

                if ($response['status'] === 429) {
                    // Rate limited, wait and retry
                    $delay = pow(2, $attempts) * 1000000; // microseconds
                    usleep($delay);
                    $attempts++;
                    continue;
                }

                throw new RuntimeException("HTTP {$response['status']}: {$response['error']}");
            } catch (Exception $e) {
                $lastError = $e;
                $attempts++;

                if ($attempts >= $this->maxRetries) {
                    break;
                }

                // Exponential backoff
                $delay = pow(2, $attempts - 1) * 1000000;
                usleep($delay);
            }
        }

        throw $lastError ?? new RuntimeException('Failed to redirect to support system');
    }

    /**
     * Make HTTP request to support system
     */
    private function makeRequest($userData)
    {
        $url = $this->systemUrl . '/api/auth/redirect/' . $this->tenantSlug;

        $ch = curl_init();

        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => json_encode($userData),
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json',
                'User-Agent: PHP-Support-Integration/1.0'
            ],
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => false, // Don't follow redirects
            CURLOPT_TIMEOUT => $this->timeout,
            CURLOPT_SSL_VERIFYPEER => true,
            CURLOPT_SSL_VERIFYHOST => 2
        ]);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);

        curl_close($ch);

        if ($httpCode >= 300 && $httpCode < 400) {
            // Redirect response
            $redirectUrl = curl_getinfo($ch, CURLINFO_REDIRECT_URL);
            return [
                'redirect' => true,
                'url' => $redirectUrl,
                'status' => $httpCode
            ];
        }

        return [
            'redirect' => false,
            'status' => $httpCode,
            'response' => $response,
            'error' => $error
        ];
    }

    /**
     * Validate email format
     */
    private function validateEmail($email)
    {
        return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
    }

    /**
     * Get redirect URL without redirecting (for AJAX calls)
     */
    public function getRedirectUrl($email, $name, $extraData = [])
    {
        $userData = array_merge([
            'email' => trim($email),
            'name' => trim($name)
        ], $extraData);

        $response = $this->makeRequest($userData);

        if ($response['redirect']) {
            return $response['url'];
        }

        throw new RuntimeException("Failed to get redirect URL: HTTP {$response['status']}");
    }
}

// WordPress Integration Example
if (defined('ABSPATH')) {
    // WordPress-specific integration

    class WPSupportRedirect extends SupportRedirect
    {
        public function __construct($tenantSlug, $options = [])
        {
            $systemUrl = get_option('support_system_url', 'https://tickets.yourcompany.com');
            parent::__construct($systemUrl, $tenantSlug, $options);
        }

        /**
         * WordPress shortcode for support button
         */
        public static function support_button_shortcode($atts)
        {
            if (!is_user_logged_in()) {
                return '<p>Please <a href="' . wp_login_url() . '">log in</a> to contact support.</p>';
            }

            $atts = shortcode_atts([
                'text' => 'Contact Support',
                'class' => 'support-button',
                'tenant' => get_option('support_tenant_slug', 'default')
            ], $atts);

            $current_user = wp_get_current_user();

            try {
                $redirect = new self($atts['tenant']);
                $redirectUrl = $redirect->getRedirectUrl(
                    $current_user->user_email,
                    $current_user->display_name,
                    [
                        'wordpress_user_id' => $current_user->ID,
                        'site_url' => get_site_url()
                    ]
                );

                return sprintf(
                    '<a href="%s" class="%s" target="_blank">%s</a>',
                    esc_url($redirectUrl),
                    esc_attr($atts['class']),
                    esc_html($atts['text'])
                );

            } catch (Exception $e) {
                error_log('Support redirect error: ' . $e->getMessage());
                return '<p>Support system temporarily unavailable. Please try again later.</p>';
            }
        }

        /**
         * Handle support form submission
         */
        public static function handle_support_form()
        {
            if (!isset($_POST['contact_support'])) {
                return;
            }

            if (!wp_verify_nonce($_POST['support_nonce'], 'contact_support')) {
                wp_die('Security check failed');
            }

            if (!is_user_logged_in()) {
                wp_die('You must be logged in to contact support');
            }

            $current_user = wp_get_current_user();
            $tenant = get_option('support_tenant_slug', 'default');

            try {
                $redirect = new self($tenant);
                $redirect->redirect(
                    $current_user->user_email,
                    $current_user->display_name,
                    [
                        'wordpress_user_id' => $current_user->ID,
                        'form_message' => sanitize_textarea_field($_POST['message'] ?? ''),
                        'priority' => sanitize_text_field($_POST['priority'] ?? 'normal')
                    ]
                );
            } catch (Exception $e) {
                wp_die('Unable to contact support. Please try again later. Error: ' . $e->getMessage());
            }
        }
    }

    // Register WordPress hooks
    add_shortcode('support_button', ['WPSupportRedirect', 'support_button_shortcode']);
    add_action('admin_post_contact_support', ['WPSupportRedirect', 'handle_support_form']);
    add_action('admin_post_nopriv_contact_support', ['WPSupportRedirect', 'handle_support_form']);

    // Add settings page
    add_action('admin_menu', function() {
        add_options_page(
            'Support System Settings',
            'Support Settings',
            'manage_options',
            'support-settings',
            function() {
                ?>
                <div class="wrap">
                    <h1>Support System Settings</h1>
                    <form method="post" action="options.php">
                        <?php settings_fields('support_settings_group'); ?>
                        <table class="form-table">
                            <tr>
                                <th><label for="support_system_url">Support System URL</label></th>
                                <td>
                                    <input type="url" id="support_system_url" name="support_system_url"
                                           value="<?php echo esc_attr(get_option('support_system_url', 'https://tickets.yourcompany.com')); ?>"
                                           class="regular-text">
                                    <p class="description">The base URL of your ticket system</p>
                                </td>
                            </tr>
                            <tr>
                                <th><label for="support_tenant_slug">Tenant Slug</label></th>
                                <td>
                                    <input type="text" id="support_tenant_slug" name="support_tenant_slug"
                                           value="<?php echo esc_attr(get_option('support_tenant_slug', 'default')); ?>"
                                           class="regular-text">
                                    <p class="description">Your unique tenant identifier</p>
                                </td>
                            </tr>
                        </table>
                        <?php submit_button(); ?>
                    </form>

                    <h2>Usage</h2>
                    <p>Use the shortcode <code>[support_button]</code> in posts or pages to add a support button.</p>
                    <p>Or use the shortcode with parameters: <code>[support_button text="Get Help" class="my-button" tenant="my-tenant"]</code></p>
                </div>
                <?php
            }
        );
    });

    add_action('admin_init', function() {
        register_setting('support_settings_group', 'support_system_url');
        register_setting('support_settings_group', 'support_tenant_slug');
    });
}

// Laravel Integration Example
if (class_exists('Illuminate\Support\Facades\Route')) {
    // Laravel-specific integration

    class LaravelSupportRedirect extends SupportRedirect
    {
        public function __construct($tenantSlug = null, $options = [])
        {
            $systemUrl = config('services.support_system.url', env('SUPPORT_SYSTEM_URL', 'https://tickets.yourcompany.com'));
            $tenantSlug = $tenantSlug ?? config('services.support_system.tenant', env('SUPPORT_TENANT_SLUG', 'default'));

            parent::__construct($systemUrl, $tenantSlug, $options);
        }

        /**
         * Laravel route handler
         */
        public static function handleRedirect(Request $request)
        {
            $user = auth()->user();

            if (!$user) {
                return redirect()->route('login');
            }

            try {
                $redirect = new self();
                $redirect->redirect(
                    $user->email,
                    $user->name,
                    [
                        'laravel_user_id' => $user->id,
                        'company' => $user->company ?? null,
                        'role' => $user->role ?? null
                    ]
                );
            } catch (Exception $e) {
                Log::error('Support redirect failed', [
                    'user_id' => $user->id,
                    'error' => $e->getMessage()
                ]);

                return back()->withErrors(['support' => 'Unable to contact support. Please try again later.']);
            }
        }

        /**
         * Get redirect URL for AJAX calls
         */
        public static function getRedirectUrlForUser($user = null)
        {
            $user = $user ?? auth()->user();

            if (!$user) {
                throw new RuntimeException('User not authenticated');
            }

            $redirect = new self();
            return $redirect->getRedirectUrl(
                $user->email,
                $user->name,
                [
                    'user_id' => $user->id,
                    'company' => $user->company ?? null
                ]
            );
        }
    }

    // Register routes (add to routes/web.php)
    /*
    Route::get('/support', function() {
        return view('support.contact');
    })->name('support.contact');

    Route::post('/support/redirect', function(Request $request) {
        return LaravelSupportRedirect::handleRedirect($request);
    })->name('support.redirect');
    */
}

// Usage Examples:

// Basic usage
try {
    $support = new SupportRedirect('https://tickets.yourcompany.com', 'acme-corp');
    $support->redirect('user@example.com', 'John Doe');
} catch (Exception $e) {
    echo 'Error: ' . $e->getMessage();
}

// With extra data
try {
    $support = new SupportRedirect('https://tickets.yourcompany.com', 'acme-corp');
    $support->redirect('user@example.com', 'John Doe', [
        'company' => 'Acme Corporation',
        'role' => 'Developer',
        'priority' => 'high'
    ]);
} catch (Exception $e) {
    echo 'Error: ' . $e->getMessage();
}

// Get URL without redirecting (for AJAX)
try {
    $support = new SupportRedirect('https://tickets.yourcompany.com', 'acme-corp');
    $redirectUrl = $support->getRedirectUrl('user@example.com', 'John Doe');
    echo '<a href="' . htmlspecialchars($redirectUrl) . '">Contact Support</a>';
} catch (Exception $e) {
    echo 'Error: ' . $e->getMessage();
}
?>