<?php
use Automattic\WooCommerce\Utilities\OrderUtil;

/**
 * Backend Only Mode of the plugin (Order Fulfilment).
 *
 * Defines the plugin name, version, and hooks for order fulfillment
 * and inventory management from the backend.
 *
 * @link       http://www.techspawn.com
 * @since      1.2.2
 * @package    Wcmlim
 * @subpackage Wcmlim/admin
 * @author     techspawn1 <contact@techspawn.com>
 */

 include plugin_dir_path(__FILE__) . 'backend-helper/wcmlim-backend-location-functions.php';
 include plugin_dir_path(__FILE__) . 'backend-helper/wcmlim-backend-order-functions.php';
 include plugin_dir_path(__FILE__) . 'backend-helper/wcmlim-backend-shipping-functions.php';
 include plugin_dir_path(__FILE__) . 'backend-helper/wcmlim-backend-stock-functions.php';

class Wcmlim_Backend_Only_Mode
{
  public $version;

  use Wcmlim_Backend_Location_Functions;
  use Wcmlim_Backend_Order_Functions;
  use Wcmlim_Backend_Shipping_Functions;
  use Wcmlim_Backend_Stock_Functions;

  /**
   * Initialize the class and set its hooks
   */
  public function __construct()
  {
    $plugin_public = null;

    // Check if Wcmlim_Public class exists before instantiating
    if (class_exists('Wcmlim_Public')) {
      $plugin_public = new Wcmlim_Public('wcmlim', WCMLIM_VERSION);
    }

    // Check if backend-only mode is enabled
    $wcmlim_allow_only_backend = get_option('wcmlim_allow_only_backend');
    if ($wcmlim_allow_only_backend == 'on') {
      // Register frontend actions for backend-only mode
      add_action('wp_enqueue_scripts', array($this, 'wcmlim_show_address_checkout'));
      add_action('woocommerce_before_add_to_cart_button', array($this, 'wcmlim_display_location_backend_only_mode'));
    }

    add_action('woocommerce_saved_order_items', array($this, 'action_woocommerce_saved_order'), 10, 2);
    if (!is_multiloca_premium_active()) {
    add_action('woocommerce_process_shop_order_meta', [$plugin_public, 'wcmlim_maybe_reduce_stock_levels'], 10, 2);
    }

    // HPOS compatibility hooks
    add_action('woocommerce_order_item_saved', array($this, 'action_woocommerce_saved_order'), 10, 2);


    // Order fulfillment configuration
    $fulfilment_rule = get_option("wcmlim_order_fulfilment_rules");
    if ($fulfilment_rule == "nearby_instock") {
      $fulfilment_rule = "clcsadd";
    }
    
    // Set up actions based on fulfillment rule
    switch ($fulfilment_rule) {
      case "clcsadd":
        add_action('woocommerce_checkout_update_order_review', array($this, 'wcmlim_backend_mode_nearby_location_selection_shipping_address'));
        add_action('woocommerce_add_order_item_meta', array($this, 'add_order_item_meta'), 10, 3);
        break;
      
      case "shipping_loc":
        add_action('woocommerce_thankyou', array($this, 'wcmlim_fulfil_order_shipping_zones'), 10, 1);
        add_action('woocommerce_after_checkout_validation', array($this, 'wcmlim_shipping_error'), 10, 2);
        break;
      
      case "maxinvloc":
      case "locappriority":
      case "nearby_instock":
      default:
        add_action('woocommerce_thankyou', array($this, 'wcmlim_fulfil_saved_order_items'), 10, 4);
        break;
    }
    // Always add these hooks regardless of mode
    add_action('woocommerce_order_item_line_item_html', array($this, 'add_orders_multi_inventory_ui'), 10, 4);
    
    // Only add cart item name filter in admin context, not on frontend
    if (is_admin() && !wp_doing_ajax()) {
      add_filter('woocommerce_cart_item_name', [$this, 'wcmlim_cart_item_name'], 10, 3);
    }
    
    add_filter('woocommerce_hidden_order_itemmeta', [$plugin_public, 'hidden_order_itemmeta'], 50);
    
    // Stock management hooks
    if (!is_multiloca_premium_active()) {
    add_action("woocommerce_payment_complete", [$plugin_public, "wcmlim_maybe_reduce_stock_levels"]);
    add_action('woocommerce_order_status_completed', [$plugin_public, "wcmlim_maybe_reduce_stock_levels"]);
    add_action('woocommerce_order_status_processing', [$plugin_public, "wcmlim_maybe_reduce_stock_levels"]);
    add_action('woocommerce_order_status_cancelled', [$plugin_public, 'wcmlim_maybe_increase_stock_levels']);
    add_action('woocommerce_order_status_on-hold', [$plugin_public, "wcmlim_maybe_reduce_stock_levels"]);
    }
    
  }
  // Include helper files with optimized functions


