<?php
/**
 * Admin Functions
 */

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

add_action('add_meta_boxes', 'askagento_add_meta_boxes');
add_action('save_post_' . ASKAGENTO_POST_TYPE, 'askagento_save_meta_boxes', 10, 2);
add_action('admin_enqueue_scripts', 'askagento_admin_scripts');
add_action('wp_ajax_askagento_get_data_sources', 'askagento_ajax_get_data_sources');

/**
 * Enqueue admin scripts
 */
function askagento_admin_scripts($hook) {
    global $post_type;
    
    if ($post_type !== ASKAGENTO_POST_TYPE) {
        return;
    }
    
    if (!in_array($hook, ['post.php', 'post-new.php'])) {
        return;
    }

    if ($hook === 'post-new.php' && function_exists('askagento_auto_filter_creation_mode') && askagento_auto_filter_creation_mode() !== 'manual') {
        return;
    }
    
    wp_enqueue_style('askagento-admin', ASKAGENTO_PLUGIN_URL . 'assets/css/admin.css', [], ASKAGENTO_VERSION);
    wp_enqueue_script('askagento-admin', ASKAGENTO_PLUGIN_URL . 'assets/js/admin.js', ['jquery', 'jquery-ui-sortable'], ASKAGENTO_VERSION, true);
    
    wp_localize_script('askagento-admin', 'askagentoAdmin', [
        'ajaxUrl' => admin_url('admin-ajax.php'),
        'nonce'   => wp_create_nonce('askagento_admin'),
        'i18n'    => [
            'addField'      => __('Add Field', 'askagento'),
            'confirmRemove' => __('Remove this field?', 'askagento'),
            'loading'       => __('Loading...', 'askagento'),
            'noData'        => __('No data available', 'askagento'),
        ],
    ]);
}

/**
 * Register meta boxes
 */
function askagento_add_meta_boxes() {
    $screen = function_exists('get_current_screen') ? get_current_screen() : null;
    $is_new = $screen && $screen->post_type === ASKAGENTO_POST_TYPE && $screen->base === 'post' && $screen->action === 'add';
    if ($is_new && function_exists('askagento_auto_filter_creation_mode') && askagento_auto_filter_creation_mode() === 'auto') {
        return;
    }

    add_meta_box('askagento_fields', __('Filter Fields', 'askagento'), 'askagento_render_fields_metabox', ASKAGENTO_POST_TYPE, 'normal', 'high');
    add_meta_box('askagento_settings', __('Settings', 'askagento'), 'askagento_render_settings_metabox', ASKAGENTO_POST_TYPE, 'side', 'default');
    add_meta_box('askagento_cache', __('Cache', 'askagento'), 'askagento_render_cache_metabox', ASKAGENTO_POST_TYPE, 'side', 'default');
    add_meta_box('askagento_shortcode', __('Shortcode', 'askagento'), 'askagento_render_shortcode_metabox', ASKAGENTO_POST_TYPE, 'side', 'default');
}

/**
 * Render fields metabox
 */
function askagento_render_fields_metabox($post) {
    wp_nonce_field('askagento_save', 'askagento_nonce');
    $fields = askagento_get_fields($post->ID);
    ?>
    <div class="askagento-fields-wrap">
        <div id="askagento-fields-list" class="askagento-fields-list">
            <?php if (empty($fields)): ?>
                <p class="askagento-no-fields"><?php esc_html_e('No fields. Click "Add Field" to start.', 'askagento'); ?></p>
            <?php else: ?>
                <?php foreach ($fields as $i => $field): ?>
                    <?php askagento_render_field_row($field, $i); ?>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
        
        <p class="askagento-actions">
            <button type="button" class="button button-primary" id="askagento-add-field">
                + <?php esc_html_e('Add Field', 'askagento'); ?>
            </button>
        </p>
    </div>
    
    <!-- Modal -->
    <div id="askagento-modal" class="askagento-modal" style="display:none;">
        <div class="askagento-modal-box">
            <div class="askagento-modal-head">
                <strong><?php esc_html_e('Add Field', 'askagento'); ?></strong>
                <button type="button" class="askagento-modal-close">&times;</button>
            </div>
            <div class="askagento-modal-search">
                <input type="text" id="askagento-search" placeholder="<?php esc_html_e('Search...', 'askagento'); ?>">
            </div>
            <div id="askagento-sources" class="askagento-sources"></div>
            <div class="askagento-modal-foot">
                <button type="button" class="button" id="askagento-cancel"><?php esc_html_e('Cancel', 'askagento'); ?></button>
                <button type="button" class="button button-primary" id="askagento-add-selected" disabled><?php esc_html_e('Add', 'askagento'); ?></button>
            </div>
        </div>
    </div>
    
    <!-- Template -->
    <script type="text/html" id="tmpl-askagento-field">
        <?php askagento_render_field_template(); ?>
    </script>
    <?php
}

