<?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);
        }

        // ── REVIEWS ─────────────────────────────────────────────────────────
        if ($type === 'reviews') {
            foreach ($stores as $store) {
                if ($store_api->is_store_local($store)) {
                    $args = [
                        'status' => 'approve',
                        'type' => 'review',
                    ];
                    $reviews = get_comments($args);
                    foreach ($reviews as $r) {
                        $results[] = [
                            'Store'         => $store->name,
                            'Review ID'     => $r->comment_ID,
                            'Product ID'    => $r->comment_post_ID,
                            'Reviewer'      => $r->comment_author,
                            'Email'         => $r->comment_author_email,
                            'Rating'        => get_comment_meta($r->comment_ID, 'rating', true),
                            'Review'        => $r->comment_content,
                            'Date'          => $r->comment_date,
                            'Status'        => wp_get_comment_status($r->comment_ID),
                        ];
                    }
                } else {
                    $remote_reviews = $fetch_all_remote($store, 'wc/v3/products/reviews');
                    foreach ($remote_reviews as $r) {
                        if (!is_array($r)) continue;
                        $results[] = [
                            'Store'         => $store->name,
                            'Review ID'     => $r['id']              ?? '',
                            'Product ID'    => $r['product_id']     ?? '',
                            'Reviewer'      => $r['reviewer']       ?? '',
                            'Email'         => $r['reviewer_email'] ?? '',
                            'Rating'        => $r['rating']         ?? '',
                            'Review'        => is_string($r['review'] ?? '') ? $r['review'] : '',
                            'Date'          => $r['date_created']   ?? '',
                            'Status'        => $r['status']         ?? '',
                        ];
                    }
                }
            }
            return new WP_REST_Response(['status' => 'success', 'data' => $results], 200);
        }

        // ── CATEGORIES ─────────────────────────────────────────────────────
        if ($type === 'categories') {
            foreach ($stores as $store) {
                if ($store_api->is_store_local($store)) {
                    $categories = get_terms(['taxonomy' => 'product_cat', 'hide_empty' => false]);
                    if (!is_wp_error($categories)) {
                        foreach ($categories as $c) {
                            $results[] = [
                                'Store'       => $store->name,
                                'Category ID' => $c->term_id,
                                'Name'        => $c->name,
                                'Slug'        => $c->slug,
                                'Description' => $c->description,
                                'Parent'      => $c->parent,
                                'Count'       => $c->count,
                            ];
                        }
                    }
                } else {
                    $remote_categories = $fetch_all_remote($store, 'wc/v3/products/categories');
                    foreach ($remote_categories as $c) {
                        if (!is_array($c)) continue;
                        $results[] = [
                            'Store'       => $store->name,
                            'Category ID' => $c['id']           ?? '',
                            'Name'        => $c['name']         ?? '',
                            'Slug'        => $c['slug']         ?? '',
                            'Description' => $c['description']  ?? '',
                            'Parent'      => $c['parent']       ?? 0,
                            'Count'       => $c['count']        ?? 0,
                        ];
                    }
                }
            }
            return new WP_REST_Response(['status' => 'success', 'data' => $results], 200);
        }

        // ── TAGS ───────────────────────────────────────────────────────────
        if ($type === 'tags') {
            foreach ($stores as $store) {
                if ($store_api->is_store_local($store)) {
                    $tags = get_terms(['taxonomy' => 'product_tag', 'hide_empty' => false]);
                    if (!is_wp_error($tags)) {
                        foreach ($tags as $t) {
                            $results[] = [
                                'Store'       => $store->name,
                                'Tag ID'      => $t->term_id,
                                'Name'        => $t->name,
                                'Slug'        => $t->slug,
                                'Description' => $t->description,
                                'Count'       => $t->count,
                            ];
                        }
                    }
                } else {
                    $remote_tags = $fetch_all_remote($store, 'wc/v3/products/tags');
                    foreach ($remote_tags as $t) {
                        if (!is_array($t)) continue;
                        $results[] = [
                            'Store'       => $store->name,
                            'Tag ID'      => $t['id']           ?? '',
                            'Name'        => $t['name']         ?? '',
                            'Slug'        => $t['slug']         ?? '',
                            'Description' => $t['description']  ?? '',
                            'Count'       => $t['count']        ?? 0,
                        ];
                    }
                }
            }
            return new WP_REST_Response(['status' => 'success', 'data' => $results], 200);
        }

        // ── CUSTOMERS ───────────────────────────────────────────────────────
        if ($type === 'customers') {
            foreach ($stores as $store) {
                if ($store_api->is_store_local($store)) {
                    $customers = get_users(['role' => 'customer']);
                    foreach ($customers as $c) {
                        $customer = new WC_Customer($c->ID);
                        $results[] = [
                            'Store'           => $store->name,
                            'Customer ID'     => $c->ID,
                            'First Name'      => $customer->get_first_name(),
                            'Last Name'       => $customer->get_last_name(),
                            'Email'           => $customer->get_email(),
                            'Orders Count'    => $customer->get_order_count(),
                            'Total Spend'     => $customer->get_total_spent(),
                            'Username'        => $c->user_login,
                            'Date Registered' => $c->user_registered,
                        ];
                    }
                } else {
                    $remote_customers = $fetch_all_remote($store, 'wc/v3/customers');
                    foreach ($remote_customers as $c) {
                        if (!is_array($c)) continue;
                        $results[] = [
                            'Store'           => $store->name,
                            'Customer ID'     => $c['id']                ?? '',
                            'First Name'      => $c['first_name']        ?? '',
                            'Last Name'       => $c['last_name']         ?? '',
                            'Email'           => $c['email']             ?? '',
                            'Orders Count'    => $c['orders_count']      ?? 0,
                            'Total Spend'     => $c['total_spend']       ?? 0,
                            'Username'        => $c['username']          ?? '',
                            'Date Registered' => $c['date_created']      ?? '',
                        ];
                    }
                }
            }
            return new WP_REST_Response(['status' => 'success', 'data' => $results], 200);
        }

        // ── COUPONS ─────────────────────────────────────────────────────────
        if ($type === 'coupons') {
            foreach ($stores as $store) {
                if ($store_api->is_store_local($store)) {
                    $coupons = get_posts([
                        'post_type'   => 'shop_coupon',
                        'post_status' => 'publish',
                        'numberposts' => -1,
                    ]);
                    foreach ($coupons as $coupon) {
                        $wc_coupon = new WC_Coupon($coupon->ID);
                        $results[] = [
                            'Store'           => $store->name,
                            'Coupon ID'       => $coupon->ID,
                            'Code'            => $wc_coupon->get_code(),
                            'Description'     => $coupon->post_excerpt,
                            'Discount Type'   => $wc_coupon->get_discount_type(),
                            'Amount'          => $wc_coupon->get_amount(),
                            'Free Shipping'   => $wc_coupon->get_free_shipping() ? 'Yes' : 'No',
                            'Usage Count'     => $wc_coupon->get_usage_count(),
                            'Usage Limit'     => $wc_coupon->get_usage_limit() ?: 'Unlimited',
                            'Expiry Date'     => $wc_coupon->get_date_expires() ? $wc_coupon->get_date_expires()->date('Y-m-d') : 'Never',
                        ];
                    }
                } else {
                    $remote_coupons = $fetch_all_remote($store, 'wc/v3/coupons');
                    foreach ($remote_coupons as $c) {
                        if (!is_array($c)) continue;
                        $results[] = [
                            'Store'           => $store->name,
                            'Coupon ID'       => $c['id']                ?? '',
                            'Code'            => $c['code']              ?? '',
                            'Description'     => $c['description']       ?? '',
                            'Discount Type'   => $c['discount_type']     ?? '',
                            'Amount'          => $c['amount']            ?? '',
                            'Free Shipping'   => isset($c['free_shipping']) && $c['free_shipping'] ? 'Yes' : 'No',
                            'Usage Count'     => $c['usage_count']       ?? 0,
                            'Usage Limit'     => $c['usage_limit']       ?? 'Unlimited',
                            'Expiry Date'     => $c['date_expires']      ?? 'Never',
                        ];
                    }
                }
            }
            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]);
    }

}
