=== PoPayPOS Reports for WooCommerce ===
Contributors: amitrotem
Tags: popay, woocommerce, pos, reports, sales analytics
Requires at least: 5.0
Tested up to: 6.8
Stable tag: 2.0.4
Requires PHP: 7.4
License: GPLv2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html

Complete sales analytics and reporting solution for PoPayPOS and Omni POS integration with WooCommerce.

== Description ==

**PoPayPOS Reports for WooCommerce** is a powerful analytics plugin designed specifically for businesses using PoPayPOS (Omni POS) systems with WooCommerce. Get comprehensive insights into your point-of-sale transactions with professional reports, visual analytics, and data export capabilities.

**Why Choose PoPayPOS Reports?**
✅ **100% HPOS Compatible** - Future-proof with WooCommerce High-Performance Order Storage
✅ **Real-time Analytics** - Track sales performance instantly
✅ **Professional Reports** - Export to CSV/Excel for business analysis
✅ **Visual Dashboards** - Beautiful charts and graphs
✅ **Payment Method Tracking** - Monitor all payment types
✅ **Employee Performance** - Track individual cashier sales

The plugin allows site administrators to view detailed analytics for POS orders, including:
- Comparison between POS orders and regular orders
- Daily detailed reports
- Visual graphs
- Export data to CSV/Excel
- Detailed statistics
- **Full compatibility with High-Performance Order Storage (HPOS)**

== System Requirements ==
- WordPress 5.0 or higher
- WooCommerce 5.0 or higher
- PHP 7.4 or higher

== Compatibility ==
This plugin is fully compatible with WooCommerce High-Performance Order Storage (HPOS).  
It uses the WooCommerce Data Store API instead of direct SQL queries, ensuring compatibility with future database changes.

Supported features:
- HPOS enabled
- HPOS disabled (traditional database)
- Automatic switching between systems
- Support for WooCommerce 5.0+

== Installation ==

= From WordPress Dashboard =
1. Go to **Plugins > Add New**
2. Search for "PoPayPOS Reports"
3. Click **Install Now** then **Activate**
4. Navigate to **WooCommerce > PoPayPOS Reports**

= Manual Installation =
1. Download the plugin ZIP file
2. Upload the `popaypos-reports` folder to `/wp-content/plugins/`
3. Go to **Plugins** in your WordPress admin
4. Find **PoPayPOS Reports for WooCommerce** and activate it
5. Navigate to **WooCommerce > PoPayPOS Reports**

= Requirements =
- WordPress 5.0+
- WooCommerce 5.0+  
- PHP 7.4+
- PoPayPOS/Omni POS system integration

== Usage ==
= Accessing Reports =
1. Go to the WordPress admin panel
2. Navigate to **WooCommerce > POS Reports**

= Creating a Report =
1. Select a start date and end date
2. Click **Generate Report**
3. View results in summary cards, graphs, and tables

= Exporting Data =
1. Generate a report
2. Select an export format (CSV or Excel)
3. Click **Export Report**

== Features ==
= Summary Cards =
- Number of POS orders
- Total POS order amount
- Number of regular orders
- Total regular order amount
- Total revenue
- Percentage of POS orders from all orders

= Graphs =
- Line chart comparing daily revenue
- Bar chart comparing daily order counts

= Detailed Tables =
- List of all POS orders with direct links
- Daily breakdown of orders and revenue

= Data Export =
- Export to CSV
- Export to Excel (basic)

== Data Structure ==
The plugin identifies orders with the meta field:
`order_source` = `pos`  
Orders without this field or with a different value are considered regular orders.

== Technical Architecture ==
= WooCommerce Data Store API =
Instead of direct SQL queries:
```php
$orders = wc_get_orders(array(
    'limit' => -1,
    'status' => array('completed', 'processing', 'on-hold'),
    'meta_query' => array(
        array(
            'key' => 'order_source',
            'value' => 'pos',
            'compare' => '='
        )
    )
));
```

= HPOS Detection =
```php
if (class_exists('Automattic\WooCommerce\Utilities\OrderUtil')) {
    $hpos_enabled = \Automattic\WooCommerce\Utilities\OrderUtil::custom_orders_table_usage_is_enabled();
}
```

