<?php
/*
Plugin Name: MRW WooCommerce PK
Plugin URI: https://proyectokamila.com
Description: Plugin personalizado para agregar MRW como método de envío en WooCommerce.
Version: 1.0
Author: ProyectoKamila
Author URI: https://proyectokamila.com
*/

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Salir si se accede directamente
}


function mrw_shipping_init() {
    if ( ! class_exists( 'WooCommerce' ) ) {
        add_action( 'admin_notices', function() {
            echo '<div class="error"><p>' . __('MRW WooCommerce Shipping requires WooCommerce to be activated to work.', 'mrw_shipping') . '</p></div>';
        } );
        return;
    }
  

    // Añade MRW como método de envío
    function add_mrw_shipping_method( $methods ) {
       
        $methods['mrw_shipping'] = 'WC_MRW_Shipping_Method';
        $methods['mrw_shipping_home'] = 'WC_MRW_Shipping_Method_Home';
        
        return $methods;
    }
    add_filter( 'woocommerce_shipping_methods', 'add_mrw_shipping_method' );
    class WC_MRW_Shipping_Method_Office extends WC_Shipping_Method {
        public function __construct() {
            $this->id                 = 'mrw_shipping';
            $this->method_title       = __( 'MRW', 'mrw_shipping' );
            $this->method_description = __( 'Custom Shipping Method for MRW', 'mrw_shipping' ); 

           

            $this->enabled            = $this->get_option( 'enabled' );
            $this->title              = $this->get_option( 'title' );
            $this->price=   $this->get_option('mrwprice');
            $this->pricedelivery=   $this->get_option('mrwdeliveryprice');
        }
    }
    // Define la clase WC_MRW_Shipping_Method
    class WC_MRW_Shipping_Method_Home  extends WC_Shipping_Method {
        public function __construct() {
            $this->id                 = 'mrw_shipping';
            $this->method_title       = __( 'MRW', 'mrw_shipping' );
            $this->method_description = __( 'Custom Shipping Method for MRW', 'mrw_shipping' ); 

           

            $this->enabled            = $this->get_option( 'enabled' );
            $this->title              = $this->get_option( 'title' );
            $this->price=   $this->get_option('mrwprice');
            $this->pricedelivery=   $this->get_option('mrwdeliveryprice');
            
     
        // Save settings in admin if you have any defined
        add_action( 'woocommerce_update_options_shipping_' . $this->id, array( $this, 'process_admin_options' ) );
        }

        public function is_available( $package ) {
            WC()->session->set( 'fee_adicional_added', false );
            $weight = 0;
            foreach ( $package['contents'] as $item_id => $values ) {
                $_product = $values['data'];
                $weight = $weight + $_product->get_weight() * $values['quantity'];
            }

            $weight = wc_get_weight( $weight, 'kg' );
            
            if ( $weight > 80 ) {
                return false;
            }
           
    add_action( 'woocommerce_after_checkout_billing_form', 'add_mrw_office_field' );
    // add_action( 'woocommerce_update_options_shipping_', 'add_mrw_office_field' );
            return true;
        }

        public function calculate_shipping( $package = [] ) {
            $rate = [
                'id' => $this->id,
                'label' => $this->title,
                'cost' => 90,  // Puedes ajustar el costo de envío aquí
            ];
            $this->add_rate( $rate );
       
        }


        
    }
    

    // Añade el campo de oficina de MRW en la página de pago
function add_mrw_office_field( $checkout ) {
    echo '<div id="mrw_offices_sends" >';
    echo '<div id="mrw_office_type";"><h2>' . __('Tipos de envio') . '</h2>';

    woocommerce_form_field( 'mrw_shipping_type', array(
        'type'          => 'select',
        'class'         => array( 'mrw-shipping-type-field-class form-row-wide' ),
        'label'         => __( 'Tipo de envío' ),
        'options'       => array(
            'seleccione' => __( 'Seleccione una opción' ),
            '0' => __( 'Ninguno' ),
            '1' => __( 'MRW a agencia' ),
            '2' => __( 'MRW a domicilio' ),
            '3' => __( 'MRW a agencia cobro destino' ),
        
        ),
        'required'      => true,
        'onchange'      => 'pagoOnChange(this);', // Agregar evento onchange para llamar a la función JavaScript
        //'css'          => 'display: none;', // Agregar estilo CSS para ocultar el campo
    ), 'seleccione', $checkout->get_value( 'mrw_shipping_type' ) ); // Establecer "Seleccione una opción" como opción predeterminada

    echo '</div>';

    echo '<div id="mrw_office_field" style="display: none ;" >';
    // Desactivar la verificación de SSL
    $args = array(
        'sslverify' => false
    );

    // Obtener datos desde la API de MRW
    $api_url = 'https://api.mrwve.com/maps/buscar_agencia.php?id=*&id=*';
    $response = wp_remote_get( $api_url, $args );

    if ( is_wp_error( $response ) ) {
        echo __('Error al obtener los datos de MRW');
        return;
    }

    $body = wp_remote_retrieve_body( $response );
    $data = json_decode( $body );

    // Obtener opciones de estados
    $state_options = array();
    if ( ! empty( $data->estado_2 ) ) {
        foreach ( $data->estado_2 as $estado ) {
            $state_options[ $estado->ID_ESTADO ] = $estado->ESTADO;
        }
    }
     if ( ! empty( $data->agencias ) ) {
        $options = array();
        foreach ( $data->agencias as $agencia ) {
            $options[ $agencia->CODIGO ] = $agencia->NOMBRE;
        }
     }
    

       

    // Agregar campo de selección del estado
    woocommerce_form_field( 'mrw_state', array(
        'type'          => 'select',
        'class'         => array( 'mrw-state-field-class form-row-wide' ),
        'label'         => __( 'Estado' ),
        'options'       => $state_options,
        'required'      => true,
        'onchange'      => 'updateMRWOffices(this.value);',
        'css'         => 'display:none;',
    ), $checkout->get_value( 'mrw_state' ) );
// Obtener todas las agencias
    $all_offices = array();
    if ( ! empty( $data->agencias ) ) {
        foreach ( $data->agencias as $agencia ) {
            $all_offices[ $agencia->ID_ESTADO ][] = $agencia;
        }
    }

    // Convertir el array de agencias a formato JSON para utilizar en JavaScript
    $all_offices_json = json_encode( $all_offices );



    // Agregar campo de selección de la oficina
    woocommerce_form_field( 'mrw_office', array(
        'type'          => 'select',
        'class'         => array( 'mrw-office-field-class form-row-wide' ),
        'label'         => __( 'Selecciona una oficina de MRW' ),
        'options'       => $options,
        'required'      => true,
    ), $checkout->get_value( 'mrw_office' ) );
    echo '</div>';
    echo '<div id="mrw_office_field_venezuela" style="display: none ;" >';
    $venezuela_routes = array(
        'Amazonas ' => 'Amazonas MRW - Amazonas',
        'Apure' => 'Apure MRW - Apure',
        'Aragua' => 'Aragua MRW - Aragua',
        'Barcelona' => 'Barcelona MRW - Barcelona',
        'Barinas' => 'Barinas MRW - Barinas',
        'Bolívar' => 'Bolívar MRW - Bolívar',
        'Carabobo' => 'Carabobo MRW - Carabobo',
        'Caracas' => 'Caracas MRW - Caracas',
        'Cojedes' => 'Cojedes MRW - Cojedes',
        'Delta Amacuro' => 'Delta Amacuro MRW - Delta Amacuro',
        'Falcón' => 'Falcón MRW - Falcón',
        'Guárico' => 'Guárico MRW - Guárico',
        'La Guaira' => 'La Guaira MRW - La Guaira',
        'Lara' => 'Lara MRW - Lara',
        'Mérida' => 'Mérida MRW - Mérida',
        'Miranda' => 'Miranda MRW - Miranda',
        'Monagas' => 'Monagas MRW - Monagas',
        'Nueva Esparta' => 'Nueva Esparta MRW - Nueva Esparta',
        'Portuguesa' => 'Portuguesa MRW - Portuguesa',
        'Sucre' => 'Sucre MRW - Sucre',
        'Táchira' => 'Táchira MRW - Táchira',
        'Trujillo' => 'Trujillo MRW - Trujillo',
        'Yaracuy' => 'Yaracuy MRW - Yaracuy',
        'Zulia' => 'Zulia MRW - Zulia',

        // Agrega aquí todas las rutas que desees mostrar en el campo de selección
    );
    
    woocommerce_form_field( 'venezuela_delivery_route', array(
        'type'          => 'select',
        'class'         => array( 'venezuela-delivery-route-field-class form-row-wide' ),
        'label'         => __( 'Ruta de entrega' ),
        'options'       => $venezuela_routes,
        'required'      => true,
    ), $checkout->get_value( 'venezuela_delivery_route' ) );
    echo '</div>';
    // Agregar el script JavaScript
    // Agregar el script JavaScript
    ?>
    
 <script>

			jQuery(document).ready(function() {
				jQuery("#mrw_shipping_type").change(function() {
					if(jQuery(this).val() == "1") {
						jQuery("#mrw_office_field").show();
                        jQuery("#mrw_office_field_venezuela").hide();
					} else if(jQuery(this).val() == "2") {
						jQuery("#mrw_office_field").hide();
                        jQuery("#mrw_office_field_venezuela").show();
					}
                    
                    var fee_adicional = jQuery(this).val();
                    jQuery.ajax({
                        type: 'POST',
                        url: wc_checkout_params.ajax_url,
                        data: {
                            'action': 'actualizar_fee_adicional',
                            'fee_adicional': fee_adicional
                        },
                        success: function (response) {
                            jQuery('body').trigger('update_checkout');
                        }
                    });
                    //  .then(result => location.reload());
          
				});
			});
		


 function updateMRWOffices(stateId) {
        var allOffices = <?php echo $all_offices_json; ?>;
        var offices = allOffices[stateId] || [];

        var officeSelect = document.getElementById('mrw_office');

        // Limpiar las opciones actuales
        officeSelect.innerHTML = '';

        // Agregar las nuevas opciones
        offices.forEach(function(office) {
            var option = document.createElement('option');
            option.value = office.CODIGO;
            option.text = office.NOMBRE;
            officeSelect.appendChild(option);
        });

        // Mostrar el campo de selección de la oficina
        officeSelect.style.display = offices.length > 0 ? 'block' : 'none';
    }

    document.addEventListener('DOMContentLoaded', function() {
        var stateSelect = document.getElementById('mrw_state');

        stateSelect.addEventListener('change', function() {
            updateMRWOffices(this.value);
        });

        // Obtener el estado seleccionado al cargar la página
        var initialSelectedState = stateSelect.value;

        // Mostrar las agencias correspondientes al estado seleccionado inicialmente
        updateMRWOffices(initialSelectedState);
    });

//     function toggleMRWOfficeField(value) {

//         if (value=="office"){
//            office = document.getElementById("mrw_office_field");
//            office.style.display = "block";

//            venezuela = document.getElementById("mrw_office_field_venezuela");
//            venezuela.style.display = "none";

//       }else{

//         office = document.getElementById("mrw_office_field");
//            office.style.display = "none";

//            venezuela = document.getElementById("mrw_office_field_venezuela");
//            venezuela.style.display = "block";
//       }
// }

       
    </script>
    <?php
    echo '</div>';
}

//add_action( 'woocommerce_after_checkout_billing_form', 'add_mrw_office_field' );







    // Valida si el campo de oficina de MRW está seteado
    function validate_mrw_office_field( ) {
        if ( ! $_POST['mrw_office'] )
            wc_add_notice( __( 'Please enter your MRW office.' ), 'error' );
    }
    add_action( 'woocommerce_checkout_process', 'validate_mrw_office_field' );

    // Actualiza el pedido con el campo de oficina de MRW
    function save_mrw_office_field( $order_id ) {
        if ( ! empty( $_POST['mrw_office'] ) ) {
            update_post_meta( $order_id, 'MRW Office', sanitize_text_field( $_POST['mrw_office'] ) );
        }
    }
    add_action( 'woocommerce_checkout_update_order_meta', 'save_mrw_office_field' );
}
add_action( 'woocommerce_after_checkout_billing_form', 'add_mrw_office_field' );
add_action( 'plugins_loaded', 'mrw_shipping_init' );
// Agregar campo de Cédula a la dirección de envío
add_filter( 'woocommerce_checkout_fields', 'agregar_cedula_direccion_envio' );
function agregar_cedula_direccion_envio( $fields ) {
    // exit($fields);
    $fields['billing']['shipping_cedula'] = array(
        'label'       => __( 'Cédula o RIF', 'woocommerce' ),
        'required'    => true,
        'class'       => array( 'form-row-wide' ),
        'clear'       => true,
        'priority'    => 70,
    );
    return $fields;
}


