=== MX R1 Checkout ===
Contributors: mediax
Tags: woocommerce, checkout, r1, invoice, b2b, croatia, oib, hpos, blocks, webhook, tax-validation
Requires at least: 6.7
Tested up to: 7.1
Requires PHP: 7.4
WC requires at least: 10.1
WC tested up to: 11.3
Stable tag: 3.0.0
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html

Adds R1 (company) invoice fields to WooCommerce checkout (Classic + Checkout Block) with tax ID validation, HPOS compatibility, admin tools, and optional webhook/REST integrations.

== Description ==

**MX R1 Checkout** adds an optional company invoice section to WooCommerce checkout. Customers can request an R1 invoice and enter the company name, address, and tax ID.

The plugin is designed for **regional B2B e-commerce** (Croatia, Serbia, Slovenia, Bosnia and Herzegovina), where customers may need a company invoice (R1 račun) with a country-specific tax identification number (OIB, PIB, davčna številka, JIB/PDV). Tax ID validation is built in for all four countries.

Version 3 is the successor of the free "WooCommerce MX R1 račun" plugin (version 2). It is a complete rewrite with:

* Checkout Block support next to Classic Checkout
* Works with HPOS (Custom Order Tables) and with posts order storage
* Multi-country tax ID validation
* An immutable invoice snapshot on every order
* Read-only support for orders created with version 2 (no migration needed)

== Upgrading from version 2 (WooCommerce MX R1 račun) ==

Version 3 is a separate plugin (folder `mx-r1-checkout`), so it does not replace version 2 automatically.

1. Install and activate MX R1 Checkout.
2. Deactivate and delete "WooCommerce MX R1 račun".
3. Check WooCommerce → Settings → Company invoice settings.

While version 2 is still active, MX R1 Checkout stays paused and shows an admin notice, so customers never see two R1 sections.

Orders created with version 2 keep their data (`R1 račun`, `Ime tvrtke`, `Adresa tvrtke`, `OIB tvrtke`). Version 3 reads them as they are (escaping added by version 2, such as `\&quot;`, is removed for display): in the admin order screen, order list column and filter, emails, PDF invoices, REST API, webhooks, and CSV export. Nothing is migrated or changed.

Differences from version 2 worth knowing:

* Version 2 removed WooCommerce's own "Company name" billing field. Version 3 leaves WooCommerce fields untouched; if you do not need it, hide it in the page editor of the Checkout page (select the Checkout block, then set Company to hidden in its address field settings). The same setting applies to Classic Checkout; on a shop that uses only Classic Checkout with a classic theme it is under Appearance → Customize → WooCommerce → Checkout.
* Version 2 showed the R1 section only for Croatian billing addresses. Version 3 shows it for every billing country and adapts the tax ID label and validation to the country.
* Version 2 printed the R1 data on every WooCommerce PDF Invoices & Packing Slips document. Version 3 prints it on the invoice only; add other documents with the `mx_r1_pdf_allowed_document_types` filter.
* Version 2 added a second R1 block to some emails of CorvusPay orders. Version 3 shows the R1 data once in every order email, whatever the payment method.

== Main Features ==

= Checkout Fields =

* **R1 fields on checkout (Classic + Checkout Block)**:
  * "Need R1 invoice" toggle
  * Company name
  * Company address
  * Company tax ID (label and validation adapt to the billing country)
* **Conditional display**: Company fields appear only when R1 is requested
* **Conditional requiredness**: Company name, company address, and tax ID are all required when R1 is requested
* **Configurable labels** for all R1 fields
* **Optional customer profile**: signed-in customers can save company details (with explicit consent) to prefill future checkouts

= Order Data =

* **Canonical order meta**:
  * `mx_r1_need_invoice` (`'1'` / `'0'`)
  * `mx_r1_company`
  * `mx_r1_address`
  * `mx_r1_oib` — same value as `mx_r1_tax_id`, kept for compatibility with integrations
  * `mx_r1_tax_id` — preferred key: digits only for HR, RS, SI and BA; for other countries letters and digits as entered (upper case, without spaces or punctuation, e.g. `ATU12345678`)
  * `mx_r1_tax_country` — ISO country code of the tax ID
  * `mx_r1_tax_type` — type identifier (e.g. `oib`, `pib`, `tin`, `jib_pdv`)
* **Central order helper** (`MX_R1_Order_Helper`) as the single read path for current and version 2 orders

= Display Options =

* Thank You page (classic and block themes; on block themes only when WooCommerce shows the billing address to the visitor)
* View Order page (customer account)
* WooCommerce order emails (with your configured labels)
* PDF invoices (via WooCommerce PDF Invoices & Packing Slips)

