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

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

// Ensure styles are always an array and pull admin settings if empty
$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'] ?? '15px' ),
    esc_attr( $dakidarts_styles['form_margin'] ?? '10px auto' ),
    esc_attr( $dakidarts_styles['button_radius'] ?? '8px' )
);

// -------------------------
// Button texts
// -------------------------
$dakidarts_calculate_text = ! empty( $dakidarts_styles['calculate_text'] ) ? $dakidarts_styles['calculate_text'] : __( 'Calculate', 'dakidarts-numerology-core' );
$dakidarts_try_again_text = ! empty( $dakidarts_styles['try_again_text'] ) ? $dakidarts_styles['try_again_text'] : __( 'Try Again', 'dakidarts-numerology-core' );

// -------------------------
// Button style mode
// -------------------------
$dakidarts_button_mode = $dakidarts_styles['button_style_mode'] ?? 'inherit';

// -------------------------
// Button inline styles
// -------------------------
$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'] ?? '#0073aa' ),
        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'] ?? '#0073aa' ),
        esc_attr( $dakidarts_styles['button_radius'] ?? '4px' ),
        ( $dakidarts_styles['button_position'] ?? 'center' ) === 'center' ? '0 auto' :
        ( ( $dakidarts_styles['button_position'] ?? 'center' ) === 'right' ? '0 0 0 auto' : '0 0 0 0' )
    );
}

/**
 * Recursive function to render API response as nested cards
 */
function dakidarts_is_list( $value ) {
    if ( ! is_array( $value ) ) {
        return false;
    }
    return array_keys( $value ) === range( 0, count( $value ) - 1 );
}

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

function dakidarts_render_list( $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">';
        foreach ( $items as $item ) {
            $html .= '<li>' . 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' ] as $label_key ) {
            if ( isset( $item[ $label_key ] ) ) {
                $title = $item[ $label_key ];
                break;
            }
        }

        $html .= '<div class="dakidarts-card-item">';
        if ( $title !== '' ) {
            $html .= '<h5>' . esc_html( $title ) . '</h5>';
        }
        foreach ( $item as $k => $v ) {
            if ( in_array( $k, [ 'title', 'name', 'number', 'cycle', 'label' ], true ) ) {
                continue;
            }
            $label = esc_html( dakidarts_get_label( $k, $label_map ) );
            $html .= '<div class="dakidarts-row"><span class="dakidarts-row__label">' . $label . ':</span> ' . ( is_array( $v ) ? dakidarts_render_response( $v, 2, $styles, $label_map ) : '<span class="dakidarts-row__value">' . esc_html( $v ) . '</span>' ) . '</div>';
        }
        $html .= '</div>';
    }
    $html .= '</div>';
    return $html;
}

function dakidarts_render_response( $data, $level = 0, $styles = [], $label_map = [] ) {
    if ( ! is_array( $data ) ) {
        return '<p>' . esc_html( $data ) . '</p>';
    }

    if ( dakidarts_is_list( $data ) ) {
        return dakidarts_render_list( $data, $styles, $label_map );
    }

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

        $heading = esc_html( dakidarts_get_label( $key, $label_map ) );

        $form_bg = $styles['form_bg'] ?? '';
        $bg = $level === 0
            ? ( $form_bg !== '' ? $form_bg : '#fefefe' )
            : ( $level === 1
                ? ( $form_bg !== '' ? dakidarts_adjust_brightness( $form_bg, -10 ) : '#f9f9f9' )
                : ( $form_bg !== '' ? dakidarts_adjust_brightness( $form_bg, -20 ) : '#efefef' ) );

        $html .= '<div class="dakidarts-card" style="background:' . esc_attr( $bg ) . ';padding:12px 15px;margin:10px 0;border-radius:' . esc_attr( $styles['button_radius'] ?? '6px' ) . ';box-shadow:0 2px 6px rgba(0,0,0,0.05);">';
        $html .= '<h4 style="margin:0 0 8px;color:' . esc_attr( $styles['button_bg'] ?? '#0073aa' ) . ';font-size:16px;">' . $heading . '</h4>';
        if ( is_array( $value ) ) {
            $html .= dakidarts_render_response( $value, $level + 1, $styles, $label_map );
        } else {
            $html .= '<p style="margin:0;color:#333;">' . esc_html( $value ) . '</p>';
        }
        $html .= '</div>';
    }
    return $html;
}

/**
 * Helper to adjust hex color brightness
 */
function dakidarts_adjust_brightness( $hex, $steps ) {
    $steps = max( -255, min( 255, $steps ) );
    $hex   = str_replace( '#', '', $hex );
    if ( strlen( $hex ) === 3 ) {
        $hex = str_repeat( $hex[0], 2 ) . str_repeat( $hex[1], 2 ) . str_repeat( $hex[2], 2 );
    }
    $r = max( 0, min( 255, hexdec( substr( $hex, 0, 2 ) ) + $steps ) );
    $g = max( 0, min( 255, hexdec( substr( $hex, 2, 2 ) ) + $steps ) );
    $b = max( 0, min( 255, hexdec( substr( $hex, 4, 2 ) ) + $steps ) );
    return '#' . str_pad( dechex( $r ), 2, '0', STR_PAD_LEFT ) . str_pad( dechex( $g ), 2, '0', STR_PAD_LEFT ) . str_pad( dechex( $b ), 2, '0', STR_PAD_LEFT );
}
?>

<div class="dakidarts-result dakidarts-result-<?php echo esc_attr( $dakidarts_template ); ?>" style="<?php echo esc_attr( $dakidarts_form_style ); ?>">

    <?php if ( ! empty( $dakidarts_response ) ) : ?>
        <?php echo wp_kses_post( dakidarts_render_response( $dakidarts_response, 0, $dakidarts_styles, $dakidarts_label_map ) ); ?>
    <?php else : ?>
        <p><?php esc_html_e( 'No data returned from the API.', 'dakidarts-numerology-core' ); ?></p>
    <?php endif; ?>

    <div class="dakidarts-button-wrapper">
        <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>

<style>
.dakidarts-result { font-family: inherit; color: #333; line-height:1.6; }
.dakidarts-result p { margin-bottom:6px; }
.dakidarts-result h4 { font-weight:600; }
.dakidarts-card p { margin:0; }
.dakidarts-list { margin: 0; padding-left: 18px; }
.dakidarts-list li { margin-bottom: 6px; }
.dakidarts-list-grid { display: grid; gap: 10px; }
.dakidarts-card-item { background: rgba(255,255,255,0.7); border-radius: 8px; padding: 10px 12px; border: 1px solid rgba(0,0,0,0.05); }
.dakidarts-card-item h5 { margin: 0 0 6px; font-size: 14px; color: #111827; }
.dakidarts-row { font-size: 13px; margin-bottom: 4px; }
.dakidarts-row__label { font-weight: 600; color: #374151; }
.dakidarts-row__value { color: #111827; }
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const tryAgainBtn = document.querySelector('.dakidarts-try-again');
    if (tryAgainBtn) {
        tryAgainBtn.addEventListener('click', function(e) {
            e.preventDefault();
            window.location.href = window.location.href.split('?')[0]; // clean reload
        });
    }
});
</script>
