<?php
/**
 * Dakidarts Numerology Core - Shortcodes (POST & AJAX)
 *
 * Registers and handles shortcodes for displaying Numerology forms/results with AJAX processing.
 *
 * @package Dakidarts_Numerology_Core
 */

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

class Dakidarts_Shortcodes {

    /**
     * Constructor.
     */
    public function __construct() {
        add_action( 'init', [ $this, 'register_shortcodes' ] );

        // AJAX handlers for calculation
        add_action( 'wp_ajax_dakidarts_numerology_calculate', [ $this, 'ajax_calculate' ] );
        add_action( 'wp_ajax_nopriv_dakidarts_numerology_calculate', [ $this, 'ajax_calculate' ] );
    }

    /**
     * Register the main shortcode.
     *
     * Example: [dakidarts_numerology endpoint="life-path"]
     */
    public function register_shortcodes() {
        add_shortcode( 'dakidarts_numerology', [ $this, 'render_shortcode' ] );
    }

    /**
     * Handle AJAX Calculation submit
     */
    public function ajax_calculate() {
        // Nonce check
        if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'dakidarts_numerology_nonce' ) ) {
            wp_send_json_error( __( 'Security check failed. Please refresh and try again.', 'dakidarts-numerology-core' ) );
        }

        $endpoint = isset( $_POST['endpoint'] ) ? sanitize_key( wp_unslash( $_POST['endpoint'] ) ) : '';
        $template = isset( $_POST['template'] ) ? sanitize_key( wp_unslash( $_POST['template'] ) ) : 'default';

        $endpoints = Dakidarts_API::get_endpoints();
        if ( ! isset( $endpoints[ $endpoint ] ) ) {
            wp_send_json_error( __( 'Invalid Numerology endpoint.', 'dakidarts-numerology-core' ) );
        }

        $params = [];
        $received_data = isset( $_POST['params'] ) && is_array( $_POST['params'] ) ? $_POST['params'] : [];

        foreach ( $endpoints[ $endpoint ]['params'] as $param ) {
            if ( isset( $received_data[ $param ] ) ) {
                $value = sanitize_text_field( wp_unslash( $received_data[ $param ] ) );

                // Cast numeric fields for endpoints that require integers
                $numeric_endpoints = ['life-path', 'karmic-lesson', 'karmic-debt'];
                if ( in_array($endpoint, $numeric_endpoints, true) && in_array($param, ['birth_year', 'birth_month', 'birth_day', 'year', 'month', 'day'], true) ) {
                    $value = (int) $value;
                }

                if ( in_array( $param, [ 'reduce', 'include_gaps', 'expanded', 'allow_masters' ], true ) ) {
                    $value = strtolower( $value );
                    $value = in_array( $value, [ 'true', 'false' ], true ) ? $value : 'false';
                }

                $params[ $param ] = $value;
            }
        }

        $response = Dakidarts_API::request( $endpoint, $params );

        if ( is_wp_error( $response ) ) {
            wp_send_json_error( $response->get_error_message() );
        }

        if ( class_exists( 'Dakidarts_Render' ) ) {
            $html = Dakidarts_Render::render_result( $response, $template, $endpoint );
            wp_send_json_success( [ 'html' => $html ] );
        }

        wp_send_json_error( __( 'Result renderer not available.', 'dakidarts-numerology-core' ) );
    }

    /**
     * Handle shortcode rendering.
     *
     * @param array $atts Shortcode attributes.
     * @return string
     */
    public function render_shortcode( $atts ) {
        $atts = shortcode_atts(
            [
                'endpoint' => 'life-path', // Default endpoint
                'template' => 'default',   // Template name
            ],
            $atts,
            'dakidarts_numerology'
        );

        $endpoint = sanitize_key( $atts['endpoint'] );
        $template = sanitize_key( $atts['template'] );

        $endpoints = Dakidarts_API::get_endpoints();
        if ( ! isset( $endpoints[ $endpoint ] ) ) {
            return '<p>' . esc_html__( 'Invalid Numerology endpoint.', 'dakidarts-numerology-core' ) . '</p>';
        }

        // Render input form with dynamic attributes
        if ( class_exists( 'Dakidarts_Render' ) ) {
            return Dakidarts_Render::render_form( $endpoint, $endpoints[ $endpoint ]['params'], $template );
        }

        return '<p>' . esc_html__( 'Form renderer not available.', 'dakidarts-numerology-core' ) . '</p>';
    }
}
