<?php
/**
 * FAQ Manager Helper Class
 */

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

class PC_FAQ_Manager_Helper {
    
    /**
     * Get all FAQs ordered by order meta
     */
    public static function get_faqs($posts_per_page = -1) {
        $args = array(
            'post_type' => 'pc_faq',
            'post_status' => 'publish',
            'posts_per_page' => $posts_per_page,
            'orderby' => 'meta_value_num',
            'meta_key' => '_pc_faq_order',
            'order' => 'ASC',
        );
        
        return get_posts($args);
    }
    
    /**
     * Get FAQ count
     */
    public static function get_faq_count() {
        $args = array(
            'post_type' => 'pc_faq',
            'post_status' => 'publish',
            'posts_per_page' => 1,
        );
        
        $query = new WP_Query($args);
        return $query->found_posts;
    }
    
    /**
     * Reorder FAQs
     */
    public static function reorder_faqs($faq_ids) {
        if (!is_array($faq_ids) || empty($faq_ids)) {
            return false;
        }
        
        foreach ($faq_ids as $order => $faq_id) {
            $faq_id = intval($faq_id);
            $order = intval($order);
            
            if ($faq_id > 0) {
                update_post_meta($faq_id, '_pc_faq_order', $order);
            }
        }
        
        return true;
    }
    
    /**
     * Get max order value
     */
    public static function get_max_order() {
        global $wpdb;
        
        $max_order = $wpdb->get_var($wpdb->prepare(
            "SELECT MAX(CAST(meta_value AS SIGNED)) 
             FROM {$wpdb->postmeta} 
             WHERE meta_key = %s",
            '_pc_faq_order'
        ));
        
        return $max_order ? intval($max_order) : 0;
    }
    
    /**
     * Sanitize and validate FAQ data
     */
    public static function sanitize_faq_data($data) {
        $sanitized = array();
        
        if (isset($data['title'])) {
            $sanitized['title'] = sanitize_text_field($data['title']);
        }
        
        if (isset($data['content'])) {
            $sanitized['content'] = wp_kses_post($data['content']);
        }
        
        if (isset($data['order'])) {
            $sanitized['order'] = intval($data['order']);
        }
        
        return $sanitized;
    }
    
    /**
     * Check user capabilities
     */
    public static function can_manage_faqs() {
        return current_user_can('manage_options') || current_user_can('edit_posts');
    }
}