/**
 * Render single field row
 */
function askagento_render_field_row($field, $index) {
    $types = ['checkbox' => 'Checkbox', 'radio' => 'Radio', 'dropdown' => 'Dropdown', 'range' => 'Range'];
    $type_label = $types[$field['type']] ?? $field['type'];
    ?>
    <div class="askagento-field" data-index="<?php echo absint($index); ?>">
        <span class="askagento-handle">☰</span>
        <span class="askagento-label"><?php echo esc_html($field['label']); ?></span>
        <code class="askagento-source"><?php echo esc_html($field['source']); ?></code>
        <span class="askagento-type"><?php echo esc_html($type_label); ?></span>
        <span class="askagento-buttons">
            <button type="button" class="button askagento-configure">⚙</button>
            <button type="button" class="button askagento-remove">✕</button>
        </span>

        <input type="hidden" name="askagento_fields[<?php echo absint($index); ?>][source]" value="<?php echo esc_attr($field['source']); ?>">
        <input type="hidden" name="askagento_fields[<?php echo absint($index); ?>][label]" value="<?php echo esc_attr($field['label']); ?>">
        <input type="hidden" name="askagento_fields[<?php echo absint($index); ?>][type]" value="<?php echo esc_attr($field['type']); ?>">
        <input type="hidden" name="askagento_fields[<?php echo absint($index); ?>][show_count]" value="<?php echo $field['show_count'] ? '1' : '0'; ?>">
        
        <div class="askagento-config" style="display:none;">
            <p>
                <label><?php esc_html_e('Label', 'askagento'); ?></label>
                <input type="text" class="askagento-cfg-label" value="<?php echo esc_attr($field['label']); ?>">
            </p>
            <p>
                <label><?php esc_html_e('Type', 'askagento'); ?></label>
                <select class="askagento-cfg-type">
                    <option value="checkbox" <?php selected($field['type'], 'checkbox'); ?>>Checkbox</option>
                    <option value="radio" <?php selected($field['type'], 'radio'); ?>>Radio</option>
                    <option value="dropdown" <?php selected($field['type'], 'dropdown'); ?>>Dropdown</option>
                    <option value="range" <?php selected($field['type'], 'range'); ?>>Range</option>
                </select>
            </p>
            <p>
                <label><input type="checkbox" class="askagento-cfg-count" <?php checked($field['show_count']); ?>> <?php esc_html_e('Show count', 'askagento'); ?></label>
            </p>
        </div>
    </div>
    <?php
}

/**
 * Field template for JS
 */
function askagento_render_field_template() {
    ?>
    <div class="askagento-field" data-index="{{index}}">
        <span class="askagento-handle">☰</span>
        <span class="askagento-label">{{label}}</span>
        <code class="askagento-source">{{source}}</code>
        <span class="askagento-type">{{type_label}}</span>
        <span class="askagento-buttons">
            <button type="button" class="button askagento-configure">⚙</button>
            <button type="button" class="button askagento-remove">✕</button>
        </span>
        
        <input type="hidden" name="askagento_fields[{{index}}][source]" value="{{source}}">
        <input type="hidden" name="askagento_fields[{{index}}][label]" value="{{label}}">
        <input type="hidden" name="askagento_fields[{{index}}][type]" value="{{type}}">
        <input type="hidden" name="askagento_fields[{{index}}][show_count]" value="1">
        
        <div class="askagento-config" style="display:none;">
            <p>
                <label><?php esc_html_e('Label', 'askagento'); ?></label>
                <input type="text" class="askagento-cfg-label" value="{{label}}">
            </p>
            <p>
                <label><?php esc_html_e('Type', 'askagento'); ?></label>
                <select class="askagento-cfg-type">
                    <option value="checkbox">Checkbox</option>
                    <option value="radio">Radio</option>
                    <option value="dropdown">Dropdown</option>
                    <option value="range">Range</option>
                </select>
            </p>
            <p>
                <label><input type="checkbox" class="askagento-cfg-count" checked> <?php esc_html_e('Show count', 'askagento'); ?></label>
            </p>
        </div>
    </div>
    <?php
}

