<?php
/**
 * Core functionality for LLMS.txt Generator
 */
if (!defined('ABSPATH')) {
    exit;
}
class CCSPLLMS_Core {
    
    public function init() {
        add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
        add_action('add_meta_boxes', array($this, 'add_meta_boxes'));
        add_action('save_post', array($this, 'save_post_meta'));
        add_action('wp_ajax_ccspllms_regenerate', array($this, 'ajax_regenerate_file'));
        add_action('wp_ajax_ccspllms_toggle_post', array($this, 'ajax_toggle_post'));
        add_action('wp_ajax_ccspllms_bulk_action', array($this, 'ajax_bulk_action'));
        add_action('wp_ajax_ccspllms_get_analytics', array($this, 'ajax_get_analytics'));
    }
    
    public function enqueue_scripts() {
        // Frontend scripts if needed
    }
    
    public function enqueue_admin_scripts($hook) {
        if (strpos($hook, 'ccspllms') !== false) {
            // Correct path to your CSS file
            $css_path = plugin_dir_path(__FILE__) . 'assets/css/ccspllms-admin.css';
            $css_ver  = file_exists($css_path) ? filemtime($css_path) : CCSPLLMS_VERSION;

            wp_enqueue_style(
                'ccspllms-admin-css',
                CCSPLLMS_PLUGIN_URL . 'assets/css/ccspllms-admin.css',
                array(),
                $css_ver
            );

            // Correct path to your JS file
            $js_path = plugin_dir_path(__FILE__) . 'assets/js/ccspllms-admin.js';
            $js_ver  = file_exists($js_path) ? filemtime($js_path) : CCSPLLMS_VERSION;

            wp_enqueue_script(
                'ccspllms-admin-js',
                CCSPLLMS_PLUGIN_URL . 'assets/js/ccspllms-admin.js',
                array('jquery'),
                $js_ver,
                true
            );

            wp_enqueue_style(
                'ccspllms-fontawesome',
                CCSPLLMS_PLUGIN_URL . 'assets/css/fontawesome.min.css',
                array(),
                '5.15.4' 
            );

            
            wp_localize_script('ccspllms-admin-js', 'ccspllms_ajax', array(
                    'ajax_url' => admin_url('admin-ajax.php'),
                    'nonce' => wp_create_nonce('ccspllms_nonce')
                ));

            // Pass analytics data to JS for chart
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            if (isset($_GET['page']) && strpos(sanitize_text_field(wp_unslash($_GET['page'])), 'ccspllms') !== false) {
                $analytics = new CCSPLLMS_Analytics();
                $data = $analytics->get_analytics_data();
                wp_localize_script(
                    'ccspllms-admin-js',
                    'ccspllmsAnalyticsData',
                    $data['daily_stats'] ?? []
                );
            }

            wp_enqueue_script('chartjs', CCSPLLMS_PLUGIN_URL . 'assets/js/chart.js', array(), CCSPLLMS_VERSION, true);


            }  
    }
    
    public function add_meta_boxes() {
        $post_types = get_option('ccspllms_post_types', array('post', 'page'));
        if (!is_array($post_types)) {
            if (empty($post_types)) {
                $post_types = array();
            } else {
                $post_types = explode(',', $post_types);
                $post_types = array_map('trim', $post_types);
            }
        }
        foreach ($post_types as $post_type) {
            if (!empty($post_type)) {
                add_meta_box(
                    'ccspllms_meta_box',
                    'LLMS.txt Settings',
                    array($this, 'render_meta_box'),
                    $post_type,
                    'side',
                    'default'
                );
            }
        }
    }
    
