/*
Theme Name: Learnify Child
Author: 
Description: Your description goes here
Version: 1.0
Template: learnify

This is the child theme for Learnify theme, generated with Generate Child Theme plugin by catchthemes.

(optional values you can add: Theme URI, Author URI, License, License URI, Tags, Text Domain)
*/

add_filter( 'woocommerce_checkout_fields', 'agregar_campos_personalizados_facturacion' );
function agregar_campos_personalizados_facturacion( $fields ) {
    
    // Campo DNI / CUIT
    $fields['billing']['billing_dni'] = array(
        'type'        => 'text',
        'label'       => __( 'DNI / CUIT', 'woocommerce' ),
        'placeholder' => __( 'Ingrese su número de documento', 'woocommerce' ),
        'required'    => true,
        'class'       => array( 'form-row-first' ), // Ocupa la mitad izquierda de la fila
        'clear'       => false,
        'priority'    => 25,
    );

    // Campo Fecha de Nacimiento
    $fields['billing']['billing_birthdate'] = array(
        'type'        => 'date', // Selector de fecha nativo del navegador
        'label'       => __( 'Fecha de Nacimiento', 'woocommerce' ),
        'required'    => true,
        'class'       => array( 'form-row-last' ), // Ocupa la mitad derecha de la fila
        'clear'       => true,
        'priority'    => 26,
    );

    return $fields;
}

add_action( 'woocommerce_checkout_update_order_meta', 'guardar_campos_personalizados_facturacion' );
function guardar_campos_personalizados_facturacion( $order_id ) {
    if ( ! empty( $_POST['billing_dni'] ) ) {
        update_post_meta( $order_id, '_billing_dni', sanitize_text_field( $_POST['billing_dni'] ) );
    }
    if ( ! empty( $_POST['billing_birthdate'] ) ) {
        update_post_meta( $order_id, '_billing_birthdate', sanitize_text_field( $_POST['billing_birthdate'] ) );
    }
}

add_action( 'woocommerce_admin_order_data_after_billing_address', 'mostrar_campos_personalizados_en_admin', 10, 1 );
function mostrar_campos_personalizados_en_admin( $order ){
    $dni = get_post_meta( $order->get_id(), '_billing_dni', true );
    $birthdate = get_post_meta( $order->get_id(), '_billing_birthdate', true );

    if ( $dni ) {
        echo '<p><strong>' . __( 'DNI / CUIT' ) . ':</strong> ' . esc_html( $dni ) . '</p>';
    }
    if ( $birthdate ) {
        // Formatea la fecha si viene en AAAA-MM-DD
        $fecha_formateada = date_i18n( get_option( 'date_format' ), strtotime( $birthdate ) );
        echo '<p><strong>' . __( 'Fecha de Nacimiento' ) . ':</strong> ' . esc_html( $fecha_formateada ) . '</p>';
    }
}