<?php
/**
 * Wizard Session Management
 */
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class Trstemp_WizardSession {
    
    private static $session_key = 'trstemp_wizard_data';
    
    public static function save_step_data($step, $data) {
        $session_data = self::get_session_data();
        
        // Sanitize data before saving
        if (is_array($data)) {
            $data = self::sanitize_data($data);
        }
        
        $session_data['step_' . $step] = $data;
        $session_data['last_step'] = $step;
        $session_data['updated_at'] = time();
        
        update_option(self::$session_key, $session_data);
        
        // phpcs:disable WordPress.PHP.DevelopmentFunctions.error_log_error_log, WordPress.PHP.DevelopmentFunctions.error_log_print_r -- Debug logging
        // Debug log
        error_log('TRSTEMP: Saved step ' . $step . ' data: ' . print_r($data, true));
        // phpcs:enable WordPress.PHP.DevelopmentFunctions.error_log_error_log, WordPress.PHP.DevelopmentFunctions.error_log_print_r
    }
    
    public static function get_step_data($step) {
        $session_data = self::get_session_data();
        $step_data = isset($session_data['step_' . $step]) ? $session_data['step_' . $step] : array();
        
        // phpcs:disable WordPress.PHP.DevelopmentFunctions.error_log_error_log, WordPress.PHP.DevelopmentFunctions.error_log_print_r -- Debug logging
        // Debug log
        error_log('TRSTEMP: Retrieved step ' . $step . ' data: ' . print_r($step_data, true));
        // phpcs:enable WordPress.PHP.DevelopmentFunctions.error_log_error_log, WordPress.PHP.DevelopmentFunctions.error_log_print_r
        
        return $step_data;
    }
    
    public static function get_session_data() {
        return get_option(self::$session_key, array());
    }
    
    public static function clear_session() {
        delete_option(self::$session_key);
    }
    
    public static function get_summary() {
        $data = self::get_session_data();
        
        $summary = array(
            'website_type' => $data['step_1']['website_type_name'] ?? $data['step_1']['website_type'] ?? '',
            'website_type_features' => $data['step_1']['features'] ?? array(),
            'template_id' => $data['step_3']['template_id'] ?? $data['step_2']['template_id'] ?? '',
            'template_name' => $data['step_3']['template_name'] ?? $data['step_2']['template_name'] ?? '',
            'logo' => $data['step_3']['logo'] ?? '',
            'font_pair' => $data['step_3']['font_pair'] ?? 'lato',
            'color_palette' => $data['step_3']['color_palette'] ?? 'original',
            'site_title' => $data['step_3']['site_title'] ?? $data['step_5']['site_title'] ?? get_bloginfo('name'),
            'site_tagline' => $data['step_3']['site_tagline'] ?? $data['step_5']['site_tagline'] ?? get_bloginfo('description'),
            'selected_features' => $data['step_4']['selected_features'] ?? array(),
            'import_options' => $data['step_5']['import_options'] ?? array()
        );
        
        // phpcs:disable WordPress.PHP.DevelopmentFunctions.error_log_error_log, WordPress.PHP.DevelopmentFunctions.error_log_print_r -- Debug logging
        // Debug log
        error_log('TRSTEMP: Generated summary: ' . print_r($summary, true));
        // phpcs:enable WordPress.PHP.DevelopmentFunctions.error_log_error_log, WordPress.PHP.DevelopmentFunctions.error_log_print_r
        
        return $summary;
    }
    
    private static function sanitize_data($data) {
        if (!is_array($data)) {
            return sanitize_text_field($data);
        }
        
        $sanitized = array();
        foreach ($data as $key => $value) {
            $key = sanitize_key($key);
            if (is_array($value)) {
                $sanitized[$key] = self::sanitize_data($value);
            } elseif (is_string($value)) {
                if (strpos($key, 'color') !== false) {
                    $sanitized[$key] = sanitize_hex_color($value) ?: sanitize_text_field($value);
                } elseif (strpos($key, 'url') !== false) {
                    $sanitized[$key] = esc_url_raw($value);
                } else {
                    $sanitized[$key] = sanitize_text_field($value);
                }
            } else {
                $sanitized[$key] = $value;
            }
        }
        return $sanitized;
    }
}

// AJAX handlers
// AJAX handler: Save wizard step data
add_action( 'wp_ajax_trstemp_save_step_data', function () {

    // Capability check
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_send_json_error(
            array( 'message' => __( 'Insufficient permissions', 'turbo-templates-library-for-elementor' ) ),
            403
        );
    }

    // ✅ Nonce verification (MUST before reading $_POST)
    if (
        ! isset( $_POST['nonce'] ) ||
        ! wp_verify_nonce(
            sanitize_text_field( wp_unslash( $_POST['nonce'] ) ),
            'trstemp_wizard_nonce'
        )
    ) {
        wp_send_json_error(
            array( 'message' => __( 'Invalid nonce', 'turbo-templates-library-for-elementor' ) ),
            403
        );
    }

    // Step number
    $step = isset( $_POST['step'] ) ? absint( $_POST['step'] ) : 0;

    // Safe data read
    $data = array();
    if ( isset( $_POST['data'] ) ) {
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Data sanitized after decoding
        $raw_data = wp_unslash( $_POST['data'] );

        // JSON string হলে decode
        if ( is_string( $raw_data ) ) {
            $decoded = json_decode( $raw_data, true );
            if ( json_last_error() === JSON_ERROR_NONE && is_array( $decoded ) ) {
                $data = $decoded;
            }
        } elseif ( is_array( $raw_data ) ) {
            $data = $raw_data;
        }
    }

    if ( $step <= 0 ) {
        wp_send_json_error(
            array( 'message' => __( 'Invalid step', 'turbo-templates-library-for-elementor' ) ),
            400
        );
    }

    // Save session data
    Trstemp_WizardSession::save_step_data( $step, $data );

    wp_send_json_success(
        array(
            'message' => __( 'Step data saved successfully', 'turbo-templates-library-for-elementor' ),
            'step'    => $step,
        )
    );
});

add_action('wp_ajax_trstemp_get_step_data', function() {
    // phpcs:disable WordPress.Security.NonceVerification.Missing -- Read-only session data
    // Security check
    // ✅ Nonce verification FIRST
    if (
        ! isset( $_POST['nonce'] ) ||
        ! wp_verify_nonce(
            sanitize_text_field( wp_unslash( $_POST['nonce'] ) ),
            'trstemp_wizard_nonce'
        )
    ) {
        wp_send_json_error(
            array( 'message' => __( 'Invalid nonce', 'turbo-templates-library-for-elementor' ) ),
            403
        );
    }

    // Capability check
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_send_json_error(
            array( 'message' => __( 'Insufficient permissions', 'turbo-templates-library-for-elementor' ) ),
            403
        );
    }
    
    $step = isset($_POST['step']) ? absint($_POST['step']) : 0;
    
    if ($step > 0) {
        $data = Trstemp_WizardSession::get_step_data($step);
        wp_send_json_success($data);
    } else {
        wp_send_json_error('Invalid step');
    }
    // phpcs:enable WordPress.Security.NonceVerification.Missing
});

add_action('wp_ajax_trstemp_get_wizard_summary', function() {
    // Security check
    if (!current_user_can('manage_options')) {
        wp_send_json_error('Insufficient permissions');
    }
    
    $summary = Trstemp_WizardSession::get_summary();
    wp_send_json_success($summary);
});

// Backward compatibility
