<?php
/**
 * Admin interface for LLMS.txt Generator
 */
if (!defined('ABSPATH')) {
    exit;
}
class CCSPLLMS_Admin {
    
    public function __construct() {
        add_action('admin_menu', array($this, 'add_admin_menu'));
        add_action('admin_init', array($this, 'register_settings'));

        add_action('wp_ajax_ccspllms_save_custom_content', array($this, 'save_custom_content')); 

        add_action('wp_ajax_ccspllms_delete_history', array($this, 'delete_history_entries'));

        add_action('wp_ajax_ccspllms_update_bot_status', array($this, 'update_bot_status'));
        add_action('wp_ajax_ccspllms_export_analytics', array($this, 'export_analytics'));

    }
    
    public function add_admin_menu() {
        add_menu_page(
            'LLMS Generator',
            'LLMS Generator',
            'manage_options',
            'ccspllms-generator',
            array($this, 'admin_page'),
            'dashicons-edit-page',
            30
        );
        
        add_submenu_page(
            'ccspllms-generator',
            'Dashboard',
            'Dashboard',
            'manage_options',
            'ccspllms-generator',
            array($this, 'admin_page')
        );
        
        add_submenu_page(
            'ccspllms-generator',
            'Settings',
            'Settings',
            'manage_options',
            'ccspllms-settings',
            array($this, 'settings_page')
        );
        
        add_submenu_page(
            'ccspllms-generator',
            'Content Management',
            'Content Management',
            'manage_options',
            'ccspllms-content',
            array($this, 'content_page')
        );
        
        add_submenu_page(
            'ccspllms-generator',
            'Bot Analytics',
            'Bot Analytics',
            'manage_options',
            'ccspllms-analytics',
            array($this, 'analytics_page')
        );
        
        add_submenu_page(
            'ccspllms-generator',
            'Cron Settings',
            'Cron Settings',
            'manage_options',
            'ccspllms-cron',
            array($this, 'cron_page')
        );
        
        add_submenu_page(
            'ccspllms-generator',
            'Advanced Settings',
            'Advanced Settings',
            'manage_options',
            'ccspllms-advanced',
            array($this, 'advanced_page')
        );
    }
    
   
    public function register_settings() {
    register_setting('ccspllms_settings', 'ccspllms_enabled', array(
        'sanitize_callback' => 'ccspllms_sanitize_checkbox',
        'default' => 0
    ));
    register_setting('ccspllms_settings', 'ccspllms_site_title', array(
        'sanitize_callback' => 'ccspllms_sanitize_text',
    ));
    register_setting('ccspllms_settings', 'ccspllms_site_tagline', array(
        'sanitize_callback' => 'ccspllms_sanitize_text',
    ));
    register_setting('ccspllms_settings', 'ccspllms_post_types', array(
        'sanitize_callback' => 'ccspllms_sanitize_text',
    ));
    register_setting('ccspllms_settings', 'ccspllms_excerpt_priority', array(
        'sanitize_callback' => 'ccspllms_sanitize_text',
    ));
    register_setting('ccspllms_settings', 'ccspllms_word_limit', array(
        'sanitize_callback' => 'ccspllms_sanitize_int',
    ));
    register_setting('ccspllms_settings', 'ccspllms_use_canonical', array(
        'sanitize_callback' => 'ccspllms_sanitize_checkbox',
    ));
    register_setting('ccspllms_settings', 'ccspllms_auto_regenerate', array(
        'sanitize_callback' => 'ccspllms_sanitize_checkbox',
    ));
    register_setting('ccspllms_settings', 'ccspllms_email_notifications', array(
        'sanitize_callback' => 'ccspllms_sanitize_checkbox',
    ));
    register_setting('ccspllms_settings', 'ccspllms_notification_email', array(
        'sanitize_callback' => 'ccspllms_sanitize_email',
    ));
    register_setting('ccspllms_settings', 'ccspllms_cron_frequency', array(
        'sanitize_callback' => 'ccspllms_sanitize_cron_frequency',
    ));
    register_setting('ccspllms_settings', 'ccspllms_cron_time', array(
        'sanitize_callback' => 'ccspllms_sanitize_text',
    ));
    register_setting('ccspllms_settings', 'ccspllms_debug_logging', array(
        'sanitize_callback' => 'ccspllms_sanitize_checkbox',
    ));
    }

    
    public function admin_page() {
        include_once CCSPLLMS_PLUGIN_DIR . 'admin/partials/ccspllms-admin-display.php';
    }
    
    public function settings_page() {
        include_once CCSPLLMS_PLUGIN_DIR . 'admin/partials/ccspllms-settings-display.php';
    }
    
    public function content_page() {
        include_once CCSPLLMS_PLUGIN_DIR . 'admin/partials/ccspllms-content-display.php';
    }
    
    public function analytics_page() {
        include_once CCSPLLMS_PLUGIN_DIR . 'admin/partials/ccspllms-analytics-display.php';
    }
    
    public function cron_page() {
        include_once CCSPLLMS_PLUGIN_DIR . 'admin/partials/ccspllms-cron-display.php';
    }
    
