<?php
/**
 * Content Control - Granular Control Per Content Type
 * 
 * Handles per-post-type and per-post AI refusal settings.
 * Allows site owners to selectively apply refusal signals.
 */

namespace HumanGate;

class ContentControl {
    
    /**
     * Initialize content control
     */
    public function init() {
        // Add meta boxes to post edit screens
        add_action('add_meta_boxes', [$this, 'add_meta_boxes']);
        
        // Save meta box data
        add_action('save_post', [$this, 'save_meta_box'], 10, 2);
        
        // Note: Post type settings are registered in Admin::register_settings()
        // to ensure proper timing and integration with the settings API
    }
    
    /**
     * Add meta box to post edit screens
     */
    public function add_meta_boxes() {
        // Get all public post types (show meta box on all, not just enabled ones)
        // This allows users to enable/disable on a per-post basis even if the post type is disabled
        $post_types = get_post_types(['public' => true], 'names');
        
        if (empty($post_types)) {
            return;
        }
        
        // Add meta box to each public post type
        foreach ($post_types as $post_type) {
            add_meta_box(
                'humangate_refusal_control',
                __('HumanGate AI Refusal', 'humangate'),
                [$this, 'render_meta_box'],
                $post_type,
                'side',
                'high'
            );
        }
    }
    
    /**
     * Render meta box content
     */
    public function render_meta_box($post) {
        // Security nonce
        wp_nonce_field('humangate_save_meta_box', 'humangate_meta_box_nonce');
        
        // Get current value (default: inherit from post type setting)
        $current_value = get_post_meta($post->ID, '_humangate_refusal_enabled', true);
        
        // If not set, inherit from post type setting
        if ($current_value === '') {
            $post_type_setting = 'humang_refusal_post_types_' . $post->post_type;
            $inherit_value = get_option($post_type_setting, true);
            $current_value = $inherit_value ? 'inherit' : 'disabled';
        }
        
        ?>
        <div style="padding: 10px 0;">
            <p>
                <label>
                    <input type="radio" 
                           name="humangate_refusal_enabled" 
                           value="enabled" 
                           <?php checked($current_value, 'enabled'); ?>>
                    <?php esc_html_e('Enable AI Refusal', 'humangate'); ?>
                </label>
            </p>
            <p>
                <label>
                    <input type="radio" 
                           name="humangate_refusal_enabled" 
                           value="disabled" 
                           <?php checked($current_value, 'disabled'); ?>>
                    <?php esc_html_e('Disable AI Refusal', 'humangate'); ?>
                </label>
            </p>
            <p>
                <label>
                    <input type="radio" 
                           name="humangate_refusal_enabled" 
                           value="inherit" 
                           <?php checked($current_value, 'inherit'); ?>>
                    <?php esc_html_e('Use Post Type Default', 'humangate'); ?>
                </label>
            </p>
            <p class="description" style="margin-top: 10px; font-size: 12px; color: #999;">
                <?php esc_html_e('Controls whether AI refusal signals (meta tags, headers) are applied to this content.', 'humangate'); ?>
            </p>
        </div>
        <?php
    }
    
    /**
     * Save meta box data
     */
    public function save_meta_box($post_id, $post = null) {
        // Verify nonce
        if (!isset($_POST['humangate_meta_box_nonce'])) {
            return;
        }
        $nonce = sanitize_text_field(wp_unslash($_POST['humangate_meta_box_nonce']));
        if (!wp_verify_nonce($nonce, 'humangate_save_meta_box')) {
            return;
        }
        
        // Check autosave
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }
        
        // Check permissions
        if (!current_user_can('edit_post', $post_id)) {
            return;
        }
        
