<?php
// Enqueue parent theme stylesheet
function equipo_enovathemes_child_scripts() {
    wp_enqueue_style( 'equipo_enovathemes-parent-style', get_template_directory_uri(). '/style.css' );
}
add_action( 'wp_enqueue_scripts', 'equipo_enovathemes_child_scripts' );

/* ---------------------------------------------------------
 * Custom WooCommerce Stock Status Options by Lamin
 * --------------------------------------------------------- */

// 1) Add new stock status options in product edit dropdown
add_filter('woocommerce_product_stock_status_options', function($statuses) {
    $statuses['made_to_order']   = __('Made to Order', 'woocommerce');
    $statuses['direct_delivery'] = __('Direct Delivery', 'woocommerce'); // updated label
    return $statuses;
});

// 2) Display those custom statuses on single product + shop pages
add_filter('woocommerce_get_availability_text', function($text, $product) {
    $status = $product->get_stock_status();
    switch ($status) {
        case 'made_to_order':
            $text = __('Made to Order', 'woocommerce');
            break;
        case 'direct_delivery':
            $text = __('Direct Delivery', 'woocommerce'); // updated label
            break;
    }
    return $text;
}, 10, 2);

// 3) Optional: add custom CSS class to the stock text (for styling)
add_filter('woocommerce_get_availability_class', function($class, $product) {
    $status = $product->get_stock_status();
    if ($status === 'made_to_order')   { $class = 'stock made-to-order'; }
    if ($status === 'direct_delivery') { $class = 'stock direct-delivery'; }
    return $class;
}, 10, 2);

/* 4) Make custom statuses behave like "in stock" everywhere (front + admin) */
add_filter('woocommerce_product_is_in_stock', function ($in_stock, $product) {
    if ($product instanceof WC_Product) {
        $status = $product->get_stock_status();
        if (in_array($status, ['made_to_order','direct_delivery'], true)) {
            return true;
        }
    }
    return $in_stock;
}, 10, 2);

/* 5) Variable parents: if Woo computed "outofstock" but any child has a custom status,
      surface that custom status for the parent row instead of "Out of stock". */
add_filter('woocommerce_product_get_stock_status', function ($status, $product) {
    if ($product instanceof WC_Product_Variable && $status === 'outofstock') {
        foreach ($product->get_children() as $child_id) {
            $child = wc_get_product($child_id);
            if (!$child) { continue; }
            $child_status = $child->get_stock_status();
            if (in_array($child_status, ['made_to_order','direct_delivery','onbackorder'], true)) {
                return $child_status; // lets admin/product list show the custom label
            }
        }
    }
    return $status;
}, 10, 2);

/* Keep variations themselves "in stock" when set to the custom statuses */
add_filter('woocommerce_product_variation_get_stock_status', function ($status, $product) {
    if ($product instanceof WC_Product_Variation) {
        if (in_array($status, ['made_to_order','direct_delivery'], true)) {
            return $status; // keep the custom key; purchasability handled above
        }
    }
    return $status;
}, 10, 2);


/**
 * SIMPLE products: replace price with
 *   - big: "£##.## inc VAT"
 *   - small: "£##.## excluding VAT"
 *
 * VARIABLE products:
 *   - keep Woo's default min–max range at the top
 *   - when a variation is selected, the price block near the button
 *     shows BOTH: "£##.## inc VAT" and "£##.## excluding VAT"
 */