    public function advanced_page() {
        include_once CCSPLLMS_PLUGIN_DIR . 'admin/partials/ccspllms-advanced-display.php';
    }


    // Admin page edit
    public function save_custom_content() {
        check_ajax_referer('ccspllms_nonce');
        if (!current_user_can('edit_posts')) {
            wp_send_json_error('Unauthorized');
        }
        $post_id = isset($_POST['post_id']) ? absint(wp_unslash($_POST['post_id'])) : 0;
        $custom_content = sanitize_textarea_field(isset($_POST['custom_content']) ? wp_unslash($_POST['custom_content']) : '');
        if ($post_id) {
            if ($custom_content) {
                update_post_meta($post_id, '_ccspllms_custom_content', $custom_content);
            } else {
                delete_post_meta($post_id, '_ccspllms_custom_content');
            }
            wp_send_json_success();
        }
        wp_send_json_error('Invalid post ID');
    }

    // Delete history in cron page
    /**
 * Delete history entries via AJAX.
 */
public function delete_history_entries() {

            // Verify nonce for CSRF protection.
            check_ajax_referer( 'ccspllms_nonce', 'ccspllms_delete_history' );

            // Ensure the user has permission.
            if ( ! current_user_can( 'manage_options' ) ) {
                wp_send_json_error( __( 'Unauthorized request.', 'cloudcusp-llms-txt-generator' ), 403 );
            }

            // Sanitize IDs.
            $ids = array();
            if ( isset( $_POST['ids'] ) && is_array( $_POST['ids'] ) ) {
                $ids = array_map( 'absint', wp_unslash( $_POST['ids'] ) );
            }

            if ( empty( $ids ) ) {
                wp_send_json_error( __( 'No valid IDs provided.', 'cloudcusp-llms-txt-generator' ), 400 );
            }

            global $wpdb;

            $table = $wpdb->prefix . 'ccspllms_generation_log';

            // Prepare placeholders for the IN clause.
            $placeholders = implode( ', ', array_fill( 0, count( $ids ), '%d' ) );

            // Safely prepare the query.
            $sql     = $wpdb->prepare( "DELETE FROM {$table} WHERE id IN ($placeholders)", $ids );
            $deleted = $wpdb->query( $sql );

            if ( false !== $deleted ) {
                wp_send_json_success(
                    array(
                        'deleted' => $deleted,
                        'message' => __( 'Entries deleted successfully.', 'cloudcusp-llms-txt-generator' ),
                    )
                );
            } else {
                wp_send_json_error( __( 'Failed to delete entries.', 'cloudcusp-llms-txt-generator' ), 500 );
            }
        }


    public function update_bot_status() {
    
        check_ajax_referer('ccspllms_nonce', 'ccspllms_update_bot_nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Unauthorized');
        }

        $bot_name = isset($_POST['bot_name']) ? sanitize_text_field( wp_unslash( $_POST['bot_name'] ) ) : '';
        $status_input = isset($_POST['status']) ? intval($_POST['status']) : 0;

        // Map 1/0 to allowed/blocked
        $status = ($status_input === 1) ? 'allowed' : 'blocked';

        global $wpdb;
        $bots_table = $wpdb->prefix . 'ccspllms_bots';

        $updated = $wpdb->update(
            $bots_table,
            array('status' => $status),
            array('bot_name' => $bot_name),
            array('%s'),
            array('%s')
        );

        if ($updated !== false) {
            wp_send_json_success();
        } else {
            wp_send_json_error('Failed to update status');
        }
    }

    public function export_analytics() {
        check_ajax_referer('ccspllms_nonce', 'ccspllms_export_nonce');
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Unauthorized');
        }
        // Safely get format (works whether POST or GET)
        $format = isset($_REQUEST['format']) ? sanitize_text_field(wp_unslash($_REQUEST['format'])) : 'csv';
        $format = ($format === 'json') ? 'json' : 'csv';

        $analytics = new CCSPLLMS_Analytics();
        $output = $analytics->export_analytics_data($format);
        if ($format === 'csv') {
            header('Content-Type: text/csv');
            header('Content-Disposition: attachment; filename="analytics.csv"');
            echo esc_html($output);

        } else {
            header('Content-Type: application/json');
            header('Content-Disposition: attachment; filename="analytics.json"');
            echo esc_html($output);

        }
        exit;
    }

    
        

}

     /**
     * Sanitization functions for plugin settings
     */
    function ccspllms_sanitize_checkbox($value) {
        return ($value === '1' || $value === 1 || $value === true || $value === 'on') ? 1 : 0;
    }

    function ccspllms_sanitize_text($value) {
        return sanitize_text_field($value);
    }

    function ccspllms_sanitize_int($value) {
        return intval($value);
    }

    function ccspllms_sanitize_email($value) {
        return sanitize_email($value);
    }

    function ccspllms_sanitize_cron_frequency($value) {
        $allowed = array('hourly', 'twicedaily', 'daily', 'weekly');
        return in_array($value, $allowed) ? $value : 'daily';
    }

// Initialize admin
if (is_admin()) {
    new CCSPLLMS_Admin();
}
