=== MultiOrder Sync For WooCommerce ===
Contributors: kiranms1996
Tags: multiple, order, sync, link orders, woocommerce
Requires at least: 5.0
Tested up to: 7.0
Stable tag: 1.3.1
Requires PHP: 7.2
License: GPLv2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html

A WooCommerce plugin that detects repeat orders from the same customer before shipment and helps admins combine them into one fulfillment workflow.

== Description ==
MultiOrder Sync For WooCommerce is built for stores where the same customer may place multiple orders before shipment. The plugin helps admins detect those related orders, review them together, and combine them into one fulfillment workflow across a single store or a multisite network. Features include:
- Detecting repeat customer orders using customer ID, billing email, and address-based matching.
- Grouping related orders before shipment so admins can review and combine them quickly.
- Linking orders into parent and linked-order relationships for easier handling.
- Email notifications for grouped-order events.
- REST API support for fetching grouped orders and related order data.
- Admin screens for reviewing, filtering, rebuilding, and managing grouped orders.

== Installation ==
1. Upload the `emw-multiple-order-management` folder to the `/wp-content/plugins/` directory.
2. Activate the plugin through the 'Plugins' menu in WordPress.
3. Navigate to 'Muilti-Order' in the admin menu to configure settings and manage orders.

== Frequently Asked Questions ==
= Does this plugin require WooCommerce? =
Yes, WooCommerce must be installed and active.

= Can I customize the email notifications? =
Yes, the Notifications tab allows you to customize the email subject and template.

= Does it support WordPress Multisite? =
Yes, the plugin can fetch and manage orders across subsites using the REST API.

== Screenshots ==
1. Admin page showing order groups.
2. Group details popup for linking orders.
3. Settings page for configuring order statuses and criteria.

== Features ==
- Detect repeat orders placed by the same customer before shipment.
- Group and combine related WooCommerce orders using customer and address-based criteria.
- Manually link, unlink, and review grouped orders from one admin workflow.
- Reduce duplicate packing and shipment effort by handling related orders together.
- Use REST API endpoints for external CRM, ERP, and fulfillment integrations.
- Customize grouped-order notification emails.
- Support multisite workflows by working across subsites.

== REST API ==
This plugin exposes custom REST API endpoints for external access:

1. `/wp-json/emw-mom/v1/orders`  
   Fetch WooCommerce orders with optional filters.  
   **Method:** GET  
   **Header:** `X-EMW-MOM-API-Key: YOUR_API_KEY`

2. `/wp-json/emw-mom/v1/multiple-order-group/<order_id>`  
   Fetch group of orders by individual order ID.  
   **Method:** GET  
   **Header:** `X-EMW-MOM-API-Key: YOUR_API_KEY`

3. `/wp-json/emw-mom/v1/groups/<group_id>/summary`  
   Fetch summary data for a grouped-order candidate, including confidence, totals, repeated products, and shipping-destination overview.  
   **Method:** GET  
   **Header:** `X-EMW-MOM-API-Key: YOUR_API_KEY`

4. `/wp-json/emw-mom/v1/settings/detection`  
   Fetch the current time-window, confidence, and suggested-parent detection settings.  
   **Method:** GET  
   **Header:** `X-EMW-MOM-API-Key: YOUR_API_KEY`

5. `/wp-json/emw-mom/v1/settings/exclusions`  
   Fetch the current exclusion settings, including excluded statuses and excluded payment methods.  
   **Method:** GET  
   **Header:** `X-EMW-MOM-API-Key: YOUR_API_KEY`

== Developer Notes ==
You can extend the plugin using the following hooks and filters:
- `emw_mom_order_group_created`
- `emw_mom_order_linked`
- `emw_mom_api_key_validated`
- ...and more.

== Changelog ==

