<?php

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

class ShopCentral_Customer_Intelligence
{
    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/customer-intelligence', [
            'methods' => WP_REST_Server::READABLE,
            'callback' => [$this, 'get_intelligence_data'],
            'permission_callback' => [$this, 'check_permission'],
        ]);

        register_rest_route($this->namespace, '/api/store-manager/customer-blacklist', [
            'methods' => WP_REST_Server::CREATABLE,
            'callback' => [$this, 'blacklist_customer'],
            'permission_callback' => [$this, 'check_permission'],
        ]);

        register_rest_route($this->namespace, '/api/store-manager/customer-order-history', [
            'methods' => WP_REST_Server::READABLE,
            'callback' => [$this, 'customerOrderHistory'],
            'permission_callback' => [$this, 'check_permission'],
        ]);
    }

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

    public function get_intelligence_data($request)
    {
        global $wpdb;
        $table = $wpdb->prefix . 'shopcentral_stores';
        $stores = $wpdb->get_results("SELECT * FROM $table");

        $customers_map = [];

        $after = $request->get_param('after');
        $before = $request->get_param('before');
        $date_params = [];
        if ($after) $date_params['after'] = $after;
        if ($before) $date_params['before'] = $before;

        // Fetch top customers from all stores
        foreach ($stores as $store) {
            $store_api = new ShopCentral_Store_API($this->namespace);
            
            // Use wc-analytics/customers to include guests and better LTV data
            $query_params = array_merge(['per_page' => 100], $date_params);
            $remote_customers = $store_api->get_remote_wc_data($store, "wc-analytics/customers", $query_params);
            
            // Fallback to wc/v3/customers if analytics is unavailable
            if (empty($remote_customers) || (is_array($remote_customers) && isset($remote_customers['code']) && $remote_customers['code'] == 'rest_no_route')) {
                $remote_customers = $store_api->get_remote_wc_data($store, "wc/v3/customers", $query_params);
            }

            if (is_array($remote_customers)) {
                foreach ($remote_customers as $c) {
                    if (isset($c['code']) && isset($c['message'])) continue;

                    $email = strtolower(trim($c['email'] ?? ''));
                    if (empty($email)) continue;

                    // Handle name mapping (analytics uses 'name', wc/v3 uses first/last)
                    $first_name = $c['first_name'] ?? '';
                    $last_name = $c['last_name'] ?? '';
                    if (isset($c['name']) && empty($first_name)) {
                        $parts = explode(' ', $c['name'], 2);
                        $first_name = $parts[0];
                        $last_name = $parts[1] ?? '';
                    }

                    if (!isset($customers_map[$email])) {
                        $customers_map[$email] = [
                            'email' => $email,
                            'first_name' => $first_name,
                            'last_name' => $last_name,
                            'avatar_url' => $c['avatar_url'] ?? '',
                            'stores_present' => [],
                            'total_spent' => 0.0,
                            'orders_count' => 0,
                            'currency_symbol' => '$',
                            'currency_code' => 'USD'
                        ];
                    }

                    // Handle both Analytics API (total_spend) and standard API (total_spent)
                    $spent = 0;
                    if (isset($c['total_spend'])) $spent = $c['total_spend'];
                    else if (isset($c['total_spent'])) $spent = $c['total_spent'];
                    else if (isset($c['sum_revenue'])) $spent = $c['sum_revenue'];

                    $orders = 0;
                    if (isset($c['orders_count'])) $orders = $c['orders_count'];

                    $customers_map[$email]['stores_present'][] = [
                        'store_id' => $store->id,
                        'store_name' => $store->name,
                        'customer_id' => $c['id']
                    ];

                    $customers_map[$email]['total_spent'] += (float)$spent;
                    $customers_map[$email]['orders_count'] += (int)$orders;
                    
                    // Capture currency info from local store if possible
                    if ($store_api->is_store_local($store)) {
                        $customers_map[$email]['currency_symbol'] = get_woocommerce_currency_symbol();
                        $customers_map[$email]['currency_code'] = get_woocommerce_currency();
                    }
                }
            }
        }

        // Process intelligence data
        $intelligence = array_values($customers_map);

        // Sort by total LTV (spent) descending
        usort($intelligence, function($a, $b) {
            return $b['total_spent'] <=> $a['total_spent'];
        });

        // Get global blacklist
        $blacklist = get_option('shopcentral_global_blacklist', []);

        foreach ($intelligence as &$item) {
            $item['is_blacklisted'] = in_array($item['email'], $blacklist);
            $item['multi_store'] = count($item['stores_present']) > 1;
        }

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

    public function blacklist_customer($request)
    {
        $params = $request->get_json_params();
        $email = strtolower(trim($params['email'] ?? ''));
        $action = $params['action'] ?? 'add'; // 'add' or 'remove'

        if (empty($email) || !is_email($email)) {
            return new WP_Error('invalid_email', 'Invalid email address', ['status' => 400]);
        }

        $blacklist = get_option('shopcentral_global_blacklist', []);

        if ($action === 'add') {
            if (!in_array($email, $blacklist)) {
                $blacklist[] = $email;
                update_option('shopcentral_global_blacklist', $blacklist);
            }

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

            // Attempt to delete customer from all stores using the email
            foreach ($stores as $store) {
                $customers = $store_api->get_remote_wc_data($store, "wc/v3/customers", ['email' => $email]);
                if (is_array($customers) && !empty($customers) && !isset($customers[0]->code)) {
                    foreach ($customers as $c) {
                        // Delete or set role role to None
                        $store_api->send_remote_wc_request($store, "wc/v3/customers/{$c->id}?force=true", "DELETE");
                    }
                }
            }
            
            return new WP_REST_Response(['message' => 'Customer blacklisted and removed from stores', 'blacklist' => $blacklist], 200);

        } else {
            // Remove from blacklist
            $blacklist = array_filter($blacklist, function($e) use ($email) { return $e !== $email; });
            update_option('shopcentral_global_blacklist', array_values($blacklist));
            return new WP_REST_Response(['message' => 'Customer removed from blacklist', 'blacklist' => array_values($blacklist)], 200);
        }
    }

    /**
     * Get customer order history from the active store (local or remote)
     */
    public function customerOrderHistory(WP_REST_Request $request)
    {
        global $wpdb;

        $email    = sanitize_email($request->get_param('email'));
        $per_page = max(1, (int) ($request->get_param('per_page') ?? 20));
        $page     = max(1, (int) ($request->get_param('page') ?? 1));

        if (empty($email)) {
            return new WP_Error('missing_param', 'email is required', ['status' => 400]);
        }

        $table         = $wpdb->prefix . 'shopcentral_stores';
        $current_store = $wpdb->get_row("SELECT * FROM $table WHERE is_current = 1");

        if (!$current_store) {
            return new WP_Error('no_store', 'No active store configured', ['status' => 404]);
        }

        $store_api = new ShopCentral_Store_API($this->namespace);
        $is_local  = untrailingslashit($current_store->url) === untrailingslashit(home_url());

        if ($is_local) {
            // ── LOCAL STORE ───────────────────────────────────────────────────
            $user = get_user_by('email', $email);

            $query_args = [
                'limit'    => $per_page,
                'page'     => $page,
                'orderby'  => 'date',
                'order'    => 'DESC',
                'return'   => 'objects',
            ];

            if ($user) {
                $query_args['customer_id'] = $user->ID;
            } else {
                $query_args['billing_email'] = $email;
            }

            $orders = wc_get_orders($query_args);
            $total  = wc_get_orders(array_merge($query_args, ['return' => 'ids', 'limit' => -1]));
            $total  = count($total);

            $formatted = [];
            foreach ($orders as $order) {
                $items = [];
                foreach ($order->get_items() as $item) {
                    $items[] = [
                        'product_id'   => $item->get_product_id(),
                        'name'         => $item->get_name(),
                        'quantity'     => $item->get_quantity(),
                        'subtotal'     => $item->get_subtotal(),
                    ];
                }
                $formatted[] = [
                    'id'             => $order->get_id(),
                    'status'         => $order->get_status(),
                    'date_created'   => $order->get_date_created() ? $order->get_date_created()->date('Y-m-d H:i:s') : null,
                    'total'          => $order->get_total(),
                    'currency'       => $order->get_currency(),
                    'currency_symbol'=> html_entity_decode(get_woocommerce_currency_symbol($order->get_currency()), ENT_QUOTES, 'UTF-8'),
                    'payment_method' => $order->get_payment_method_title(),
                    'items'          => $items,
                    'items_count'    => count($items),
                ];
            }

            return new WP_REST_Response([
                'data' => $formatted,
                'meta' => ['total' => $total, 'pages' => ceil($total / $per_page)]
            ], 200);

        } else {
            // ── REMOTE STORE ──────────────────────────────────────────────────
            // First resolve the customer ID on the remote store
            $remote_customers = $store_api->get_remote_wc_data($current_store, 'wc/v3/customers', ['email' => $email]);

            $customer_id = null;
            if (is_array($remote_customers) && !empty($remote_customers) && !isset($remote_customers[0]['code'])) {
                $customer_id = $remote_customers[0]['id'] ?? null;
            }

            $params = [
                'per_page' => $per_page,
                'page'     => $page,
                'orderby'  => 'date',
                'order'    => 'desc',
            ];

            if ($customer_id) {
                $params['customer'] = $customer_id;
            } else {
                $params['billing_email'] = $email;
            }

            $remote_orders = $store_api->get_remote_wc_data($current_store, 'wc/v3/orders', $params);

            if (!is_array($remote_orders) || isset($remote_orders['code'])) {
                return new WP_Error('remote_error', 'Could not fetch orders from remote store', ['status' => 502]);
            }

            $formatted = [];
            foreach ($remote_orders as $o) {
                if (isset($o['code'])) continue;
                $items = [];
                foreach ($o['line_items'] ?? [] as $li) {
                    $items[] = [
                        'product_id' => $li['product_id'] ?? null,
                        'name'       => $li['name'] ?? '',
                        'quantity'   => $li['quantity'] ?? 1,
                        'subtotal'   => $li['subtotal'] ?? 0,
                    ];
                }
                $currency        = $o['currency'] ?? 'USD';
                $currency_symbol = html_entity_decode(get_woocommerce_currency_symbol($currency), ENT_QUOTES, 'UTF-8');
                $formatted[] = [
                    'id'             => $o['id'],
                    'status'         => $o['status'],
                    'date_created'   => $o['date_created'] ?? null,
                    'total'          => $o['total'],
                    'currency'       => $currency,
                    'currency_symbol'=> $currency_symbol,
                    'payment_method' => $o['payment_method_title'] ?? '',
                    'items'          => $items,
                    'items_count'    => count($items),
                ];
            }

            return new WP_REST_Response([
                'data' => $formatted,
                'meta' => ['total' => count($formatted)]
            ], 200);
        }
    }
}
