<?php
/**
 * Default Numerology Result Template - Dynamic & Admin-Styled
 *
 * Variables expected:
 *   - $response (array|string)
 *   - $template (string)
 *   - $styles (array)
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

$dakidarts_styles   = isset( $styles ) && is_array( $styles ) ? $styles : get_option( 'dakidarts_numerology_style_settings', [] );
$dakidarts_template = isset( $template ) ? $template : 'default';
$dakidarts_response = isset( $response ) ? $response : [];
$dakidarts_label_map = isset( $label_map ) && is_array( $label_map ) ? $label_map : [];

// Form container styles
$dakidarts_form_style = sprintf(
    'background:%s;padding:%s;margin:%s;border-radius:%s;',
    esc_attr( $dakidarts_styles['form_bg'] ?? '#fff' ),
    esc_attr( $dakidarts_styles['form_padding'] ?? '25px' ),
    esc_attr( $dakidarts_styles['form_margin'] ?? '2rem auto' ),
    esc_attr( $dakidarts_styles['form_radius'] ?? '20px' )
);

$dakidarts_try_again_text = ! empty( $dakidarts_styles['try_again_text'] ) ? $dakidarts_styles['try_again_text'] : __( 'Calculate Another', 'dakidarts-numerology-core' );
$dakidarts_button_mode     = $dakidarts_styles['button_style_mode'] ?? 'inherit';

$dakidarts_button_inline_style = '';
if ( $dakidarts_button_mode === 'custom' ) {
    $dakidarts_button_inline_style = sprintf(
        'background:%s;color:%s;padding:%s;border:%s %s %s;border-radius:%s;display:block;margin:%s;text-align:center;',
        esc_attr( $dakidarts_styles['button_bg'] ?? '#4f46e5' ),
        esc_attr( $dakidarts_styles['button_color'] ?? '#fff' ),
        esc_attr( $dakidarts_styles['button_padding'] ?? '10px 20px' ),
        esc_attr( $dakidarts_styles['button_border_width'] ?? '1px' ),
        esc_attr( $dakidarts_styles['button_border_style'] ?? 'solid' ),
        esc_attr( $dakidarts_styles['button_border_color'] ?? '#4f46e5' ),
        esc_attr( $dakidarts_styles['button_radius'] ?? '10px' ),
        ( $dakidarts_styles['button_position'] ?? 'center' ) === 'center' ? '0 auto' :
        ( ( $dakidarts_styles['button_position'] ?? 'center' ) === 'right' ? '0 0 0 auto' : '0 0 0 0' )
    );
}

if ( ! function_exists( 'dakidarts_is_list_pro' ) ) {
    function dakidarts_is_list_pro( $value ) {
        if ( ! is_array( $value ) ) {
            return false;
        }
        return array_keys( $value ) === range( 0, count( $value ) - 1 );
    }
}

if ( ! function_exists( 'dakidarts_get_label_pro' ) ) {
    function dakidarts_get_label_pro( $key, $label_map = [] ) {
        if ( isset( $label_map[ $key ] ) ) {
            return $label_map[ $key ];
        }
        return ucwords( str_replace( [ '_', '-' ], ' ', $key ) );
    }
}

if ( ! function_exists( 'dakidarts_render_list_pro' ) ) {
    function dakidarts_render_list_pro( $items, $styles = [], $label_map = [] ) {
        if ( empty( $items ) ) {
            return '';
        }

        $all_scalars = true;
        foreach ( $items as $item ) {
            if ( is_array( $item ) ) {
                $all_scalars = false;
                break;
            }
        }

        if ( $all_scalars ) {
            $html = '<ul class="dakidarts-list" style="margin: 0 0 1rem; padding-left: 1.25rem;">';
            foreach ( $items as $item ) {
                $html .= '<li style="margin-bottom: 0.5rem; color: #4b5563;">' . esc_html( $item ) . '</li>';
            }
            $html .= '</ul>';
            return $html;
        }

        $html = '<div class="dakidarts-list-grid">';
        foreach ( $items as $item ) {
            if ( ! is_array( $item ) ) {
                $html .= '<div class="dakidarts-card-item">' . esc_html( $item ) . '</div>';
                continue;
            }

            $title = '';
            foreach ( [ 'title', 'name', 'number', 'cycle', 'label', 'age' ] as $label_key ) {
                if ( isset( $item[ $label_key ] ) ) {
                    $title = $item[ $label_key ];
                    break;
                }
            }

            $html .= '<div class="dakidarts-card-item">';
            if ( $title !== '' ) {
                $html .= '<h5 style="margin: 0 0 0.75rem; font-family: var(--space-font); font-size: 0.95rem; color: #1e1b4b; font-weight: 700;">' . esc_html( $title ) . '</h5>';
            }
            foreach ( $item as $k => $v ) {
                if ( in_array( $k, [ 'title', 'name', 'number', 'cycle', 'label', 'age' ], true ) ) {
                    continue;
                }
                $label = esc_html( dakidarts_get_label_pro( $k, $label_map ) );
                $html .= '<div class="dakidarts-row"><span class="dakidarts-row__label">' . $label . ':</span> ' . ( is_array( $v ) ? dakidarts_render_response_pro( $v, 2, $styles, $label_map ) : '<span class="dakidarts-row__value">' . esc_html( $v ) . '</span>' ) . '</div>';
            }
            $html .= '</div>';
        }
        $html .= '</div>';
        return $html;
    }
}

if ( ! function_exists( 'dakidarts_render_response_pro' ) ) {
    function dakidarts_render_response_pro( $data, $level = 0, $styles = [], $label_map = [] ) {
        if ( ! is_array( $data ) ) {
            return '<p style="margin: 0 0 1rem; color: #4b5563;">' . esc_html( $data ) . '</p>';
        }

        if ( dakidarts_is_list_pro( $data ) ) {
            return dakidarts_render_list_pro( $data, $styles, $label_map );
        }

        $html = '';
        foreach ( $data as $key => $value ) {
            if ( $key === '_api_metadata_' || $key === '_enterprise' ) {
                continue;
            }

            $heading = esc_html( dakidarts_get_label_pro( $key, $label_map ) );
            $form_bg = $styles['form_bg'] ?? '#ffffff';
            
            // Premium nested card hierarchy styles
            $bg = $level === 0
                ? '#ffffff'
                : ( $level === 1
                    ? 'rgba(249, 250, 251, 0.7)'
                    : 'rgba(243, 244, 246, 0.5)' );

            $html .= '<div class="dakidarts-card" style="background:' . esc_attr( $bg ) . '; padding: 1.5rem; margin: 1.25rem 0; border-radius: 16px; border: 1px solid rgba(0, 0, 0, 0.05);">';
            $html .= '<h4 style="margin: 0 0 0.85rem; color: ' . esc_attr( $styles['button_bg'] ?? '#4f46e5' ) . '; font-family: var(--space-font); font-size: 1.05rem; font-weight: 700;">' . $heading . '</h4>';
            
            if ( is_array( $value ) ) {
                $html .= dakidarts_render_response_pro( $value, $level + 1, $styles, $label_map );
            } else {
                $html .= '<p style="margin: 0; color: #374151; font-size: 0.95rem; line-height: 1.6;">' . esc_html( $value ) . '</p>';
            }
            $html .= '</div>';
        }
        return $html;
    }
}

// ----------------------------------------------------
// EXTRACT PRIMARY NUMBER (CELESTIAL BADGE)
// ----------------------------------------------------
$dakidarts_primary_number = null;
$dakidarts_primary_label = '';
$dakidarts_target_keys = [
    'life_path_number'          => 'Life Path',
    'destiny_number'            => 'Destiny',
    'attitude_number'           => 'Attitude',
    'personality_number'        => 'Personality',
    'heart_desire_number'       => "Heart's Desire",
    'personal_year_number'      => 'Personal Year',
    'personal_month_number'     => 'Personal Month',
    'personal_day_number'       => 'Personal Day',
    'subconscious_self_number'  => 'Subconscious Self',
    'balance_number'            => 'Balance',
    'rational_thought_number'   => 'Rational Thought',
    'birth_day_number'          => 'Birth Day',
    'ancestral_number'          => 'Ancestral Number',
];

if ( is_array( $dakidarts_response ) ) {
    // Check first level keys
    foreach ( $dakidarts_target_keys as $key => $label ) {
        if ( isset( $dakidarts_response[ $key ] ) && ( is_numeric( $dakidarts_response[ $key ] ) || is_string( $dakidarts_response[ $key ] ) ) ) {
            $dakidarts_primary_number = $dakidarts_response[ $key ];
            $dakidarts_primary_label  = $label;
            break;
        }
    }
    
    // If not found in first level, check nested
    if ( null === $dakidarts_primary_number ) {
        foreach ( $dakidarts_response as $key => $val ) {
            if ( is_array( $val ) ) {
                foreach ( $dakidarts_target_keys as $t_key => $label ) {
                    if ( isset( $val[ $t_key ] ) && ( is_numeric( $val[ $t_key ] ) || is_string( $val[ $t_key ] ) ) ) {
                        $dakidarts_primary_number = $val[ $t_key ];
                        $dakidarts_primary_label  = $label;
                        break 2;
                    }
                }
            }
        }
    }
}
?>

<div class="dakidarts-result-container" style="animation: fadeIn 0.5s ease-out; font-family: var(--outfit-font);">

    <?php if ( ! empty( $dakidarts_response ) ) : ?>
        
        <?php if ( null !== $dakidarts_primary_number ) : ?>
            <!-- Interactive Grand Celestial Badge Highlight -->
            <div class="dakidarts-badge-wrapper" style="text-align: center; margin-bottom: 2rem;">
                <div class="dakidarts-holographic-badge">
                    <span class="dakidarts-holographic-number"><?php echo esc_html( $dakidarts_primary_number ); ?></span>
                </div>
                <div class="dakidarts-badge-label" style="font-family: var(--space-font); font-weight: 700; font-size: 1.1rem; color: #1e1b4b; margin-top: 0.5rem; text-transform: uppercase; letter-spacing: 0.05em;">
                    <?php echo esc_html( $dakidarts_primary_label ); ?>
                </div>
            </div>
        <?php endif; ?>

        <!-- Recursive dynamic rendering with premium card overrides -->
        <div class="dakidarts-response-body">
            <?php echo wp_kses_post( dakidarts_render_response_pro( $dakidarts_response, 0, $dakidarts_styles, $dakidarts_label_map ) ); ?>
        </div>

    <?php else : ?>
        <p style="text-align: center; padding: 2rem; color: #6b7280;"><?php esc_html_e( 'No data returned from the API.', 'dakidarts-numerology-core' ); ?></p>
    <?php endif; ?>

    <div class="dakidarts-button-wrapper" style="margin-top: 2.5rem; text-align: center;">
        <button type="button" class="button dakidarts-try-again" <?php echo $dakidarts_button_mode === 'custom' ? 'style="' . esc_attr( $dakidarts_button_inline_style ) . '"' : ''; ?>>
            <?php echo esc_html( $dakidarts_try_again_text ); ?>
        </button>
    </div>
</div>
