<?php

namespace ACB\Inc\Ajax_Parts;
use \ACB\Inc\ACB_BaseController;

defined('ABSPATH') or die('Hey, what are you doing here? You silly human!');

/**
 * Ajax handle
 */
class ACB_MessageCreation {

    public function __construct() {
        /**
         * Message fetch from database
         */
        $this->ACB_message_truncate();
        $this->ACB_message_creation();
    }

    /**
     * Handle settings data update
     */
    public function ACB_message_truncate() {
        // Check if the action is correct
        if (!isset($_POST['action']) || sanitize_text_field(wp_unslash($_POST['action'])) !== 'acb_data_truncate') {
            return;
        }

        // Verify nonce for security
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'acb_settings_nonce')) {
            wp_die(__('Security check failed', 'acb'));
        }

        // Check user capabilities
        if (!current_user_can('manage_options')) {
            wp_die(__('You do not have sufficient permissions to access this page.', 'acb'));
        }

        /**
         * Sanitize all form data
         */
        $ac_frontend = isset($_POST['acb_frontend']) ? sanitize_text_field(wp_unslash($_POST['acb_frontend'])) : '';
        $ac_backend = isset($_POST['acb_backend']) ? sanitize_text_field(wp_unslash($_POST['acb_backend'])) : '';
        $ac_position = isset($_POST['acb_position']) ? sanitize_text_field(wp_unslash($_POST['acb_position'])) : '';
        $ac_customization = isset($_POST['acb_customization']) ? sanitize_text_field(wp_unslash($_POST['acb_customization'])) : '';
        $ac_bg_color_value = isset($_POST['bg_color_value']) ? sanitize_hex_color(wp_unslash($_POST['bg_color_value'])) : '';
        $ac_left_pos_value = isset($_POST['left_pos_value']) ? absint(wp_unslash($_POST['left_pos_value'])) : 0;
        $right_pos_value = isset($_POST['right_pos_value']) ? absint(wp_unslash($_POST['right_pos_value'])) : 0;

        /**
         * Prepare settings array
         */
        $settings_page = array(
            'acb_frontend_settings' => $ac_frontend,
            'acb_backend_settings' => $ac_backend,
            'acb_position_settings' => $ac_position,
            'acb_customization_settings' => $ac_customization,
            'acb_bg_color_value_settings' => $ac_bg_color_value,
            'acb_left_pos_value_settings' => $ac_left_pos_value,
            'acb_right_pos_value_settings' => $right_pos_value,
        );

        // Update option and send response
        if (update_option('acb_settings_value', wp_json_encode($settings_page))) {
            wp_send_json_success(__('Settings saved successfully', 'acb'));
        } else {
            wp_send_json_error(__('Failed to save settings', 'acb'));
        }
    }

    /**
     * Fetch messages from database
     */
    public function ACB_message_creation() {
        // Verify nonce for security
        $permission = check_ajax_referer('acb_msg_post_nonce', 'nonce', false);
        if (!$permission) {
            wp_die(__('Security check failed', 'acb'));
        }

        // Check user capabilities
        if (!current_user_can('read')) {
            wp_die(__('You do not have sufficient permissions to access this page.', 'acb'));
        }

        global $wpdb;
        $wpdb->hide_errors();
        
        // Use wpdb->prepare for secure database query
        $table = $wpdb->prefix . 'acb_admin_chat_box';
        $fetch = $wpdb->get_results($wpdb->prepare("SELECT * FROM `%1s` ORDER BY id DESC", $table));

        if (!$fetch) {
            wp_send_json_error(__('No messages found', 'acb'));
        }

        // Start output buffering to capture the HTML
        ob_start();

        foreach ($fetch as $message) {
            // Sanitize and validate the JSON data
            $all_data = wp_kses_post($message->data);
            $manage = json_decode($all_data, true);

            // Validate JSON decode
            if (json_last_error() !== JSON_ERROR_NONE || !is_array($manage)) {
                continue; // Skip invalid JSON data
            }

            // Sanitize individual fields
            $user_name = isset($manage['acb_user_name']) ? sanitize_text_field($manage['acb_user_name']) : '';
            $user_msg = isset($manage['acb_user_msg']) ? wp_kses_post($manage['acb_user_msg']) : '';
            $user_id = isset($manage['user_id']) ? absint($manage['user_id']) : 0;
            $msg_date = isset($manage['acb_msg_date']) ? sanitize_text_field($manage['acb_msg_date']) : '';

            // Validate and format date
            $formatted_date = '';
            if (!empty($msg_date)) {
                $timestamp = strtotime($msg_date);
                if ($timestamp !== false) {
                    $formatted_date = date_i18n('M d, Y > h:i A', $timestamp);
                }
            }

            // Output the message HTML with proper escaping
            ?>
            <span class="nick" style="color: black"><?php echo esc_html($user_name); ?></span>: 
            <span class="msg" id="incoming_msg" data-id="<?php echo esc_attr($user_id); ?>">
                <?php echo wp_kses_post($user_msg); ?>
                <br>
                <span style="font-size:10px;color:#5a3c04;">
                    <?php echo esc_html($formatted_date); ?>
                    <br>
                </span>
            </span>
            <br />
            <?php
        }

        // Get the output and clean the buffer
        $output = ob_get_clean();
        
        // Send JSON response with the HTML content
        wp_send_json_success($output);
    }
}