  /**
   * Update total inventory data across all locations
   * 
   * @param int $product_id The product ID to update
   * @return void
   */
  public function wcmlim_update_totaldata($product_id)
  {
    if (empty($product_id)) {
      return;
    }

    // Get only linked locations for this product
    $linked_locations = wp_get_object_terms($product_id, 'locations', array('fields' => 'ids'));
    
    $total = 0;
    
    if (!empty($linked_locations)) {
      // Calculate total stock from linked locations only
      foreach ($linked_locations as $location_id) {
        $stock = get_post_meta($product_id, "wcmlim_stock_at_{$location_id}", true);
        $total += intval($stock);
      }
    } else {
      // If no locations are linked, use the original stock value or current stock
      $original_stock = get_post_meta($product_id, '_original_stock', true);
      if ($original_stock !== '') {
        $total = intval($original_stock);
      } else {
        // Fallback: get current stock value
        $total = intval(get_post_meta($product_id, '_stock', true));
      }
    }
    
    // Update product meta
    update_post_meta($product_id, '_stock', $total);
    update_post_meta($product_id, '_stock_status', ($total > 0) ? 'instock' : 'outofstock');
    
    // Clear product cache
    wc_delete_product_transients($product_id);
  }

  /**
   * Find a product in an existing array and return details
   * 
   * @param int $product_id Product ID to find
   * @param array $tmp_cart_item_exist Array to search in
   * @return array|int Found item details or 0 if not found
   */
  public function find_product_in_array($product_id, $tmp_cart_item_exist)
  {
    if (empty($tmp_cart_item_exist) || empty($product_id)) {
      return 0;
    }

    foreach ($tmp_cart_item_exist as $key => $value) {
      if ($product_id == $value['product_id']) {
        $result = array(
          "item_quantity" => $value['item_quantity'],
          "item_id" => $value['item_id']
        );
        
        // Remove found item from array to prevent duplication
        unset($tmp_cart_item_exist[$key]);
        return $result;
      }
    }
    
    return 0;
  }

  /**
   * Send notification to location manager after order fulfillment
   * 
   * @param int $term_id Location term ID
   * @param int $order_id Order ID
   * @return void
   */
  public function sendnotification_formanager($term_id, $order_id)
  {
    if (empty($term_id) || empty($order_id)) {
      return;
    }

    // Get location details
    $order = wc_get_order($order_id);
    if (!$order) {
      return;
    }

    // Get location email and manager details
    $wcmlim_emailadd = get_term_meta($term_id, 'wcmlim_email', true);
    $shop_manager = get_term_meta($term_id, 'wcmlim_shop_manager', true);
    
    // Build recipient email list
    $email_recipients = $wcmlim_emailadd;
    if (!empty($shop_manager)) {
      $author_id = $shop_manager[0];
      $author_obj = get_user_by('id', $author_id);
      if ($author_obj && !is_wp_error($author_obj)) {
        $author_email = $author_obj->user_email;
        $email_recipients = $author_email . ", " . $wcmlim_emailadd;
      }
    }
    
    // Skip if no recipients
    if (empty($email_recipients)) {
      return;
    }
    
    // Get order and location details
    $currency = get_woocommerce_currency_symbol();
    $term_data = get_term($term_id);
    $location_name = !is_wp_error($term_data) ? $term_data->name : '';
    
    // Calculate order total for this location
    $total = 0;
    $islimitenable = get_option('wcmlim_clear_cart');
    if ($islimitenable == "on") {
      $total = $order->get_total();
    } else {
      foreach ($order->get_items() as $item) {
        $item_term_id = $item->get_meta('_selectedLocTermId', true);
        if ($item_term_id == $term_id) {
          $total += $item->get_subtotal();
        }
      }
    }
    $formatted_total = $currency . number_format($total, 2, '.', '');
    
    // Build email template
    $message = $this->build_location_notification_email(
      $order_id, 
      $order, 
      $location_name, 
      $formatted_total,
      $term_id, 
      $currency
    );
    
    // Send email
    $subject = "You have received location order";
    $fromemail = get_bloginfo('admin_email');
    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
    $headers .= 'From: Order Received <' . $fromemail . '>' . "\r\n";
    
    wp_mail($email_recipients, $subject, $message, $headers);
  }
  
