<?php

class EveAI_Admin {
    private $api;

    public function __construct($api) {
        $this->api = $api;
    }

    public function register_settings() {
        register_setting('eveai_settings', 'eveai_api_url');
        register_setting('eveai_settings', 'eveai_tenant_id');
        register_setting('eveai_settings', 'eveai_api_key');
        register_setting('eveai_settings', 'eveai_default_language');
        register_setting('eveai_settings', 'eveai_excluded_categories');
        register_setting('eveai_settings', 'eveai_excluded_categories');
        register_setting('eveai_settings', 'eveai_access_token');
        register_setting('eveai_settings', 'eveai_token_expiry');
        register_setting('eveai_settings', 'eveai_catalog_id');
    }

    public function add_admin_menu() {
        add_options_page(
            'EveAI Sync Settings',
            'EveAI Sync',
            'manage_options',
            'eveai-sync',
            array($this, 'render_settings_page')
        );
    }

    public function render_settings_page() {
        ?>
        <div class="wrap">
            <h1><?php echo esc_html(get_admin_page_title()); ?></h1>
            <form action="options.php" method="post">
                <?php
                settings_fields('eveai_settings');
                do_settings_sections('eveai-sync');
                ?>
                <table class="form-table">
                    <tr valign="top">
                        <th scope="row">API URL</th>
                        <td><input type="text" name="eveai_api_url" value="<?php echo esc_attr(get_option('eveai_api_url')); ?>" style="width: 100%;" /></td>
                    </tr>
                    <tr valign="top">
                        <th scope="row">Tenant ID</th>
                        <td><input type="text" name="eveai_tenant_id" value="<?php echo esc_attr(get_option('eveai_tenant_id')); ?>" style="width: 100%;" /></td>
                    </tr>
                    <tr valign="top">
                        <th scope="row">API Key</th>
                        <td><input type="text" name="eveai_api_key" value="<?php echo esc_attr(get_option('eveai_api_key')); ?>" style="width: 100%;" /></td>
                    </tr>
                    <tr valign="top">
                        <th scope="row">Catalog ID</th>
                        <td><input type="text" name="eveai_catalog_id" value="<?php echo esc_attr(get_option('eveai_catalog_id')); ?>" style="width: 100%;" /></td>
                    </tr>
                    <tr valign="top">
                        <th scope="row">Default Language</th>
                        <td><input type="text" name="eveai_default_language" value="<?php echo esc_attr(get_option('eveai_default_language', 'en')); ?>" style="width: 100%;" /></td>
                    </tr>
                    <tr valign="top">
                        <th scope="row">Excluded Categories</th>
                        <td>
                            <input type="text" name="eveai_excluded_categories" value="<?php echo esc_attr(get_option('eveai_excluded_categories')); ?>" style="width: 100%;" />
                            <p class="description">Enter a comma-separated list of category names to exclude from syncing.</p>
                        </td>
                    </tr>
                </table>
                <?php submit_button('Save Settings'); ?>
            </form>

            <h2>Bulk Sync</h2>
            <p>Click the button below to start a bulk sync of all posts and pages to EveAI.</p>
            <form method="post" action="">
                <?php wp_nonce_field('eveai_bulk_sync', 'eveai_bulk_sync_nonce'); ?>
                <input type="submit" name="eveai_bulk_sync" class="button button-primary" value="Start Bulk Sync">
            </form>

            <h2>Reinitialize Site</h2>
            <p>Click the button below to remove all EveAI metadata from your site. This will reset the sync status for all posts and pages.</p>
            <button id="eveai-reinitialize" class="button button-secondary">Reinitialize Site</button>

            <div id="eveai-sync-results" style="margin-top: 20px;"></div>
        </div>
        <script>
        jQuery(document).ready(function($) {
            $('form').on('submit', function(e) {
                if ($(this).find('input[name="eveai_bulk_sync"]').length) {
                    e.preventDefault();
                    var $results = $('#eveai-sync-results');
                    $results.html('<p>Starting bulk sync...</p>');
                    $.ajax({
                        url: ajaxurl,
                        type: 'POST',
                        data: {
                            action: 'eveai_bulk_sync',
                            nonce: '<?php echo wp_create_nonce('eveai_bulk_sync_ajax'); ?>'
                        },
                        success: function(response) {
                            if (response.success) {
                                var resultsHtml = '<h3>Sync Results:</h3><ul>';
                                response.data.forEach(function(item) {
                                    resultsHtml += '<li>' + item.title + ' (' + item.type + '): ' + item.status + '</li>';
                                });
                                resultsHtml += '</ul>';
                                $results.html(resultsHtml);
                            } else {
                                $results.html('<p>Error: ' + response.data + '</p>');
                            }
                        },
                        error: function() {
                            $results.html('<p>An error occurred. Please try again.</p>');
                        }
                    });
                }
            });
            $('#eveai-reinitialize').on('click', function(e) {
                e.preventDefault();
                if (confirm('Are you sure you want to reinitialize? This will remove all EveAI metadata from your site.')) {
                    $.ajax({
                        url: ajaxurl,
                        type: 'POST',
                        data: {
                            action: 'eveai_reinitialize_site',
                            nonce: '<?php echo wp_create_nonce('eveai_reinitialize_site'); ?>'
                        },
                        success: function(response) {
                            if (response.success) {
                                alert(response.data);
                            } else {
                                alert('Error: ' + response.data);
                            }
                        },
                        error: function() {
                            alert('An error occurred. Please try again.');
                        }
                    });
                }
            });
        });
        </script>
        <?php
    }

    public function handle_bulk_sync_ajax() {
        check_ajax_referer('eveai_bulk_sync_ajax', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
            return;
        }

        $post_handler = new EveAI_Post_Handler($this->api);
        $bulk_sync = new EveAI_Bulk_Sync($this->api, $post_handler);
        $results = $bulk_sync->init_bulk_sync();

        wp_send_json_success($results);
    }

    public function add_sync_meta_box() {
        add_meta_box(
            'eveai_sync_meta_box',
            'EveAI Sync',
            array($this, 'render_sync_meta_box'),
            array('post', 'page'),
            'side',
            'default'
        );
    }

    public function render_sync_meta_box($post) {
        $excluded = get_post_meta($post->ID, '_eveai_exclude_sync', true);
        wp_nonce_field('eveai_sync_meta_box', 'eveai_sync_meta_box_nonce');
        ?>
        <label>
            <input type="checkbox" name="eveai_exclude_sync" value="1" <?php checked($excluded, '1'); ?>>
            Exclude from EveAI sync
        </label>
        <?php
    }

    public function handle_bulk_sync() {
        $post_handler = new EveAI_Post_Handler($this->api);
        $bulk_sync = new EveAI_Bulk_Sync($this->api, $post_handler);
        $bulk_sync->init_bulk_sync();
        add_settings_error('eveai_messages', 'eveai_message', 'Bulk sync initiated successfully.', 'updated');
    }
}