<?php
/**
 * Plugin Name: Central Tickets Support Integration
 * Plugin URI: https://your-ticket-system.com
 * Description: Seamlessly integrate Central Tickets support system into your WordPress site
 * Version: 1.0.0
 * Author: Central Tickets Team
 * License: GPL v2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: central-tickets
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

class CentralTicketsIntegration {

    private $system_url;
    private $tenant_slug;
    private $settings;

    public function __construct() {
        $this->settings = get_option('central_tickets_settings', array());
        $this->system_url = isset($this->settings['system_url']) ? $this->settings['system_url'] : '';
        $this->tenant_slug = isset($this->settings['tenant_slug']) ? $this->settings['tenant_slug'] : '';

        add_action('admin_menu', array($this, 'add_admin_menu'));
        add_action('admin_init', array($this, 'register_settings'));
        add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts'));
        add_shortcode('central_tickets_button', array($this, 'support_button_shortcode'));
        add_action('wp_ajax_central_tickets_redirect', array($this, 'handle_ajax_redirect'));
        add_action('wp_ajax_nopriv_central_tickets_redirect', array($this, 'handle_ajax_redirect'));
    }

    /**
     * Add admin menu
     */
    public function add_admin_menu() {
        add_options_page(
            'Central Tickets Settings',
            'Central Tickets',
            'manage_options',
            'central-tickets',
            array($this, 'settings_page')
        );
    }

    /**
     * Register settings
     */
    public function register_settings() {
        register_setting('central_tickets_settings', 'central_tickets_settings');

        add_settings_section(
            'central_tickets_main',
            'Main Settings',
            null,
            'central-tickets'
        );

        add_settings_field(
            'system_url',
            'Ticket System URL',
            array($this, 'system_url_callback'),
            'central-tickets',
            'central_tickets_main'
        );

        add_settings_field(
            'tenant_slug',
            'Tenant Slug',
            array($this, 'tenant_slug_callback'),
            'central-tickets',
            'central_tickets_main'
        );
    }

    /**
     * System URL field callback
     */
    public function system_url_callback() {
        $value = isset($this->settings['system_url']) ? $this->settings['system_url'] : '';
        echo '<input type="url" name="central_tickets_settings[system_url]" value="' . esc_attr($value) . '" class="regular-text" placeholder="https://tickets.yourdomain.com" required>';
        echo '<p class="description">The URL of your Central Tickets system</p>';
    }

    /**
     * Tenant slug field callback
     */
    public function tenant_slug_callback() {
        $value = isset($this->settings['tenant_slug']) ? $this->settings['tenant_slug'] : '';
        echo '<input type="text" name="central_tickets_settings[tenant_slug]" value="' . esc_attr($value) . '" class="regular-text" placeholder="your-company" required>';
        echo '<p class="description">Your tenant identifier (provided by Central Tickets)</p>';
    }

    /**
     * Settings page
     */
    public function settings_page() {
        ?>
        <div class="wrap">
            <h1>Central Tickets Integration Settings</h1>
            <form method="post" action="options.php">
                <?php
                settings_fields('central_tickets_settings');
                do_settings_sections('central-tickets');
                submit_button();
                ?>
            </form>

            <hr>

            <h2>Usage Instructions</h2>
            <h3>Shortcode</h3>
            <p>Add this shortcode to any page or post:</p>
            <code>[central_tickets_button text="Contact Support" class="my-custom-class"]</code>

            <h3>PHP Function</h3>
            <p>Use this function in your theme files:</p>
            <code>&lt;?php echo do_shortcode('[central_tickets_button]'); ?&gt;</code>

            <h3>Manual Button</h3>
            <p>Add this HTML anywhere:</p>
            <code>&lt;button onclick="centralTicketsRedirect()"&gt;Contact Support&lt;/button&gt;</code>
        </div>
        <?php
    }

    /**
     * Enqueue scripts and styles
     */
    public function enqueue_scripts() {
        wp_enqueue_script(
            'central-tickets-js',
            plugin_dir_url(__FILE__) . 'js/central-tickets.js',
            array('jquery'),
            '1.0.0',
            true
        );

        wp_localize_script('central-tickets-js', 'centralTicketsAjax', array(
            'ajaxurl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('central_tickets_nonce')
        ));

        wp_enqueue_style(
            'central-tickets-css',
            plugin_dir_url(__FILE__) . 'css/central-tickets.css',
            array(),
            '1.0.0'
        );
    }

    /**
     * Support button shortcode
     */
    public function support_button_shortcode($atts) {
        $atts = shortcode_atts(array(
            'text' => 'Contact Support',
            'class' => 'central-tickets-button',
            'style' => ''
        ), $atts);

        if (empty($this->system_url) || empty($this->tenant_slug)) {
            return '<p style="color: red;">Central Tickets: Please configure the plugin settings first.</p>';
        }

        $button_id = 'ct-btn-' . uniqid();

        return sprintf(
            '<button id="%s" class="%s" style="%s" onclick="centralTicketsRedirect()">%s</button>',
            esc_attr($button_id),
            esc_attr($atts['class']),
            esc_attr($atts['style']),
            esc_html($atts['text'])
        );
    }

    /**
     * Handle AJAX redirect
     */
    public function handle_ajax_redirect() {
        check_ajax_referer('central_tickets_nonce', 'nonce');

        if (empty($this->system_url) || empty($this->tenant_slug)) {
            wp_die('Configuration error');
        }

        $current_user = wp_get_current_user();

        if (!$current_user->ID) {
            wp_die('User not logged in');
        }

        $user_data = array(
            'email' => $current_user->user_email,
            'name' => $current_user->display_name,
            'wordpress_id' => $current_user->ID,
            'site_url' => get_site_url(),
            'user_role' => implode(', ', $current_user->roles)
        );

        $response = wp_remote_post($this->system_url . '/auth/redirect/' . $this->tenant_slug, array(
            'method' => 'POST',
            'timeout' => 30,
            'headers' => array(
                'Content-Type' => 'application/json',
                'User-Agent' => 'WordPress-CentralTickets/1.0.0'
            ),
            'body' => wp_json_encode($user_data),
            'sslverify' => true
        ));

        if (is_wp_error($response)) {
            wp_die('Connection error: ' . $response->get_error_message());
        }

        $response_code = wp_remote_retrieve_response_code($response);

        if ($response_code === 302) {
            $redirect_url = wp_remote_retrieve_header($response, 'location');
            wp_send_json_success(array('redirect_url' => $redirect_url));
        } elseif ($response_code === 429) {
            wp_send_json_error('Too many requests. Please try again later.', 429);
        } else {
            $body = wp_remote_retrieve_body($response);
            wp_send_json_error('Redirect failed: ' . $body, $response_code);
        }
    }
}

// Initialize the plugin
new CentralTicketsIntegration();

// Activation hook
register_activation_hook(__FILE__, 'central_tickets_activate');
function central_tickets_activate() {
    // Create default settings if they don't exist
    if (!get_option('central_tickets_settings')) {
        add_option('central_tickets_settings', array(
            'system_url' => '',
            'tenant_slug' => ''
        ));
    }
}

// Deactivation hook
register_deactivation_hook(__FILE__, 'central_tickets_deactivate');
function central_tickets_deactivate() {
    // Clean up if needed
}