/**
 * Render settings metabox
 */
function askagento_render_settings_metabox($post) {
    $settings = askagento_get_settings($post->ID);
    $post_types = get_post_types(['public' => true], 'objects');
    ?>
    <p>
        <label><strong><?php esc_html_e('Post Types', 'askagento'); ?></strong></label><br>
        <select name="askagento_settings[post_types][]" id="askagento_post_types" multiple style="width:100%;height:80px;">
            <?php foreach ($post_types as $pt): ?>
                <option value="<?php echo esc_attr($pt->name); ?>" <?php selected(in_array($pt->name, $settings['post_types'])); ?>>
                    <?php echo esc_html($pt->label); ?>
                </option>
            <?php endforeach; ?>
        </select>
    </p>
    
    <p>
        <label><strong><?php esc_html_e('Results Container', 'askagento'); ?></strong></label><br>
        <input type="text" name="askagento_settings[results_selector]" value="<?php echo esc_attr($settings['results_selector']); ?>" style="width:100%;">
        <small><?php esc_html_e('CSS selector', 'askagento'); ?></small>
    </p>
    
    <p>
        <label><input type="checkbox" name="askagento_settings[ajax_enabled]" value="1" <?php checked($settings['ajax_enabled']); ?>>
        <?php esc_html_e('AJAX filtering', 'askagento'); ?></label>
    </p>
    
    <p>
        <label><input type="checkbox" name="askagento_settings[show_count]" value="1" <?php checked($settings['show_count']); ?>>
        <?php esc_html_e('Show counts', 'askagento'); ?></label>
    </p>
    
    <p>
        <label><input type="checkbox" name="askagento_settings[hide_empty]" value="1" <?php checked($settings['hide_empty']); ?>>
        <?php esc_html_e('Hide empty', 'askagento'); ?></label>
    </p>
    <?php
}

/**
 * Render shortcode metabox
 */
function askagento_render_shortcode_metabox($post) {
    if ($post->post_status !== 'publish') {
        echo '<p>' . esc_html__('Publish to get shortcode.', 'askagento') . '</p>';
        return;
    }
    ?>
    <p style="margin:0 0 4px;"><strong><?php esc_html_e('Filter only', 'askagento'); ?></strong></p>
    <code id="askagento-shortcode">[product_filter id="<?php echo absint($post->ID); ?>"]</code>
    <p><button type="button" class="button" onclick="navigator.clipboard.writeText(document.getElementById('askagento-shortcode').textContent)"><?php esc_html_e('Copy', 'askagento'); ?></button></p>

    <p style="margin:8px 0 4px;"><strong><?php esc_html_e('Filter + AI text search', 'askagento'); ?></strong></p>
    <code id="askagento-shortcode-search">[product_filter_search id="<?php echo absint($post->ID); ?>"]</code>
    <p><button type="button" class="button" onclick="navigator.clipboard.writeText(document.getElementById('askagento-shortcode-search').textContent)"><?php esc_html_e('Copy', 'askagento'); ?></button></p>
    <?php
}

/**
 * Render cache metabox
 */