add_action('wp', function () {
    if (! function_exists('WC')) return;

    // SIMPLE products -> remove Woo’s default price and output our two-line block
    add_action('woocommerce_single_product_summary', 'lam_maybe_remove_default_price', 9);
    add_action('woocommerce_single_product_summary', 'lam_output_simple_price_block', 10);

    // VARIABLE products -> enhance the variation price HTML to include inc/ex VAT
    add_filter('woocommerce_available_variation', 'lam_variation_price_html_with_vat', 10, 3);

    // Styles
    add_action('wp_head', function () {
        echo '<style>
          .lam-price-block{margin:0 0 1rem}
          .lam-price-inc{display:block;font-size:1.75rem;line-height:1.2;font-weight:700}
          .lam-price-ex{display:block;font-size:.95rem;opacity:.9;margin-top:.2rem}
          /* Variation price block near the button */
          .single_variation .lam-var-price .lam-price-inc{display:block;font-weight:700;font-size:1.6rem;line-height:1.2}
          .single_variation .lam-var-price .lam-price-ex{display:block;font-size:.95rem;opacity:.9;margin-top:.2rem}

          /* POA button base style */
          .lam-poa-button{display:inline-block;padding:.7rem 1.1rem;border-radius:8px;font-weight:600}

          /* ===== Variation swatch selection highlight ===== */
          .lam-swatch-selected{
              border: 5px solid #000F47 !important;
              box-shadow: 0 0 0 3px rgba(0,0,0,0.2) !important;
              border-radius: 6px !important;
              transition: all .15s ease-in-out;
              position: relative;
              z-index: 1;
          }

          /* Common plugin classes */
          .variable-items-wrapper .variable-item.selected,
          .variations_form .variable-item.selected,
          .variations_form .variable-item.active,
          .woo-variation-items-wrapper .variable-item.selected,
          .swatch.selected,
          .swatch.is-selected {
              border: 5px solid #000F47 !important;
              border-radius: 6px !important;
              box-shadow: 0 0 0 3px rgba(0,0,0,0.2) !important;
              transition: all .15s ease-in-out;
          }
        </style>';
    });

    // JS: normalize "selected" state across swatch systems
    add_action('wp_footer', function () {
        ?>
        <script>
        (function($){
          function lamMarkSelected(){
            $('.lam-swatch-selected').removeClass('lam-swatch-selected');
            $('.variable-items-wrapper .variable-item.selected, .variable-items-wrapper .variable-item[aria-pressed="true"]').addClass('lam-swatch-selected');
            $('.swatch.selected, .swatch.is-selected').addClass('lam-swatch-selected');
            $('.variations input[type="radio"]:checked').each(function(){
              var id = $(this).attr('id');
              if(id){ $('label[for="'+id+'"]').addClass('lam-swatch-selected'); }
            });
            $('.variations select').each(function(){
              var name = $(this).attr('name');
              var val  = $(this).val();
              if(name && val){
                $('[data-attribute_name="'+name+'"] .variable-item').each(function(){
                  var v = $(this).attr('data-value');
                  if(v && v.toString().toLowerCase() === val.toString().toLowerCase()){
                    $(this).addClass('lam-swatch-selected');
                  }
                });
              }
            });
          }
          $(document).ready(lamMarkSelected);
          $(document).on('click change', '.variable-items-wrapper .variable-item, .swatch, .variations input, .variations select', function(){
            setTimeout(lamMarkSelected, 10);
          }).on('found_variation reset_data', 'form.variations_form', function(){
            setTimeout(lamMarkSelected, 10);
          });
        })(jQuery);
        </script>
        <?php
    });
});

/** Remove default price only for SIMPLE products */
function lam_maybe_remove_default_price() {
    if (! is_product()) return;
    global $product;
    if ($product instanceof WC_Product && $product->is_type('simple')) {
        remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_price', 10);
    }
}

/** SIMPLE products: output the two-line inc/ex VAT block under the title (only if price > 0) */
function lam_output_simple_price_block() {
    if (! is_product()) return;
    global $product;
    if (! ($product instanceof WC_Product) || ! $product->is_type('simple')) return;

    $price = (float) $product->get_price();
    if ($price <= 0) return;

    $inc = wc_get_price_including_tax($product, ['price' => $price]);
    $ex  = wc_get_price_excluding_tax($product, ['price' => $price]);

    echo '<div class="lam-price-block" itemprop="offers" itemscope itemtype="https://schema.org/Offer">';
    echo '  <span class="lam-price-inc">'. wc_price($inc) .' inc VAT</span>';
    echo '  <span class="lam-price-ex">'. wc_price($ex) .' excluding VAT</span>';
    echo '</div>';
}