        // Save value
        if (isset($_POST['humangate_refusal_enabled'])) {
            $value = sanitize_text_field(wp_unslash($_POST['humangate_refusal_enabled']));
            $allowed_values = ['enabled', 'disabled', 'inherit'];
            
            if (in_array($value, $allowed_values, true)) {
                update_post_meta($post_id, '_humangate_refusal_enabled', $value);
            }
        }
    }
    
    /**
     * Check if the current content's post type is enabled in content type control
     * 
     * @param string|null $post_type Optional post type to check. If null, detects current content.
     * @return bool True if post type is enabled, false otherwise
     */
    private function is_post_type_enabled($post_type = null) {
        // If no post type provided, detect from current context
        if ($post_type === null) {
            if (is_singular()) {
                global $post;
                if ($post) {
                    $post_type = $post->post_type;
                } else {
                    return false;
                }
            } elseif (is_archive()) {
                $queried_object = get_queried_object();
                if ($queried_object && isset($queried_object->name)) {
                    $post_type = $queried_object->name;
                } elseif ($queried_object && isset($queried_object->taxonomy)) {
                    // For taxonomy archives, check all associated post types
                    $taxonomy = get_taxonomy($queried_object->taxonomy);
                    if ($taxonomy && !empty($taxonomy->object_type)) {
                        foreach ($taxonomy->object_type as $pt) {
                            $setting = 'humang_refusal_post_types_' . $pt;
                            if (get_option($setting, true)) {
                                return true; // If any associated post type is enabled
                            }
                        }
                        return false; // None enabled
                    }
                } else {
                    global $wp_query;
                    if (!empty($wp_query->query_vars['post_type'])) {
                        $post_type = is_array($wp_query->query_vars['post_type']) 
                            ? $wp_query->query_vars['post_type'][0] 
                            : $wp_query->query_vars['post_type'];
                    }
                }
            }
        }
        
        if (empty($post_type)) {
            return false;
        }
        
        // Check if this post type is enabled in content type control
        $setting = 'humang_refusal_post_types_' . $post_type;
        return get_option($setting, true);
    }
    
    /**
     * Check if refusal should be applied to current content
     * Logic: AI blocking must be enabled AND post type must be selected
     * 
     * @return bool True if refusal should be applied, false otherwise
     */
    public function should_apply_refusal() {
        // Check if AI blocking is enabled
        $global_refusal = get_option('humang_global_refusal', true);
        if (!$global_refusal) {
            return false;
        }
        
        // Check if we're on a singular post/page
        if (is_singular()) {
            global $post;
            
            if (!$post) {
                return false;
            }
            
            // Get per-post setting
            $post_setting = get_post_meta($post->ID, '_humangate_refusal_enabled', true);
            
            // If explicitly enabled, always apply
            if ($post_setting === 'enabled') {
                return true;
            }
            
            // If explicitly disabled, never apply
            if ($post_setting === 'disabled') {
                return false;
            }
            
            // If inherit or not set, check if post type is enabled in content type control
            return $this->is_post_type_enabled($post->post_type);
        }
        
        // For archive pages and other content, check if post type is enabled
        return $this->is_post_type_enabled();
    }
    
    /**
     * Check if search engine blocking should be applied to current content
     * Logic: Search engine blocking must be enabled AND post type must be selected
     * 
     * @return bool True if search engine blocking should be applied, false otherwise
     */
    public function should_apply_search_engine_blocking() {
        // Check if search engine blocking is enabled
        $block_search_engines = get_option('humang_block_search_engines', true);
        if (!$block_search_engines) {
            return false;
        }
        
        // Check if we're on a singular post/page
        if (is_singular()) {
            global $post;
            
            if (!$post) {
                return false;
            }
            
            // Check if post type is enabled in content type control
            return $this->is_post_type_enabled($post->post_type);
        }
        
        // For archive pages and other content, check if post type is enabled
        return $this->is_post_type_enabled();
    }
    
    /**
     * Get all public post types with their settings
     * 
     * @return array Array of post type objects with settings
     */
    public function get_post_types_with_settings() {
        $post_types = get_post_types(['public' => true], 'objects');
        $result = [];
        
        foreach ($post_types as $post_type) {
            $setting_name = 'humang_refusal_post_types_' . $post_type->name;
            $enabled = get_option($setting_name, true);
            
            $result[] = [
                'name' => $post_type->name,
                'label' => $post_type->label,
                'enabled' => $enabled,
            ];
        }
        
        return $result;
    }
}
