<?php

if (!defined('ABSPATH')) {
    exit;
}

class ShopCentral_Export_Tools
{
    private $namespace;

    public function __construct($namespace = 'shopcentral/v1')
    {
        $this->namespace = $namespace;
        add_action('rest_api_init', [$this, 'register_routes']);
    }

    public function register_routes()
    {
        register_rest_route($this->namespace, '/api/store-manager/export', [
            'methods' => WP_REST_Server::READABLE,
            'callback' => [$this, 'handle_export'],
            'permission_callback' => [$this, 'check_permission'],
        ]);
    }

    public function check_permission()
    {
        return current_user_can('manage_options');
    }

    public function handle_export($request)
    {
        $type   = $request->get_param('type');
        $period = $request->get_param('period') ?? 'month';

        global $wpdb;
        $table     = $wpdb->prefix . 'shopcentral_stores';
        $stores    = $wpdb->get_results("SELECT * FROM $table");
        $store_api = new ShopCentral_Store_API($this->namespace);

        // Helper: build date range params for remote API
        $get_remote_date_params = function () use ($period) {
            if ($period === 'month') return ['after' => date('Y-m-01') . 'T00:00:00', 'before' => date('Y-m-t') . 'T23:59:59'];
            if ($period === 'year')  return ['after' => date('Y-01-01') . 'T00:00:00', 'before' => date('Y-12-31') . 'T23:59:59'];
            return []; // all time
        };

        // Helper: build date_after param for local wc_get_orders
        $get_local_date_args = function () use ($period) {
            if ($period === 'month') return ['date_after' => date('Y-m-01')];
            if ($period === 'year')  return ['date_after' => date('Y-01-01')];
            return [];
        };

        // Helper: fetch all pages from a remote endpoint (up to $max_pages)
        $fetch_all_remote = function ($store, $endpoint, $extra_params = [], $max_pages = 10) use ($store_api) {
            $all  = [];
            $page = 1;
            while ($page <= $max_pages) {
                $params = array_merge($extra_params, ['per_page' => 100, 'page' => $page]);
                $rows   = $store_api->get_remote_wc_data($store, $endpoint, $params);
                if (!is_array($rows) || isset($rows['code']) || empty($rows)) break;
                $all = array_merge($all, $rows);
                if (count($rows) < 100) break;
                $page++;
            }
            return $all;
        };

        $results = [];

        // ── PRODUCTS ────────────────────────────────────────────────────────
        if ($type === 'products') {
            foreach ($stores as $store) {
                if ($store_api->is_store_local($store)) {
                    $products = wc_get_products(['limit' => -1, 'status' => ['publish', 'draft']]);
                    foreach ($products as $p) {
                        $results[] = [
                            'Store'      => $store->name,
                            'Product ID' => $p->get_id(),
                            'Name'       => $p->get_name(),
                            'Type'       => $p->get_type(),
                            'Price'      => $p->get_price(),
                            'Stock'      => $p->get_stock_quantity() ?? 'N/A',
                            'Status'     => $p->get_status(),
                        ];
                    }
                } else {
                    // Paginate remote products (arrays, not objects)
                    $remote_products = $fetch_all_remote($store, 'wc/v3/products');
                    foreach ($remote_products as $p) {
                        if (!is_array($p)) continue;
                        $results[] = [
                            'Store'      => $store->name,
                            'Product ID' => $p['id']             ?? '',
                            'Name'       => $p['name']           ?? '',
                            'Type'       => $p['type']           ?? '',
                            'Price'      => $p['price']          ?? '',
                            'Stock'      => $p['stock_quantity'] ?? 'N/A',
                            'Status'     => $p['status']         ?? '',
                        ];
                    }
                }
            }
            return new WP_REST_Response(['status' => 'success', 'data' => $results], 200);
        }

        // ── ORDERS ──────────────────────────────────────────────────────────
        if ($type === 'orders') {
            $remote_date_params = $get_remote_date_params();
            $local_date_args    = $get_local_date_args();

            foreach ($stores as $store) {
                if ($store_api->is_store_local($store)) {
                    $orders = wc_get_orders(array_merge(['limit' => -1], $local_date_args));
                    foreach ($orders as $o) {
                        $results[] = [
                            'Store'          => $store->name,
                            'Order ID'       => $o->get_id(),
                            'Date'           => $o->get_date_created() ? $o->get_date_created()->date('Y-m-d H:i:s') : '',
                            'Status'         => $o->get_status(),
                            'Total'          => $o->get_total(),
                            'Currency'       => $o->get_currency(),
                            'Customer Email' => is_callable([$o, 'get_billing_email']) ? $o->get_billing_email() : '',
                            'Payment Method' => is_callable([$o, 'get_payment_method_title']) ? $o->get_payment_method_title() : '',
                        ];
                    }
                } else {
                    // Paginate remote orders (arrays, not objects)
                    $remote_orders = $fetch_all_remote($store, 'wc/v3/orders', $remote_date_params);
                    foreach ($remote_orders as $o) {
                        if (!is_array($o)) continue;
                        $results[] = [
                            'Store'          => $store->name,
                            'Order ID'       => $o['id']                       ?? '',
                            'Date'           => isset($o['date_created']) ? date('Y-m-d H:i:s', strtotime($o['date_created'])) : '',
                            'Status'         => $o['status']                   ?? '',
                            'Total'          => $o['total']                    ?? '',
                            'Currency'       => $o['currency']                 ?? '',
                            'Customer Email' => $o['billing']['email']         ?? '',
                            'Payment Method' => $o['payment_method_title']     ?? '',
                        ];
                    }
                }
            }
            return new WP_REST_Response(['status' => 'success', 'data' => $results], 200);
        }

        // ── PDF REPORT ──────────────────────────────────────────────────────
        if ($type === 'report') {
            $remote_date_params = $get_remote_date_params();
            $local_date_args    = $get_local_date_args();

            $local_currency = html_entity_decode(get_woocommerce_currency_symbol(), ENT_QUOTES | ENT_HTML5, 'UTF-8');
            $report = [
                'generated_at'            => current_time('mysql'),
                'period'                  => $period,
                'network_total_revenue'   => 0,
                'network_total_orders'    => 0,
                'network_currency_symbol' => $local_currency,
                'store_breakdown'         => [],
            ];

            foreach ($stores as $store) {
                $store_revenue   = 0;
                $store_orders    = 0;
                $currency_symbol = '$';

                if ($store_api->is_store_local($store)) {
                    $currency_symbol = html_entity_decode(get_woocommerce_currency_symbol(), ENT_QUOTES | ENT_HTML5, 'UTF-8');
                    $orders = wc_get_orders(array_merge(
                        ['limit' => -1, 'status' => ['wc-completed', 'wc-processing', 'wc-on-hold']],
                        $local_date_args
                    ));
                    foreach ($orders as $o) {
                        $store_revenue += (float) $o->get_total();
                        $store_orders++;
                    }
                } else {
                    // Fetch remote currency
                    $status_res = $store_api->get_remote_wc_data($store, 'wc/v3/system_status');
                    if (is_array($status_res) && isset($status_res['settings']['currency_symbol'])) {
                        $currency_symbol = html_entity_decode($status_res['settings']['currency_symbol'], ENT_QUOTES | ENT_HTML5, 'UTF-8');
                    }

                    // Try reports/sales first (fast path)
                    $sales_params = array_merge(['date_min' => '', 'date_max' => ''], []);
                    if ($period === 'month') { $sales_params = ['date_min' => date('Y-m-01'), 'date_max' => date('Y-m-t')]; }
                    if ($period === 'year')  { $sales_params = ['date_min' => date('Y-01-01'), 'date_max' => date('Y-12-31')]; }

                    $report_ok    = false;
                    $sales_report = $store_api->get_remote_wc_data($store, 'wc/v3/reports/sales', $sales_params);

                    if (is_array($sales_report) && !isset($sales_report['code'])) {
                        $rows = isset($sales_report['total_sales']) ? [$sales_report] : $sales_report;
                        foreach ($rows as $row) {
                            if (!is_array($row) || isset($row['code'])) continue;
                            $store_revenue += (float)($row['total_sales']  ?? 0);
                            $store_orders  += (int)  ($row['total_orders'] ?? 0);
                        }
                        if ($store_revenue > 0 || $store_orders > 0) $report_ok = true;
                    }

                    // Fallback: aggregate from raw orders
                    if (!$report_ok) {
                        $remote_orders = $fetch_all_remote($store, 'wc/v3/orders', array_merge(
                            ['status' => 'completed,processing,on-hold'],
                            $remote_date_params
                        ));
                        foreach ($remote_orders as $o) {
                            if (!is_array($o)) continue;
                            $store_revenue += (float)($o['total'] ?? 0);
                            $store_orders++;
                        }
                    }
                }

                $report['network_total_revenue'] += $store_revenue;
                $report['network_total_orders']  += $store_orders;
                $report['store_breakdown'][] = [
                    'store_name'      => $store->name,
                    'url'             => $store->url,
                    'currency_symbol' => $currency_symbol,
                    'revenue'         => round($store_revenue, 2),
                    'orders'          => $store_orders,
                    'aov'             => $store_orders > 0 ? round($store_revenue / $store_orders, 2) : 0,
                ];
            }

            return new WP_REST_Response(['status' => 'success', 'data' => $report], 200);
        }

        return new WP_Error('invalid_type', 'Invalid export type requested', ['status' => 400]);
    }

}