Display options and admin tools work independently of the "Enable company invoice fields" switch, which only controls the checkout fields. Existing invoice orders keep showing their data when the fields are switched off.

= Admin Tools =

* **R1 column** in the orders list (legacy + HPOS)
* **R1 filter** (with / without R1, version 2 orders included)
* **R1 info box** on the order edit screen
* **Bulk CSV export** for R1 orders
* **Bulk webhook resend**

= Webhook Integration =

* Configurable webhook URL with SSRF protection (HTTPS only)
* Full or minimal payload mode
* HMAC-SHA256 request signing
* Manual resend per order and bulk resend
* **Webhook queue** (Action Scheduler, on by default):
  * Configurable retry delay and max attempts
  * Only the order ID is queued; the payload is built when the attempt runs
  * Order note on permanent failure
  * Deduplication (prevents duplicate sends)

= REST API =

* `GET /wp-json/mx/v1/r1-orders` — List R1 orders (paginated)
* `GET /wp-json/mx/v1/r1-orders/{id}` — Single order R1 data
* Supports `page`, `per_page`, `status`, `after`, `before` parameters
* Requires `manage_woocommerce` capability

= Extra Integrations =

* **WooCommerce PDF Invoices & Packing Slips**: R1 data in invoice documents
* **CorvusPay**: R1 data appears in order emails for every payment method, CorvusPay included

== Technical Details ==

= Canonical Meta Model =

All new orders use only the canonical keys listed above. Older orders may carry an obsolete `mx_r1_source` key, which is ignored and kept.

= Legacy Compatibility (version 2 orders) =

Orders created with version 2 used the meta keys `R1 račun`, `Ime tvrtke`, `Adresa tvrtke`, `OIB tvrtke`. Version 3 does not modify or migrate them; it reads them through `MX_R1_Order_Helper` (HTML entities stored by version 2 are decoded for display) and reports `source: 'legacy'` in API responses.

= Central Order Helper =

* `MX_R1_Order_Helper::is_r1( $order )` — `true` if the order requested an R1 invoice
* `MX_R1_Order_Helper::get_fields( $order )` — all R1 data
* `MX_R1_Order_Helper::meta_query_with_invoice()` / `meta_query_without_invoice()` — order queries that match `is_r1()` exactly

== Security ==

= Webhook Security =

* **SSRF protection**: Blocks localhost, private IPs, reserved ranges, raw IP addresses
* **No redirects**: HTTP redirects are treated as errors
* **HMAC-SHA256 signing**: Optional request signing with shared secret
* **Timestamp header**: `X-MX-R1-Timestamp` for replay protection

= Admin Security =

