<?php
/**
 * FAQ Manager Admin Interface
 */

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

class PC_FAQ_Manager_Admin {
    
    /**
     * Constructor
     */
    public function __construct() {
        add_action('admin_menu', array($this, 'add_admin_menu'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
        add_action('wp_ajax_pc_faq_reorder', array($this, 'handle_ajax_reorder'));
        add_action('wp_ajax_pc_faq_add_new', array($this, 'handle_ajax_add_new'));
        add_action('wp_ajax_pc_faq_edit', array($this, 'handle_ajax_edit'));
        add_action('wp_ajax_pc_faq_delete', array($this, 'handle_ajax_delete'));
    }
    
    /**
     * Add admin menu
     */
    public function add_admin_menu() {
        add_menu_page(
            __('FAQ Manager', PC_FAQ_MANAGER_SLUG),
            __('FAQ', PC_FAQ_MANAGER_SLUG),
            'manage_options',
            'pc-faq-manager',
            array($this, 'render_main_page'),
            'dashicons-editor-help',
            25
        );
        
        add_submenu_page(
            'pc-faq-manager',
            __('All FAQs', PC_FAQ_MANAGER_SLUG),
            __('All FAQs', PC_FAQ_MANAGER_SLUG),
            'manage_options',
            'pc-faq-manager',
            array($this, 'render_main_page')
        );
        
        add_submenu_page(
            'pc-faq-manager',
            __('Add New FAQ', PC_FAQ_MANAGER_SLUG),
            __('Add New', PC_FAQ_MANAGER_SLUG),
            'manage_options',
            'pc-faq-manager-add',
            array($this, 'render_add_page')
        );
    }
    
    /**
     * Enqueue admin scripts and styles
     */
    public function enqueue_admin_scripts($hook) {
        if (strpos($hook, 'pc-faq-manager') !== false) {
            wp_enqueue_style('pc-faq-manager-admin', PC_FAQ_MANAGER_PLUGIN_URL . 'admin/css/admin-style.css', array(), PC_FAQ_MANAGER_VERSION);
            wp_enqueue_script('jquery-ui-sortable');
            wp_enqueue_script('pc-faq-manager-admin', PC_FAQ_MANAGER_PLUGIN_URL . 'admin/js/admin-script.js', array('jquery', 'jquery-ui-sortable'), PC_FAQ_MANAGER_VERSION, true);
            wp_localize_script('pc-faq-manager-admin', 'pc_faq_manager', array(
                'ajax_url' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('pc_faq_manager_nonce'),
                'confirm_delete' => __('Are you sure you want to delete this FAQ?', PC_FAQ_MANAGER_SLUG),
                'saving' => __('Saving...', PC_FAQ_MANAGER_SLUG),
                'saved' => __('Saved!', PC_FAQ_MANAGER_SLUG),
                'error' => __('Error occurred. Please try again.', PC_FAQ_MANAGER_SLUG),
            ));
        }
    }
    
    /**
     * Render main admin page
     */
    public function render_main_page() {
        if (!PC_FAQ_Manager_Helper::can_manage_faqs()) {
            wp_die(__('You do not have sufficient permissions to access this page.', PC_FAQ_MANAGER_SLUG));
        }
        
        $faqs = PC_FAQ_Manager_Helper::get_faqs();
        $faq_count = PC_FAQ_Manager_Helper::get_faq_count();
        
        include PC_FAQ_MANAGER_PLUGIN_DIR . 'admin/templates/main-page.php';
    }
    
    /**
     * Render add new FAQ page
     */
    public function render_add_page() {
        if (!PC_FAQ_Manager_Helper::can_manage_faqs()) {
            wp_die(__('You do not have sufficient permissions to access this page.', PC_FAQ_MANAGER_SLUG));
        }
        
        include PC_FAQ_MANAGER_PLUGIN_DIR . 'admin/templates/add-page.php';
    }
    
    /**
     * Handle AJAX reorder request
     */
    public function handle_ajax_reorder() {
        check_ajax_referer('pc_faq_manager_nonce', 'nonce');
        
        if (!PC_FAQ_Manager_Helper::can_manage_faqs()) {
            wp_die(__('Permission denied.', PC_FAQ_MANAGER_SLUG));
        }
        
        if (isset($_POST['faq_ids']) && is_array($_POST['faq_ids'])) {
            $result = PC_FAQ_Manager_Helper::reorder_faqs($_POST['faq_ids']);
            
            if ($result) {
                wp_send_json_success(array('message' => __('FAQs reordered successfully.', PC_FAQ_MANAGER_SLUG)));
            } else {
                wp_send_json_error(array('message' => __('Failed to reorder FAQs.', PC_FAQ_MANAGER_SLUG)));
            }
        }
        
        wp_send_json_error(array('message' => __('Invalid request.', PC_FAQ_MANAGER_SLUG)));
    }
    
    /**
     * Handle AJAX add new FAQ
     */
    public function handle_ajax_add_new() {
        check_ajax_referer('pc_faq_manager_nonce', 'nonce');
        
        if (!PC_FAQ_Manager_Helper::can_manage_faqs()) {
            wp_die(__('Permission denied.', PC_FAQ_MANAGER_SLUG));
        }
        
        $title = sanitize_text_field($_POST['title'] ?? '');
        $content = wp_kses_post($_POST['content'] ?? '');
        
        if (empty($title) || empty($content)) {
            wp_send_json_error(array('message' => __('Title and content are required.', PC_FAQ_MANAGER_SLUG)));
        }
        
        $faq_data = array(
            'post_title' => $title,
            'post_content' => $content,
            'post_status' => 'publish',
            'post_type' => 'pc_faq',
        );
        
        $faq_id = wp_insert_post($faq_data);
        
        if ($faq_id && !is_wp_error($faq_id)) {
            $max_order = PC_FAQ_Manager_Helper::get_max_order();
            update_post_meta($faq_id, '_pc_faq_order', $max_order + 1);
            
            wp_send_json_success(array(
                'message' => __('FAQ added successfully.', PC_FAQ_MANAGER_SLUG),
                'faq_id' => $faq_id,
            ));
        } else {
            wp_send_json_error(array('message' => __('Failed to add FAQ.', PC_FAQ_MANAGER_SLUG)));
        }
    }
    
    /**
     * Handle AJAX edit FAQ
     */
    public function handle_ajax_edit() {
        check_ajax_referer('pc_faq_manager_nonce', 'nonce');
        
        if (!PC_FAQ_Manager_Helper::can_manage_faqs()) {
            wp_die(__('Permission denied.', PC_FAQ_MANAGER_SLUG));
        }
        
        $faq_id = intval($_POST['faq_id'] ?? 0);
        $title = sanitize_text_field($_POST['title'] ?? '');
        $content = wp_kses_post($_POST['content'] ?? '');
        
        if (!$faq_id || empty($title) || empty($content)) {
            wp_send_json_error(array('message' => __('Invalid data provided.', PC_FAQ_MANAGER_SLUG)));
        }
        
        $faq_data = array(
            'ID' => $faq_id,
            'post_title' => $title,
            'post_content' => $content,
        );
        
        $result = wp_update_post($faq_data);
        
        if ($result && !is_wp_error($result)) {
            wp_send_json_success(array('message' => __('FAQ updated successfully.', PC_FAQ_MANAGER_SLUG)));
        } else {
            wp_send_json_error(array('message' => __('Failed to update FAQ.', PC_FAQ_MANAGER_SLUG)));
        }
    }
    
    /**
     * Handle AJAX delete FAQ
     */
    public function handle_ajax_delete() {
        check_ajax_referer('pc_faq_manager_nonce', 'nonce');
        
        if (!PC_FAQ_Manager_Helper::can_manage_faqs()) {
            wp_die(__('Permission denied.', PC_FAQ_MANAGER_SLUG));
        }
        
        $faq_id = intval($_POST['faq_id'] ?? 0);
        
        if (!$faq_id) {
            wp_send_json_error(array('message' => __('Invalid FAQ ID.', PC_FAQ_MANAGER_SLUG)));
        }
        
        $result = wp_delete_post($faq_id, true);
        
        if ($result) {
            wp_send_json_success(array('message' => __('FAQ deleted successfully.', PC_FAQ_MANAGER_SLUG)));
        } else {
            wp_send_json_error(array('message' => __('Failed to delete FAQ.', PC_FAQ_MANAGER_SLUG)));
        }
    }
}