/**
 * VARIABLE products: when a variation is selected, replace the price HTML
 * (the blue price near the button) with both inc and excluding VAT.
 * Keeps the min–max range at the top untouched.
 * If the selected variation is zero-priced, show POA instead (handled here).
 */
function lam_variation_price_html_with_vat($data, $product, $variation) {
    if (! $variation instanceof WC_Product_Variation) return $data;
    $price = (float) $variation->get_price();

    if ($price <= 0) {
        $data['price_html'] = '<div class="lam-var-price">'
                            .   '<a class="button lam-poa-button" href="'. esc_url(home_url('/contact-us/')) .'">POA</a>'
                            . '</div>';
        return $data;
    }

    $inc = wc_get_price_including_tax($variation, ['price' => $price]);
    $ex  = wc_get_price_excluding_tax($variation, ['price' => $price]);

    $inc_html = wc_price($inc) . ' inc VAT';
    $ex_html  = wc_price($ex)  . ' excluding VAT';

    $data['price_html'] = '<div class="lam-var-price">'
                        .   '<span class="lam-price-inc">'. $inc_html .'</span>'
                        .   '<span class="lam-price-ex">'. $ex_html .'</span>'
                        . '</div>';
    return $data;
}


/* ============================================
   POA (Price on Application) for price = 0
   ============================================ */

function lam_poa_product_is_zero(WC_Product $product): bool {
    if ($product->is_type('variable')) {
        $prices = $product->get_variation_prices(false);
        if (empty($prices['price'])) return true;
        $max = max($prices['price']);
        return (float)$max <= 0;
    }
    return (float)$product->get_price() <= 0;
}

add_filter('woocommerce_is_purchasable', function($purchasable, $product) {
    if ($product instanceof WC_Product && (float)$product->get_price() <= 0) {
        return false;
    }
    return $purchasable;
}, 10, 2);

add_action('woocommerce_single_product_summary', function () {
    if (! is_product()) return;
    global $product;
    if (! $product instanceof WC_Product) return;

    if (lam_poa_product_is_zero($product)) {
        remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30);
        add_action('woocommerce_single_product_summary', function () {
            echo '<div class="lam-poa-wrap" style="margin:1rem 0 0;">
                    <a class="button lam-poa-button" href="'. esc_url(home_url('/contact-us/')) .'">POA</a>
                  </div>';
        }, 30);
        return;
    }

    if ($product->is_type('variable')) {
        add_action('wp_footer', function () {
            $contact = esc_url(home_url('/contact-us/'));
            ?>
            <script>
            (function($){
              $(document).on('found_variation', 'form.variations_form', function(e, v){
                if(v && typeof v.display_price !== 'undefined' && parseFloat(v.display_price) <= 0){
                  $('.single_variation_wrap .woocommerce-variation-add-to-cart').hide();
                  if (!$('.single_variation_wrap .lam-poa-under').length){
                    $('.single_variation_wrap').append(
                      '<div class="lam-poa-under" style="margin-top:10px;">' +
                        '<a class="button lam-poa-button" href="<?php echo $contact; ?>">POA</a>' +
                      '</div>'
                    );
                  }
                  $('.lam-poa-under').show();
                } else {
                  $('.lam-poa-under').hide();
                  $('.single_variation_wrap .woocommerce-variation-add-to-cart').show();
                }
              }).on('reset_data', 'form.variations_form', function(){
                $('.lam-poa-under').hide();
                $('.single_variation_wrap .woocommerce-variation-add-to-cart').show();
              });
            })(jQuery);
            </script>
            <?php
        });
    }
}, 1);

add_filter('woocommerce_loop_add_to_cart_link', function($html, $product, $args) {
    if ($product instanceof WC_Product && lam_poa_product_is_zero($product)) {
        $url = esc_url(home_url('/contact-us/'));
        $classes = isset($args['class']) ? esc_attr($args['class']) : 'button';
        return '<a href="'. $url .'" class="'. $classes .' lam-poa-button">POA</a>';
    }
    return $html;
}, 10, 3);