== Customization ==
= Adding More Fields =
Edit the `get_orders_by_source` function:
```php
private function get_orders_by_source($source, $start_date, $end_date) {
    $args = array(
        'limit' => -1,
        'status' => array('completed', 'processing', 'on-hold'),
        'date_created' => $start_date . '...' . $end_date,
        'orderby' => 'date',
        'order' => 'DESC',
        'meta_query' => array(
            array(
                'key' => 'your_custom_field',
                'value' => 'your_value',
                'compare' => '='
            )
        )
    );
    return wc_get_orders($args);
}
```

= Styling =
Edit `assets/css/admin.css`.

== Troubleshooting ==
- **Plugin not in menu**: Ensure WooCommerce is active and you have `manage_woocommerce` permissions.
- **No data in reports**: Make sure orders contain `order_source` = `pos` and check the date range.
- **JavaScript errors**: Verify all assets are loading and check browser console.
- **HPOS issues**: Ensure WooCommerce is updated.

== Performance ==
- Uses WooCommerce Data Store API for efficiency
- HPOS improves performance
- Optimized queries for the active database
- Loads orders in small batches to save memory

== TODO: Performance Optimizations ==

=== Critical ===

1. **`get_employee_data()` re-fetches orders already in memory** (`class-reports.php` ~L524)
   - Caller extracts IDs from loaded order objects, then this method calls `wc_get_order()` per ID — pure N+1.
   - Fix: change signature to accept `array $orders` (objects) instead of `array $order_ids`; pass `array_merge( $all_pos_orders, $regular_orders )` from `get_reports_data()`.
   - Also batch `get_user_by()` calls: collect unique employee IDs first, then call `get_users( ['include' => $ids] )` once.

2. **`get_payment_methods_data()` fires a redundant full `wc_get_orders()` call** (`class-reports.php` ~L432)
   - Loads all orders in the date range a second time; the caller already has them. No transient cache.
   - Fix: pass already-loaded orders in, or use `return 'ids'` + `get_bulk_meta_values()` + transient (same pattern as `get_used_payment_methods()`).

3. **`filter_orders_by_payment_method()` and `filter_orders_by_user()` call `get_meta()` per order** (`class-reports.php` ~L261, ~L303)
   - Both filters iterate over all loaded orders calling `get_meta()` (up to 3 keys per order for user filter) instead of using the existing `get_bulk_meta_values()` helper.
   - Fix: bulk-fetch `popay_payment`, `assigned_employee`, `user_details`, `cashier_id` before the loop; filter using the resulting maps.

=== Important ===

4. **`get_used_users()` calls `get_user_by()` per unique employee in serial** (`class-reports.php` ~L808)
   - Mitigated by transient cache, but on cache miss fires one `SELECT` per unique employee.
   - Fix: collect all unique IDs from `assigned_employee` + `cashier_id` metas, then call `get_users( ['include' => $all_ids, 'fields' => ['ID', 'display_name']] )` once.

5. **`get_reports_data()` makes two separate `get_orders_by_source('pos')` calls** (`class-reports.php` ~L44)
   - `$pos_orders` (paginated) and `$all_pos_orders` (full) both trigger `wc_get_orders(limit:-1)`. The paginated result is just `array_slice` of the full set.
   - Fix: load `$all_pos_orders` once, then derive `$pos_orders` with `array_slice( $all_pos_orders, $offset, $per_page )`.

6. **`render_legacy_order_column()` calls `wc_get_order()` per row** (`class-order-columns.php` ~L96)
   - Loads a full WC_Order object just to read one meta value on the legacy order list screen.
   - Fix: use `get_post_meta( $order_id, 'order_source', true )` directly — this hook only fires on the legacy (non-HPOS) path so postmeta is the correct table.

== Support ==
For questions or support, contact the plugin developer.

== License ==
This plugin is licensed under the GPL v2 or later.

== Changelog ==
= 1.0.3 =
- Rename for compatibility with WordPress repository

= 1.0.1 =
- Full HPOS compatibility
- Uses WooCommerce Data Store API
- Automatic HPOS detection
- Admin interface compatibility notices
- Significant performance improvements

= 1.0.0 =
- Initial release
- Basic reports
- Visual graphs
- Data export
- Modern user interface