// add_action( 'woocommerce_cart_calculate_fees', 'agregar_cargo_adicional' );

// function agregar_cargo_adicional( $cart ) {
//     $cargo = 50; // La cantidad adicional que se agregará al total general
//     $cart->add_fee( 'Envio por Oficina', $cargo ); // Agregar el cargo adicional al total del carrito
   
//********************************************************************************************************* */

// Agregar el campo de fee adicional como radio buttons
// add_action( 'woocommerce_review_order_after_order_total', 'agregar_campo_fee_adicional' );


function agregar_campo_fee_adicional() {
    $pasa=false;
    if ( ! WC()->session->get( 'fee_adicional_added' ) ) {
      $pasa=true;
    }
    elseif ( WC()->session->get( 'fee_adicional_added' )==false ) {
        $pasa=true;
    }
    if($pasa){
        WC()->session->set( 'fee_adicional_added', true );
        $fee_adicional = WC()->session->get( 'fee_adicional' );
        $options = array(
            '0' => 'Ningun metodo de envio',
            '1' => 'MRW agencia cobro destino',
            '2' => 'MRW agencia',
            '3' => 'MRW a domicilio',
        );

        woocommerce_form_field( 'fee_adicional', array(
            'type'          => 'radio',
            'class'         => array( 'form-row-wide' ),
            'label'         => 'Seleccione un metodo de envio',
            'options'       => $options,
            'default'       => '0',
            'required'      => true,
        ), $fee_adicional );
    }
    else
    {
        $pasa=false;
    }
        ?>
        // <script>
        //     jQuery(document).ready(function($) {
        //         $('input[name=fee_adicional]').on('change', function() {
         
        //         });
        //     });
        // </script>
        <?php
    
}