* All admin actions require `manage_woocommerce` capability
* Nonce verification on all AJAX and form submissions (checkout relies on WooCommerce's own checkout nonce check)
* Strict input sanitization and output escaping

= Data Security =

* Webhook payloads exclude internal meta and IP addresses
* Optional minimal payload mode
* Action Scheduler stores only order IDs, never customer data

== Checkout Support ==

= Classic Checkout =

* Works with the `[woocommerce_checkout]` shortcode, page builders (Elementor, Divi, Bricks, Flatsome) and themes that render the classic checkout form
* Configurable field position (top of billing, after billing, before payment) or a custom hook
* Server-side requiredness and validation when R1 is selected
* Compatible with express payment buttons that submit through WooCommerce's classic checkout
* Developers can override the detected checkout type with the `mx_r1_checkout_context` filter (`'classic'`, `'block'`, `'none'`)

= Checkout Block =

* Uses the Additional Checkout Fields API and its conditional field schema (WooCommerce 10.1+)
* Conditional field visibility and requiredness
* Server-side validation of the complete R1 payload, including direct Store API requests

== Validation ==

* The R1 checkbox reveals or hides the dependent company, address, and tax ID fields.
* Company name, company address, and tax ID are **all required when R1 is selected** in both Classic and Block Checkout.
* Per-country settings control format, length, and checksum validation; they do not control whether a tax ID is required.
* Countries without an enabled validator still require a tax ID containing at least one digit, which is stored without claiming validation.
* Tax ID validation follows the billing country:
  * **HR (Croatia) — OIB**: 11 digits, ISO 7064 MOD 11-10 checksum; the VAT form `HR12345678901` is accepted
  * **RS (Serbia) — PIB**: 9 digits, ISO 7064 MOD 11-10 checksum
  * **SI (Slovenia) — davčna številka**: 8 digits, MOD 11 checksum (remainder 10 gives check digit 0, remainder 11 is invalid; cannot start with 0)
  * **BA (Bosnia and Herzegovina) — JIB/PDV**: 12 or 13 digits, format only
  * **Other countries**: no format validation; the value must contain a digit and may hold only the letters A–Z, digits, spaces, dots, dashes and slashes (full-width characters typed with an Asian keyboard count as their plain form)
* RS, SI and BA validators accept the optional country prefix (e.g. `SI12345678`).
* Enabled validators reject unsupported characters, invalid length, and invalid checksums. For example, `abc12345678903xyz` is not accepted as a Croatian OIB.
* Error messages are in English; a Croatian translation is included.

== Installation ==

1. Upload the plugin folder to `/wp-content/plugins/` or install the ZIP via **Plugins → Add New → Upload Plugin**.
2. If "WooCommerce MX R1 račun" (version 2) is installed, deactivate it (see "Upgrading from version 2").
3. Activate **MX R1 Checkout**.
4. Go to **WooCommerce → Settings → Company invoice settings** (in Croatian: "R1 račun").
5. Test the checkout flow (Classic and/or Checkout Block).

== Frequently Asked Questions ==

= Does it work with the WooCommerce Checkout Block? =

Yes. It uses the Additional Checkout Fields API (WooCommerce 10.1 or newer).

= Does it work with page builders? =

Yes. Any checkout page that is not built with the Checkout Block (in the page, a synced pattern, or the block theme's "Page: Checkout" template) is treated as Classic Checkout, so builder checkout widgets that render the classic form show the R1 fields.

= Is HPOS supported? =

Yes. HPOS compatibility is declared and tested with both storage modes.

= Is data from version 2 migrated automatically? =

No migration is needed. Version 2 orders are read as they are and never changed.

= Can I keep version 2 active next to version 3? =

No. Version 3 pauses itself while version 2 is active, to avoid two R1 sections at checkout. Deactivate version 2 to finish the switch.

= How do I verify webhook signatures? =

If you configure a webhook secret, each request includes:

* `X-MX-R1-Timestamp`: Unix timestamp of the request
* `X-MX-R1-Signature`: `sha256=` followed by HMAC-SHA256 hash

To verify on your server:

1. Extract the timestamp and signature from the headers
2. Compute `HMAC-SHA256(timestamp + "." + raw_body, your_secret)`
3. Compare with the provided signature (use constant-time comparison)

= What happens if webhook delivery fails? =

With the **queue enabled** (the default), failed deliveries are retried with the configured delay and number of attempts. After the last attempt an order note is added, the `mx_r1_webhook_permanent_failure` action fires, and the webhook status meta is set to `failed`.

Without the queue, the webhook is sent once when the order reaches a configured status, waiting up to 5 seconds for the answer; further webhooks in the same request (for example a bulk status change) still go to the queue. A failure is logged (WooCommerce → Status → Logs, source `mx-r1-checkout`) and the next status change or a manual resend tries again. If the endpoint accepted the request but did not answer in time, the order gets a note and the webhook is not sent again automatically, to avoid duplicates.

= Does the plugin work with multisite? =

Yes. Each site in a multisite network has its own settings and orders. Saved company data belongs to the user account, which WordPress shares across the network.

= Can I customize the webhook payload? =

Choose the full or minimal payload in settings; use the `mx_r1_webhook_payload` filter (applied to both modes) for further changes. A filter result that is not an array is ignored. The payload `status` is the order status that triggered the webhook.

= How do I use the REST API? =

The REST API requires authentication with a user that has the `manage_woocommerce` capability.

**List R1 orders:**
`GET /wp-json/mx/v1/r1-orders?page=1&per_page=20&status=completed&after=2026-01-01&before=2026-02-01`

`after` is inclusive and `before` is exclusive. Dates without a time zone are read in the site time zone.

**Get single order:**
`GET /wp-json/mx/v1/r1-orders/123`

= What does the `source` field mean? =

It is derived from the stored data, not saved at checkout:

* `'v3'` — current order schema (Classic Checkout or Checkout Block)
* `'legacy'` — version 2 order read through the compatibility layer

= Which PDF documents display R1 data? =

By default only the `invoice` document of WooCommerce PDF Invoices & Packing Slips. Developers may add exact document type slugs with the `mx_r1_pdf_allowed_document_types` filter.

== Screenshots ==

1. R1 fields on Classic Checkout
2. R1 fields on the Checkout Block
3. Admin order screen with the R1 info box
4. Orders list with R1 column and filter
5. Plugin settings page

== Changelog ==

= 3.0.0 =

First public release of the rewritten plugin (successor of "WooCommerce MX R1 račun" 2.0). Compared with 2.0:

* New: Checkout Block support (WooCommerce 10.1+), with errors under each field and server-side validation.
* New: Tax ID validation for Serbia (PIB), Slovenia (davčna številka) and Bosnia and Herzegovina (JIB/PDV) next to Croatia (OIB, also in HR VAT form), switchable per country; VAT numbers of other countries are kept with their letters.
* New: The R1 section for every billing country (version 2: Croatia only).
* New: Settings tab under WooCommerce → Settings (display options, field position, texts, validation, customer profile, webhook, privacy).
* New: Optional customer profile with explicit consent, My Account editor, privacy export and erasure.
* New: Webhooks with HMAC signing, SSRF protection, background queue with retries, manual and bulk resend.
* New: REST API for R1 orders.
* New: Bulk CSV export and R1 order filter.
* New: Company invoice data in WooCommerce order personal-data export, and in order erasure when the store enables it.
* New: Plugin updates from media-x.hr.
* Changed: Works with page-builder checkouts and express payment buttons on Classic Checkout.
* Changed: The "Enable" switch now only controls checkout fields; existing orders always show their R1 data.
* Changed: Version 2 orders are read without migration, shown without the HTML entities and backslashes version 2 stored, and included in the R1 filter.
* Changed: Version 3 pauses itself while version 2 is active.
* Changed: WooCommerce's own "Company name" field is no longer removed.
* Changed: The R1 column also works with posts order storage, and R1 data shows on the "Order received" page of block themes.
* Changed: R1 data appears once in every order email, whatever the payment method (no separate CorvusPay block).
* Changed: PDF Invoices & Packing Slips: R1 data on the invoice only by default (filter `mx_r1_pdf_allowed_document_types` for packing slips and other documents).

= 2.0.0 =

* R1 checkbox and company fields on Classic Checkout
* OIB validation (length + checksum)
* Display in admin, order details, emails
* CorvusPay and PDF Invoices integration
* R1 column in orders list
* HPOS compatibility

== Upgrade Notice ==

= 3.0.0 =
New plugin replacing "WooCommerce MX R1 račun" 2.x: install it, then deactivate version 2. Existing orders keep their data without migration.

== Privacy ==

This plugin stores R1 invoice data (company name, address, tax ID) as WooCommerce order meta.

When "Remember company invoice data" is enabled, signed-in customers can use a separate convenience profile on Classic Checkout, Checkout Block, and My Account → R1 podaci. A customer must explicitly choose to save R1 details; every save choice defaults to off and saved details never automatically request an R1 invoice. Accepted on-hold, processing, and completed checkout orders can update the profile only when the customer explicitly selected profile saving. Failed, cancelled, abandoned, guest, and R1-disabled checkouts cannot.

The saved profile is only a prefill preference. It never automatically requests an R1 invoice, bypasses checkout validation, or changes an existing order. Every order keeps its immutable R1 snapshot, and all order output uses that snapshot.

**Data stored:**

* Company name
* Company address
* Tax ID (OIB, PIB, davčna številka, JIB/PDV, or other country-specific identifier)

**Personal-data export and erasure:**

* Customer profiles are included in WordPress personal-data export and erasure.
* Order R1 data is included in WooCommerce's order export. It is anonymized by WooCommerce's order erasure only when the store enables "Remove personal data from orders on request" (WooCommerce → Settings → Accounts & Privacy); otherwise it is kept with the order as part of financial records.

**Optional data sharing:**

* If configured, R1 data may be sent to external systems via webhooks
* The REST API exposes R1 data to authenticated administrators

**External update service:**

As part of WordPress plugin update checks, plugin-information requests, and the final package-URL refresh before download, the plugin sends an HTTPS `POST` request to `https://media-x.hr/wp-json/mx-license/v1/update/info`. Its JSON payload contains exactly `plugin_slug` (`mx-r1-checkout`), `version` (the installed plugin version), `site_url` (the value of `home_url()`), and `license_key` (`FREE`). These fields let the Media X service identify the plugin and site installation and return update availability, plugin information, and a current package URL. No locale, WordPress version, WooCommerce version, PHP version, order data, or customer data is included in this payload (WordPress adds its usual User-Agent header with its version and the site address to every outgoing request).

Successful update information is normally cached for 15 minutes; a failed check is also remembered for 15 minutes so an unreachable service does not slow down admin pages. WordPress may initiate checks in scheduled/background update processing or from administrator update screens. A package download forces a fresh lookup. Network errors, HTML responses, or invalid JSON result in no new update information and do not interrupt checkout. The plugin has no separate opt-out for this custom update request.

**Data retention:**

Order R1 data follows WooCommerce order retention. Guests who do not create an account never receive a profile.

**Uninstall:**

Uninstall always cancels queued webhook attempts and removes the update-check cache. If "Delete plugin data on uninstall" is enabled, plugin settings plus canonical and legacy customer-profile metadata are also removed (on multisite: the settings of the site where the plugin is deleted; saved company data of all users, as user data is shared across the network). Orders and WooCommerce customer fields are always preserved.