= 1.3.1 - 2026-05-22 =
* Fixed: HPOS (High-Performance Order Storage) compatibility by replacing all `get_post_meta()`, `update_post_meta()`, `delete_post_meta()`, and `delete_post_meta_by_key()` calls for order meta with the WooCommerce order object API (`get_meta()`, `update_meta_data()`, `delete_meta_data()`, `save()`).
* Fixed: `fetch_orders()` in order fetcher now uses `wc_get_orders()` instead of `get_posts()` with `post_type=shop_order`, ensuring HPOS compatibility.
* Fixed: Meta box registration now supports both HPOS (`woocommerce_page_wc-orders`) and legacy (`shop_order`) order edit screens.
* Fixed: `render_order_meta_box()` callback handles both `WC_Order` (HPOS) and `WP_Post` (legacy) as the callback argument.
* Fixed: `handle_order_update()` method signature now accepts the 4th `$order` parameter passed by the `woocommerce_order_status_changed` hook.
* Fixed: `rebuild_groups()` clears order sync meta using HPOS-compatible order object methods instead of `delete_post_meta_by_key()`.
* Fixed: `count()` called inside `for` loop conditions in `build_group_match_summary()` was extracted to a variable before the loop.
* Fixed: All `$table_name` SQL interpolations in handler, orders table, admin, and order fetcher now use `esc_sql()` before interpolation.
* Fixed: `$query` in `fetch_grouped_orders()` now always passes through `$wpdb->prepare()` rather than calling `get_results()` with a raw string.
* Fixed: `$count_query` and `$list_query` in `prepare_items()` now suppress `PluginCheck.Security.DirectDB.UnescapedDBParameter` with explicit `phpcs:ignore`.
* Fixed: `$group_query` in `ajax_regroup_group()` and `update_group_status()` now uses `esc_sql()` on the table name.
* Fixed: `table_has_required_columns()` in installer now uses `esc_sql()` on the table name before interpolation.
* Fixed: Inconsistent indentation in `load_dependencies()` in the loader class.
* Fixed: Missing `/* translators: */` comment on `__('%s ago')` in `group-details-popup.php`.
* Fixed: Unescaped `wp_strip_all_tags()` output inside `printf()` in `group-details-popup.php` — wrapped with `esc_html()`.
* Fixed: `get_post_meta()` call for order meta in `group-details-popup.php` template was replaced with HPOS-compatible `$order->get_meta()`.
* Fixed: `$status_label` output in `admin-page.php` is wrapped with `esc_html()` before passing to `printf()`.
* Fixed: `NonPrefixedVariableFound` PHPCS warnings across all template files by adding inline `phpcs:ignore` annotations and `@var` docblocks.
* Fixed: `WC_Order_Item_Product` type guard missing in `build_group_summary_response()` — added `instanceof` check before calling `get_product_id()`.
* Security: Escaped all table name interpolations in SQL queries with `esc_sql()` across handler, orders table, admin, and order fetcher classes.
* Security: Ensured all dynamic SQL queries pass through `$wpdb->prepare()` with no raw string passed directly to `get_results()` or `get_var()`.
* Compatibility: Confirmed tested up to WordPress 7.0.
* Compatibility: Updated readme short description to comply with the 150-character limit.

= 1.3.0 - 2026-04-06 =
* Added: Time-window grouping with configurable detection windows for recent repeat orders.
* Added: Confidence score, confidence level, match-reason metadata, and suggested parent order guidance for grouped orders.
* Added: Exclusion controls for statuses, payment methods, COD, virtual-only orders, and already linked orders.
* Added: Richer group review workflow with recommendation banner, timeline, shipment summary, export tools, regroup, unlink, and exclusion actions.
* Added: New REST API read routes for group summary, detection settings, and exclusion settings.
* Changed: Expanded Group Orders review controls across the list table, popup workflow, and audit trail.
* Fixed: Group status and exclusion flags now stay consistent across admin, AJAX, and REST flows.
* Fixed: `/orders` REST filtering now supports `group_id`, `linked_status`, `group_status`, and `confidence_level` correctly.

= 1.2.3 - 2026-03-03 =
* Added: Dedicated **Rebuild Multiple Orders** submenu page for focused rebuild workflows.
* Changed: Simplified the main **Multiple Orders** screen by moving rebuild operations to the new submenu.
* Changed: Improved admin UI/UX with clearer section hierarchy, better filter/table presentation, and modernized rebuild layout.
* Changed: Refined user-facing terminology across menus, headings, table labels, notices, and popup content for consistency.
* Improved: Multiple order troubleshooting flow with cleaner navigation between list and rebuild operations.