// Agregar el fee adicional al total del pedido
add_action( 'woocommerce_cart_calculate_fees', 'agregar_fee_adicional_al_total' );

function agregar_fee_adicional_al_total( $cart ) {
    $fee_adicional = 0;
    $selected_option = WC()->session->get( 'fee_adicional' );
    if ( $selected_option ) {
        $fee_adicional = floatval( $selected_option );
    }
    $cart->add_fee( 'Fee adicional', $fee_adicional );
}

// Función para actualizar el fee adicional mediante Ajax
add_action( 'wp_ajax_actualizar_fee_adicional', 'actualizar_fee_adicional' );
add_action( 'wp_ajax_nopriv_actualizar_fee_adicional', 'actualizar_fee_adicional' );

function actualizar_fee_adicional() {

    $shipping= 0;
switch ($_POST['fee_adicional']) {
    case '0':
      $pre=0;
        break;
        case '1':
            $pre=0;
              break;
              case '2':
                $pre=80;
                  break;
                  case '1':
                    $pre=50;
                      break;
    }
    $fee_adicional = floatval( $pre );


$indice = 0;


    if ( $fee_adicional >= 0 ) {
        if($fee_adicional == 50){
            //Domicilio
            $indice = 1;
            $shipping = mostrar_total_peso_y_precio_productos($indice);
            WC()->session->set( 'fee_adicional', $shipping );
            echo 'success';
        }else if($fee_adicional == 80){
            //Agencia
            $indice = 2;
            $shipping = mostrar_total_peso_y_precio_productos($indice);
            WC()->session->set( 'fee_adicional', $shipping );
            echo 'success';
        }else if ($fee_adicional == 0){
            WC()->session->set( 'fee_adicional', $fee_adicional );
        }
        
    } else {
        echo 'error';
    }
    wp_die();
}