add_filter('woocommerce_get_price_html', function($price_html, $product) {
    if ($product instanceof WC_Product) {
        if (lam_poa_product_is_zero($product)) {
            return '<span class="price lam-poa-price">POA</span>';
        }
    }
    return $price_html;
}, 10, 2);


/* =========================================================
   PURCHASE ORDER (PO) ACCOUNT ROLE + CHECKOUT FLOW
   ========================================================= */

/** Helper: is current user a PO Account? */
function lam_is_po_user(): bool {
    if ( ! is_user_logged_in() ) return false;
    $user = wp_get_current_user();
    return in_array( 'po_account', (array) $user->roles, true );
}

/** Ensure the "PO Account" role exists (runs every init; safe & idempotent) */
add_action('init', function () {
    if ( ! get_role('po_account') ) {
        add_role('po_account', 'PO Account', array('read' => true));
    }
});

/** Register the Purchase Order gateway */
add_filter('woocommerce_payment_gateways', function($methods){
    $methods[] = 'WC_Gateway_Lam_PO';
    return $methods;
});

if ( ! class_exists('WC_Gateway_Lam_PO') ) {
    class WC_Gateway_Lam_PO extends WC_Payment_Gateway {
        public function __construct() {
            $this->id                 = 'lam_po';
            $this->icon               = '';
            $this->has_fields         = true; // render PO Number input
            $this->method_title       = __('Purchase Order (PO)', 'woocommerce');
            $this->method_description = __('Allow approved customers (PO Account role) to place orders on account using a PO Number.', 'woocommerce');
            $this->title              = __('Purchase Order', 'woocommerce');
            $this->description        = __('Enter your company PO Number. Your order will be placed on account for manual processing.', 'woocommerce');

            $this->init_form_fields();
            $this->init_settings();
            $this->enabled     = $this->get_option('enabled', 'yes');
            $this->order_status = 'on-hold';

            add_action('woocommerce_update_options_payment_gateways_' . $this->id, array($this, 'process_admin_options'));
        }

        public function init_form_fields() {
            $this->form_fields = array(
                'enabled' => array(
                    'title'   => __('Enable/Disable', 'woocommerce'),
                    'type'    = > 'checkbox',
                    'label'   => __('Enable Purchase Order gateway', 'woocommerce'),
                    'default' => 'yes',
                ),
            );
        }

        /** Show PO Number field */
        public function payment_fields() {
            echo wpautop( wp_kses_post( $this->description ) );
            ?>
            <p class="form-row form-row-wide">
                <label for="lam_po_number">
                    <?php esc_html_e('PO Number', 'woocommerce'); ?>
                    <abbr class="required" title="required">*</abbr>
                </label>
                <input type="text" class="input-text" name="lam_po_number" id="lam_po_number"
                    value="<?php echo isset($_POST['lam_po_number']) ? esc_attr(wp_unslash($_POST['lam_po_number'])) : ''; ?>" />
            </p>
            <?php
        }

        /** Require PO Number */
        public function validate_fields() {
            if ( empty($_POST['lam_po_number']) ) {
                wc_add_notice( __('Please enter your PO Number.', 'woocommerce'), 'error' );
                return false;
            }
            return true;
        }

        /** No real payment; put order on-hold, save PO number */
        public function process_payment( $order_id ) {
            $order = wc_get_order( $order_id );

            if ( ! empty($_POST['lam_po_number']) ) {
                $po = sanitize_text_field( wp_unslash($_POST['lam_po_number']) );
                $order->update_meta_data('_lam_po_number', $po);
                $order->add_order_note('PO Number: ' . $po);
            }

            $order->update_status( apply_filters('lam_po_order_status', 'on-hold'), __('Awaiting PO processing', 'woocommerce') );
            wc_reduce_stock_levels( $order_id );
            WC()->cart->empty_cart();

            return array(
                'result'   => 'success',
                'redirect' => $this->get_return_url( $order ),
            );
        }
    }
}