  /**
   * Build HTML email template for location notifications
   *
   * @param int $order_id Order ID
   * @param WC_Order $order Order object
   * @param string $location_name Location name
   * @param string $total_price Formatted total price
   * @param int $location_term_id Location term ID
   * @param string $currency Currency symbol
   * @return string HTML email content
   */
  private function build_location_notification_email($order_id, $order, $location_name, $total_price, $location_term_id, $currency)
  {
    $payment_method = (WC_HPOS_IS_ACTIVE) ? 
      $order->get_meta("_payment_method", true) : 
      get_post_meta($order_id, '_payment_method', true);
    
    $site_url = site_url();
    $order_date = $order->get_date_created();
    
    // Shipping address
    $shipping_info = [
      'name' => $order->get_billing_first_name() . ' ' . $order->get_billing_last_name(),
      'address' => $order->get_billing_address_1() . ' ' . $order->get_billing_address_2(),
      'city_state_zip' => $order->get_billing_city() . ', ' . $order->get_billing_state() . ' ' . $order->get_billing_postcode(),
      'country' => $order->get_billing_country(),
      'contact' => $order->get_billing_phone() . ', ' . $order->get_billing_email()
    ];
    
    // Start building email
    $message = '<table border="0" cellpadding="0" cellspacing="0" width="600" id="template_container" style="background-color:#ffffff;border:1px solid #dedede;border-radius:3px"><tbody>';
    
    // Header
    $message .= '<tr><td align="center" valign="top">
      <table border="0" cellpadding="0" cellspacing="0" width="100%" id="template_header" style="background-color:#96588a;color:#ffffff;border-bottom:0;font-weight:bold;line-height:100%;vertical-align:middle;font-family:&quot;Helvetica Neue&quot;,Helvetica,Roboto,Arial,sans-serif;border-radius:3px 3px 0 0">
        <tbody><tr><td id="header_wrapper" style="padding:36px 48px;display:block">
          <h1 style="font-family:&quot;Helvetica Neue&quot;,Helvetica,Roboto,Arial,sans-serif;font-size:30px;font-weight:300;line-height:150%;margin:0;text-align:left;color:#ffffff;background-color:inherit">Warehouse Received Order</h1>
        </td></tr></tbody>
      </table>
    </td></tr>';
    
    // Body intro
    $message .= '<tr><td align="center" valign="top">
      <table border="0" cellpadding="0" cellspacing="0" width="600" id="template_body"><tbody><tr><td valign="top" id="body_content" style="background-color:#ffffff">
      <table border="0" cellpadding="20" cellspacing="0" width="100%"><tbody><tr>
      <td valign="top" style="padding:48px 48px 32px">
      <div id="body_content_inner" style="color:#636363;font-family:&quot;Helvetica Neue&quot;,Helvetica,Roboto,Arial,sans-serif;font-size:14px;line-height:150%;text-align:left">
      <p style="margin:0 0 16px">Hi ' . $location_name . ',</p>
      <p style="margin:0 0 16px">Just to let you know — we have received your order ' . $order_id . ':</p>
      <p style="margin:0 0 16px">Payment Via ' . $payment_method . '.</p>
      <h2 style="color:#96588a;display:block;font-family:&quot;Helvetica Neue&quot;,Helvetica,Roboto,Arial,sans-serif;font-size:18px;font-weight:bold;line-height:130%;margin:0 0 18px;text-align:left">[Order #' . $order_id . '] (' . $order_date . ')</h2>
      <div style="margin-bottom:40px">
      <table cellspacing="0" cellpadding="6" width="100%" border="1" style="color:#636363;border:1px solid #e5e5e5;vertical-align:middle;width:100%;font-family:"Helvetica Neue",Helvetica,Roboto,Arial,sans-serif">
        <thead><tr>
          <th scope="col" style="color:#636363;border:1px solid #e5e5e5;vertical-align:middle;padding:12px;text-align:left">Product</th>
          <th scope="col" style="color:#636363;border:1px solid #e5e5e5;vertical-align:middle;padding:12px;text-align:left">Quantity</th>
          <th scope="col" style="color:#636363;border:1px solid #e5e5e5;vertical-align:middle;padding:12px;text-align:left">Price</th>
        </tr></thead>
        <tbody>';
    
    // Order items
    foreach ($order->get_items() as $item) {
      $item_term_id = $item->get_meta('_selectedLocTermId', true);
      
      if (!$item->is_type('line_item') || $item_term_id != $location_term_id) {
        continue;
      }
      
      $quantity = $item->get_quantity();
      $item_name = $item->get_name();
      $price = $currency . number_format($item->get_subtotal(), 2, '.', '');
      
      $message .= '<tr>
        <td style="color:#636363;border:1px solid #e5e5e5;padding:12px;text-align:left;vertical-align:middle;font-family:"Helvetica Neue",Helvetica,Roboto,Arial,sans-serif;word-wrap:break-word">
          ' . $item_name . '
        </td>
        <td style="color:#636363;border:1px solid #e5e5e5;padding:12px;text-align:left;vertical-align:middle;font-family:"Helvetica Neue",Helvetica,Roboto,Arial,sans-serif">
          ' . $quantity . '
        </td>
        <td style="color:#636363;border:1px solid #e5e5e5;padding:12px;text-align:left;vertical-align:middle;font-family:"Helvetica Neue",Helvetica,Roboto,Arial,sans-serif">
          <span>' . $price . '</span>
        </td>
      </tr>';
    }
    
    // Order footer
    $message .= '</tbody>
      <tfoot>
        <tr><th scope="row" colspan="2" style="color:#636363;border:1px solid #e5e5e5;vertical-align:middle;padding:12px;text-align:left">Payment Method:</th>
        <td style="color:#636363;border:1px solid #e5e5e5;vertical-align:middle;padding:12px;text-align:left">' . $payment_method . '</td></tr>
        <tr>
          <th scope="row" colspan="2" style="color:#636363;border:1px solid #e5e5e5;vertical-align:middle;padding:12px;text-align:left">Total Payment:</th>
          <td style="color:#636363;border:1px solid #e5e5e5;vertical-align:middle;padding:12px;text-align:left"><span>' . $total_price . '</span></td>
        </tr>
      </tfoot>
      </table></div>
      <p style="margin:0 0 16px">Thanks for using <a href="' . $site_url . '" target="_blank">' . $site_url . '</a>!</p>
      </div>';
    
    // Shipping address
    $message .= '<table id="addresses" cellspacing="0" cellpadding="0" border="0" style="width:100%;vertical-align:top;margin-bottom:40px;padding:0"><tbody><tr>
      <td valign="top" width="50%" style="text-align:left;font-family:"Helvetica Neue",Helvetica,Roboto,Arial,sans-serif;border:0;padding:0">
        <h2 style="color:#96588a;display:block;font-family:&quot;Helvetica Neue&quot;,Helvetica,Roboto,Arial,sans-serif;font-size:18px;font-weight:bold;line-height:130%;margin:0 0 18px;text-align:left">Shipping address</h2>
        <address style="padding:12px;color:#636363;border:1px solid #e5e5e5">
          ' . $shipping_info['name'] . '<br>' . $shipping_info['address'] . '<br>' . $shipping_info['city_state_zip'] . '<br>' . $shipping_info['country'] . '<br>' . $shipping_info['contact'] . '<br>
        </address>
      </td>
    </tr></tbody></table>';
    
    // Close tables
    $message .= '</td></tr></tbody></table></td></tr></tbody></table></td></tr></tbody></table>';
    
    return $message;
  }

  /**
   * Display selected location name in cart item
   * 
   * @param string $name Original item name
   * @param array $cart_item Cart item data
   * @param string $cart_item_key Cart item key
   * @return string Modified product name with location
   */
  function wcmlim_cart_item_name($name, $cart_item, $cart_item_key)
  {
    // Display location if set
    if (isset($cart_item['select_location']['location_name'])) {
      $location_string = __("Location :", "wcmlim");
      $name .= sprintf('<p>%s</p>', $location_string . $cart_item['select_location']['location_name']);
      return $name;
    }
    
    // If no location is set, don't modify name
    return $name;
  }
}

// Initialize the class
new Wcmlim_Backend_Only_Mode();