// Validar el campo de fee adicional
add_action( 'woocommerce_checkout_process', 'validar_campo_fee_adicional' );

function validar_campo_fee_adicional() {
    if ( isset( $_POST['fee_adicional'] ) && ! empty( $_POST['fee_adicional'] ) ) {
        $fee_adicional = floatval( $_POST['fee_adicional'] );
        if ( $fee_adicional < 0 ) {
            wc_add_notice( 'Por favor, ingrese un valor válido para el fee adicional.', 'error' );
        } else {
            WC()->session->set( 'fee_adicional', $fee_adicional );
        }
      //  WC()->session->__unset( 'fee_adicional' ); // Eliminar completamente la variable de sesión
    }
}

// Eliminar el campo de cargo adicional por defecto
add_filter( 'woocommerce_checkout_fields', 'eliminar_campo_cargo_adicional' );

function eliminar_campo_cargo_adicional( $fields ) {
    unset( $fields['billing']['cargo_adicional'] );
    return $fields;
}

//ccss de radius

function agregar_estilos() {
    wp_register_style( 'mrw-plugin-estilos', plugins_url( 'mrw.css', __FILE__  ) );
    wp_enqueue_style( 'mrw-plugin-estilos' );
}
add_action( 'wp_enqueue_scripts', 'agregar_estilos' );