    public function render_meta_box($post) {
        wp_nonce_field('ccspllms_meta_box', 'ccspllms_meta_box_nonce');
        
        $excluded = get_post_meta($post->ID, '_ccspllms_excluded', true);
        $custom_content = get_post_meta($post->ID, '_ccspllms_custom_content', true);
        
        echo '<p><label>';
        echo '<input type="checkbox" name="ccspllms_excluded" value="1" ' . checked($excluded, 1, false) . '>';
        echo ' Exclude from LLMS.txt</label></p>';
        
        echo '<p><label for="ccspllms_custom_content">Custom Content:</label></p>';
        echo '<textarea name="ccspllms_custom_content" id="ccspllms_custom_content" rows="4" style="width:100%;">' . esc_textarea($custom_content) . '</textarea>';
        echo '<p class="description">Leave empty to use auto-generated content.</p>';
    }
    
/**
 * Save custom post meta for CCSPLLMS.
 *
 * @param int $post_id Post ID.
 * @return void
 */
    public function save_post_meta( $post_id ) {

        // Bail if our nonce is not set.
        if ( ! isset( $_POST['ccspllms_meta_box_nonce'] ) ) {
            return;
        }

        // Always unslash before sanitizing.
        $raw_nonce = wp_unslash( $_POST['ccspllms_meta_box_nonce'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
        $nonce     = sanitize_text_field( $raw_nonce );

        // Verify the nonce.
        if ( ! wp_verify_nonce( $nonce, 'ccspllms_meta_box' ) ) {
            return;
        }

        // Prevent autosave from overwriting data.
        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
            return;
        }

        // Verify user capabilities.
        if ( ! current_user_can( 'edit_post', $post_id ) ) {
            return;
        }

        // Sanitize and save excluded flag.
        $excluded = isset( $_POST['ccspllms_excluded'] ) ? 1 : 0;
        update_post_meta( $post_id, '_ccspllms_excluded', $excluded );

        // Sanitize and save custom content.
        if ( isset( $_POST['ccspllms_custom_content'] ) && sanitize_text_field( wp_unslash( $_POST['ccspllms_custom_content'] ) ) ) {
            // Get the actual content isset() returns a boolean, not the actual content.
            $raw_content = isset($_POST['ccspllms_custom_content'])
                            ? sanitize_text_field( wp_unslash( $_POST['ccspllms_custom_content'] ) )
                            : '';

            $custom_content = sanitize_textarea_field( $raw_content );
            update_post_meta( $post_id, '_ccspllms_custom_content', $custom_content );
        }

        // Regenerate file if auto-generation is enabled.
        if ( (int) get_option( 'ccspllms_auto_regenerate', 1 ) === 1 ) {
            if ( class_exists( 'CCSPLLMS_Generator' ) ) {
                $generator = new CCSPLLMS_Generator();
                $generator->generate_file();
            } 
        }
    }

    
    public function ajax_regenerate_file() {
        check_ajax_referer('ccspllms_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_die('Unauthorized');
        }
        
        $generator = new CCSPLLMS_Generator();
        $result = $generator->generate_file();
        
        if ($result) {
            wp_send_json_success(array(
                'message' => 'LLMS.txt file generated successfully!',
                'timestamp' => current_time('mysql'),
                'file_size' => $generator->get_file_size()
            ));
        } else {
            wp_send_json_error('Failed to generate LLMS.txt file');
        }
    }
    
    public function ajax_toggle_post() {
        check_ajax_referer('ccspllms_nonce', 'nonce');
        
        $post_id = intval(isset($_POST['post_id']) ? $_POST['post_id'] : 0);
        $excluded = intval(isset($_POST['excluded']) ? $_POST['excluded'] : 0);
        
        update_post_meta($post_id, '_ccspllms_excluded', $excluded);
        
        wp_send_json_success();
    }
    
    public function ajax_bulk_action() {
        check_ajax_referer('ccspllms_nonce', 'nonce');
        
        $action = isset($_POST['action_type']) ? sanitize_text_field( wp_unslash( $_POST['action_type'] ) ) : '';
        $post_ids = isset($_POST['post_ids']) ? array_map('intval', (array) wp_unslash($_POST['post_ids'])) : [];

        
        foreach ($post_ids as $post_id) {
            switch ($action) {
                case 'enable':
                    update_post_meta($post_id, '_ccspllms_excluded', 0);
                    break;
                case 'disable':
                    update_post_meta($post_id, '_ccspllms_excluded', 1);
                    break;
                case 'reset':
                    delete_post_meta($post_id, '_ccspllms_custom_content');
                    break;
            }
        }
        
        wp_send_json_success();
    }
    
    public function ajax_get_analytics() {
        check_ajax_referer('ccspllms_nonce', 'nonce');
        
        $analytics = new CCSPLLMS_Analytics();
        $data = $analytics->get_analytics_data();
        
        wp_send_json_success($data);
    }
}