function askagento_render_cache_metabox($post) {
    $built = get_post_meta($post->ID, '_askagento_cache_built', true);
    $products = get_post_meta($post->ID, '_askagento_cache_products', true);
    ?>
    <div id="askagento-cache-status">
        <?php if ($built): ?>
            <p><strong><?php esc_html_e('Last built:', 'askagento'); ?></strong> <?php echo esc_html($built); ?></p>
            <p><strong><?php esc_html_e('Products:', 'askagento'); ?></strong> <?php echo esc_html($products); ?></p>
        <?php else: ?>
            <p><?php esc_html_e('Cache not built yet.', 'askagento'); ?></p>
        <?php endif; ?>
        
        <?php if (in_array($post->post_status, ['publish', 'private'], true)): ?>
        <p class="description" style="margin-top:8px;">
            <?php esc_html_e('The product index rebuilds automatically when you save this filter, when it is published, or when the shop page loads if the index is still empty. Use the button below for an immediate rebuild.', 'askagento'); ?>
        </p>
        <?php endif; ?>
        
    </div>
    
    <?php if ($post->post_status === 'publish'): ?>
        <p>
            <button type="button" class="button button-primary" id="askagento-build-cache">
                <?php esc_html_e('Build Cache', 'askagento'); ?>
            </button>
            <span id="askagento-cache-spinner" class="spinner" style="float:none;"></span>
        </p>
        
        <div id="askagento-cache-result"></div>
        
        <script>
        jQuery(function($) {
            var $spinner = $('#askagento-cache-spinner');
            var $result = $('#askagento-cache-result');
            var filterId = <?php echo absint($post->ID); ?>;
            
            // Build Cache (local)
            $('#askagento-build-cache').on('click', function() {
                var $btn = $(this);
                $btn.prop('disabled', true);
                $spinner.addClass('is-active');
                $result.html('');
                
                $.post(askagentoAdmin.ajaxUrl, {
                    action: 'askagento_build_cache',
                    nonce: askagentoAdmin.nonce,
                    filter_id: filterId
                }, function(r) {
                    $btn.prop('disabled', false);
                    $spinner.removeClass('is-active');
                    
                    if (r.success) {
                        $result.html('<p style="color:green;">✓ ' + r.data.products + ' products, ' + r.data.cache + ' cache rows, ' + r.data.terms + ' term rows (' + r.data.time + 's)</p>');
                        setTimeout(function() { location.reload(); }, 1500);
                    } else {
                        $result.html('<p style="color:red;">✗ ' + (r.data.message || 'Error') + '</p>');
                    }
                });
            });
        });
        </script>
    <?php else: ?>
        <p><?php esc_html_e('Publish filter first.', 'askagento'); ?></p>
    <?php endif; ?>
    <?php
}

/**
 * Save meta boxes
 */
function askagento_save_meta_boxes($post_id, $post) {
    if (
        !isset($_POST['askagento_nonce'])
        || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['askagento_nonce'])), 'askagento_save')
    ) {
        return;
    }
    
    if (!current_user_can('edit_post', $post_id)) {
        return;
    }
    
    // Fields
    $fields = [];
    $posted_fields = isset($_POST['askagento_fields']) ? (array) map_deep( wp_unslash( $_POST['askagento_fields'] ), 'sanitize_text_field' ) : [];
    foreach ($posted_fields as $field) {
        $field   = is_array($field) ? $field : [];
        $fields[] = [
            'source'     => sanitize_text_field($field['source'] ?? ''),
            'label'      => sanitize_text_field($field['label'] ?? ''),
            'type'       => sanitize_text_field($field['type'] ?? 'checkbox'),
            'show_count' => !empty($field['show_count']),
        ];
    }
    askagento_save_fields($post_id, $fields);

    // Settings
    $s = isset($_POST['askagento_settings']) ? (array) map_deep( wp_unslash( $_POST['askagento_settings'] ), 'sanitize_text_field' ) : [];
    $settings = [
        'post_types'       => !empty($s['post_types']) ? array_map('sanitize_text_field', $s['post_types']) : ['product'],
        'results_selector' => sanitize_text_field($s['results_selector'] ?? '.products'),
        'ajax_enabled'     => !empty($s['ajax_enabled']),
        'show_count'       => !empty($s['show_count']),
        'hide_empty'       => !empty($s['hide_empty']),
    ];
    askagento_save_settings($post_id, $settings);
}

/**
 * AJAX: Get data sources
 */
function askagento_ajax_get_data_sources() {
    check_ajax_referer('askagento_admin', 'nonce');

    if (!current_user_can('edit_posts')) {
        wp_send_json_error(['message' => __('Permission denied', 'askagento')], 403);
    }

    $post_types = !empty($_POST['post_types']) ? array_map('sanitize_text_field', (array) wp_unslash($_POST['post_types'])) : ['product'];
    $sources = askagento_get_data_sources($post_types);
    
    wp_send_json_success($sources);
}