/************************************************************************************************* */

add_action( 'woocommerce_review_order_before_cart_contents', 'mostrar_total_peso_y_precio_productos' );

function mostrar_total_peso_y_precio_productos($indice) {
    global $woocommerce;
    
    // Obtener los productos del carrito
    $productos = $woocommerce->cart->get_cart();
    
    // Inicializar variables para el total del peso y precio
    $total_peso = 0;
    $total_precio = 0;
    
    // Recorrer los productos del carrito
    foreach( $productos as $producto ) {
        
        // Obtener el peso y precio del producto
        $peso = floatval( get_post_meta( $producto['product_id'], '_weight', true ) );
        $precio = floatval( $producto['data']->get_price() );
        
        // Sumar el peso y precio al total
        $total_peso += $peso * $producto['quantity'];
        $total_precio += $precio * $producto['quantity'];
    }
    
     //echo '<p>Total del peso de los productos: ' . $total_peso . ' kg</p>';

    $total = 0;
    $envio = 0;
//domicilio
    if ($indice == 1 ){
    
        $envio = (2.6 * 1.16) * $total_peso;

    $total =($total_precio * 0.01 )+ $envio;
    return $total;
    //Agencia
    } else if ($indice == 2){

        $envio = (1.3 * 1.16) * $total_peso;


    $total =($total_precio * 0.01 )+ $envio;
    return $total;    
}
    //return $total;

    //echo '<p> datos </p>'. $indice;
    // Mostrar el total del peso y precio
    /*echo '<p>Total del peso de los productos: ' . $total_peso . ' kg</p>';
    echo '<p>Total del precio de los productos: $' . $total_precio . '</p>';
    */
}
add_action( 'woocommerce_thankyou', 'borrar_fee_adicional_de_session' );

function borrar_fee_adicional_de_session( $order_id ) {
    // Borrar la variable de sesión 'fee_adicional'
    WC()->session->set( 'fee_adicional_added', null );
    WC()->session->set( 'fee_adicional', null );

    // Mostrar peso en el carrito
add_action( 'woocommerce_cart_totals_before_shipping', 'mostrar_peso_en_carrito' );
function mostrar_peso_en_carrito() {
    global $woocommerce;
    $peso_total = 0;

    foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $cart_item ) {
        $peso_total += floatval( $cart_item['data']->get_weight() ) * $cart_item['quantity'];
    }

    if ( $peso_total > 0 ) {
        echo '<tr class="peso-carrito"><th>' . __( 'Peso', 'tudominio' ) . '</th><td>' . wc_format_weight( $peso_total ) . '</td></tr>';
    }
}

// Mostrar peso en la página de finalización de compra (checkout)
add_action( 'woocommerce_review_order_before_shipping', 'mostrar_peso_en_checkout' );
function mostrar_peso_en_checkout() {
    global $woocommerce;
    $peso_total = 0;

    foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $cart_item ) {
        $peso_total += floatval( $cart_item['data']->get_weight() ) * $cart_item['quantity'];
    }

    if ( $peso_total > 0 ) {
        echo '<tr class="peso-checkout"><th>' . __( 'Peso', 'tudominio' ) . '</th><td>' . wc_format_weight( $peso_total ) . '</td></tr>';
    }
}
}

?>