= 1.2.2 - 2025-12-09 =
* Added: Bulk link/unlink action for orders from the Orders list to speed up large operations.
* Added: New REST API query parameters for /orders to filter by group_id and linked_status.
* Changed: Performed full plugin integrity and compatibility checks across current WordPress and WooCommerce releases.
* Changed: Verified settings migration, metadata consistency, and renamed meta keys after the v1.2.x updates.
* Changed: Improved API key validation to return standardized JSON error responses and appropriate HTTP status codes.
* Changed: Optimized DB queries for group retrieval to reduce memory usage on large stores.
* Improved: Better PHP 8.x compatibility and tightened type declarations in key classes.
* Improved: Multisite behavior — group synchronization across subsites is more reliable and respects site-specific settings.
* Fixed: Race condition when creating parent/linked relationships during concurrent order updates (including AJAX linking scenarios that could leave stale meta).
* Fixed: Resolved an issue where linked order metadata could be lost when splitting groups.
* Fixed: Edge case in the "More" tab where recommendations could duplicate.
* Fixed: Admin notices and settings output now correctly escaped for improved security.
* Fixed: Ensured transients and caches are invalidated after settings changes.
* Deprecated: Legacy AJAX endpoints replaced by REST endpoints (legacy handlers remain for backward compatibility).
* Security: Hardened REST endpoints — stricter capability checks, input validation and sanitization.
* Tested: Confirmed REST API and AJAX endpoints (including authentication) return expected responses.
* Tested: Validated multisite order fetching and metadata persistence for linked orders.
* Tested: Verified admin upgrade routine and notices run without errors.

= 1.2.1 - 2025-08-27 =
* Added: New **"More"** tab under **Order Management Settings**.
* Added: Premium plugin showcase section featuring:
  - **Sequel247 Logistics Shipping** – Integrates WooCommerce with Sequel API for automated shipment management.
  - **Shipment Tracking** – Easily add and manage tracking info for orders. *(Coming Soon)*
  - **Post/Page Import** – Import/export content between WordPress sites. *(Coming Soon)*
  - **Activity Monitor Log** – Track and log user actions in WP dashboard. *(Coming Soon)*

= 1.2.0 - 2025-08-22 =
* Changed: Plugin name updated to **MultiOrder Sync**.
* Changed: All references to "Primary Order" have been renamed to **Parent Order**.
* Changed: All references to "Secondary Order" have been renamed to **Linked Order**.
* Changed: Updated admin labels, meta keys, API fields, and internal function names to reflect new terminology.
* Changed: Improved consistency in database schema and UI components related to order relationships.
* Fixed: Minor translation and text domain issues caused by renamed labels.

= 1.1.0 - 2025-08-18 =
* Changed: Unified `multipleorders` meta structure for all linked orders.
* Changed: Improved `ajax_link_orders` and `ajax_unlink_orders` functions to reflect accurate linked/unlinked state for each order.
* Changed: Updated `render_settings_page()` method to load settings tabs using PHP instead of JavaScript.
* Changed: Admin settings UI now loads only the active tab's content for better performance.
* Changed: Refactored tab template loading using a `switch` statement in `render_settings_page()`.
* Changed: Updated settings page navigation to use server-rendered tabs with persistent URLs.
* Changed: Improved Linked Orders meta box UI for clarity and usability.
* Deprecated: Legacy meta structure fallback for backward compatibility (to be removed in a future release).
* Fixed: Admin UI now displays correct linked order metadata across all views.

= 1.0.0 - 2025-08-13 =
* Initial release of the MultiOrder Sync plugin.
* Ability to group WooCommerce orders based on customizable criteria.
* Link grouped orders into parent/sub-order relationships.
* Admin UI for managing grouped orders.
* Settings panel for order criteria, email templates, and API key.
* REST API to:
  - Fetch all orders grouped by site: `/wp-json/emw-mom/v1/orders`
  - Get multiple order group by order ID: `/wp-json/emw-mom/v1/multiple-order-group/{order_id}`
* Multisite support for fetching orders from all network sites.
* API authentication via API key (`X-EMW-MOM-API-Key`).
* Toggleable API documentation in plugin admin settings.