/** Show PO gateway only to PO users; keep other gateways for everyone else */
add_filter('woocommerce_available_payment_gateways', function($gateways){
    if ( is_admin() ) return $gateways;

    $is_po = lam_is_po_user();

    // Hide PO gateway for non-PO users
    if ( isset($gateways['lam_po']) && ! $is_po ) {
        unset($gateways['lam_po']);
    }

    // PO users still see other gateways too (they can choose PO or pay normally)
    return $gateways;
});

/** Enforce login for PO flow (safety) */
add_action('template_redirect', function(){
    if ( is_checkout() && ! is_user_logged_in() && isset($_REQUEST['payment_method']) && $_REQUEST['payment_method'] === 'lam_po' ) {
        wc_add_notice( __('Please log in to use a Purchase Order.'), 'error' );
        wp_safe_redirect( wc_get_page_permalink( 'myaccount' ) );
        exit;
    }
});

/** Admin order screen: show PO Number clearly (bold + styled) */
add_action('woocommerce_admin_order_data_after_billing_address', function($order){
    $po = $order->get_meta('_lam_po_number');
    if ( $po ) {
        echo '<p style="margin-top:8px;">
                <strong style="font-size:13px; color:#000;">' . esc_html__('PO Number', 'woocommerce') . ':</strong>
                <span style="font-weight:700; font-size:14px; color:#000F47;"> ' . esc_html($po) . '</span>
              </p>';
    }
});

/** Include PO Number in customer/admin emails */
add_filter('woocommerce_email_order_meta_fields', function($fields, $sent_to_admin, $order){
    $po = $order->get_meta('_lam_po_number');
    if ( $po ) {
        $fields['lam_po_number'] = array(
            'label' => __('PO Number', 'woocommerce'),
            'value' => $po,
        );
    }
    return $fields;
}, 10, 3);

/** Optional: make PO Number visible in the order preview panel */
add_filter('woocommerce_admin_order_preview_get_order_details', function($data, $order){
    $po = $order->get_meta('_lam_po_number');
    if ($po) {
        $data['data']['po_number'] = $po;
    }
    return $data;
}, 10, 2);


/* =======================================
   ALWAYS SHOW 2 DECIMAL PLACES
   ======================================= */
add_filter('wc_price_args', function($args){
    $args['decimals'] = 2; // e.g. £1.70 instead of £1.7
    return $args;
});


/* =======================================
   FBT (Frequently Bought Together) decimals fix
   Keeps totals at 2 decimals even when the widget writes its own HTML via JS
   ======================================= */
add_action('wp_footer', function () {
    if ( ! is_product() ) return;
    ?>
    <script>
    (function($){
      function formatTwoDecimals(el){
        var txt = $(el).text();
        var m = txt.replace(/,/g,'').match(/^\s*([^0-9\-+]*?)\s*([\-+]?\d+(?:\.\d+)?)/);
        if(!m) return;
        var cur = m[1] || '';
        var num = parseFloat(m[2]);
        if(isNaN(num)) return;
        var after = txt.slice(m[0].length);
        $(el).text(cur + num.toFixed(2) + after);
      }

      function fixFbtDecimals(ctx){
        var $els = $(ctx).find(
          '.yith-wfbt-total .price, .yith-wfbt-price, ' +
          '.woobt-total .price, .woobt-total-price, .woobt-price, ' +
          '.wpc-fbt-total .price, .wpc-fbt-price'
        );
        $els.each(function(){ formatTwoDecimals(this); });
      }

      $(document).ready(function(){
        fixFbtDecimals(document);
        var boxSel = '.yith-wfbt-section, .woobt-wrap, .wpc-fbt';
        $(document).on('change click', boxSel+' input, '+boxSel+' select', function(){
          setTimeout(function(){ fixFbtDecimals(document); }, 60);
        });
        var mo = new MutationObserver(function(){ fixFbtDecimals(document); });
        mo.observe(document.body, {subtree:true, childList:true});
      });
    })(jQuery);
    </script>
    <?php
});
