<?php
/**
 * GGM Commerce Customer Resources
 *
 * MCP Resources for exposing customer data to AI assistants
 * Resources are read-only data sources
 *
 * @package GGM_Commerce
 * @since 1.0.0
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery
// phpcs:disable WordPress.DB.DirectDatabaseQuery.NoCaching
// phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter

class GGM_Commerce_Customer_Resources {

    /**
     * MCP Server instance
     * @var GGM_Commerce_MCP_Server
     */
    private $server;

    /**
     * Constructor
     *
     * @param GGM_Commerce_MCP_Server $server MCP server instance
     */
    public function __construct($server) {
        $this->server = $server;
        $this->register_resources();
    }

    /**
     * Register all customer resources
     */
    private function register_resources() {
        // All customers
        $this->server->register_resource(
            'customer://list',
            'Customers List',
            'List of all customers',
            [$this, 'get_customers_list']
        );

        // Single customer by email
        $this->server->register_resource(
            'customer://{email}',
            'Customer Details',
            'Complete customer information including addresses and order history',
            [$this, 'get_customer']
        );

        // Customer addresses
        $this->server->register_resource(
            'customer://{email}/addresses',
            'Customer Addresses',
            'All addresses for a specific customer',
            [$this, 'get_customer_addresses']
        );

        // Customer statistics
        $this->server->register_resource(
            'customer://statistics',
            'Customer Statistics',
            'Customer analytics and statistics',
            [$this, 'get_customer_statistics']
        );
    }

    /**
     * Get list of all customers
     *
     * @param array $params URI parameters
     * @return array Customers list data
     */
    public function get_customers_list($params = []) {
        global $wpdb;

        $customers = $wpdb->get_results(
            "SELECT
                id,
                email,
                first_name,
                last_name,
                phone,
                total_orders,
                total_spent,
                created_at,
                last_order_date
            FROM {$wpdb->prefix}ggmc_customers
            ORDER BY last_order_date DESC"
        );

        // Format data
        foreach ($customers as &$customer) {
            $customer->id = (int) $customer->id;
            $customer->total_orders = (int) $customer->total_orders;
            $customer->total_spent = (float) $customer->total_spent;
        }

        return [
            'customers' => $customers,
            'count' => count($customers),
            'timestamp' => current_time('mysql')
        ];
    }

    /**
     * Get single customer details
     *
     * @param array $params URI parameters (expects 'email')
     * @return array Customer data
     */
    public function get_customer($params) {
        if (!isset($params['email'])) {
            return ['error' => 'Customer email is required'];
        }

        $email = sanitize_email($params['email']);

        if (!is_email($email)) {
            return ['error' => 'Invalid email address'];
        }

        global $wpdb;

        // Get customer data
        $customer = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM {$wpdb->prefix}ggmc_customers WHERE email = %s",
            $email
        ));

        if (!$customer) {
            return ['error' => 'Customer not found'];
        }

        // Get customer addresses
        $addresses = $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM {$wpdb->prefix}ggmc_customer_addresses WHERE customer_id = %d",
            $customer->id
        ));

        // Get customer orders
        $orders = $wpdb->get_results($wpdb->prepare(
            "SELECT
                id,
                order_number,
                total_amount,
                status,
                payment_status,
                created_at
            FROM {$wpdb->prefix}ggmc_orders
            WHERE customer_email = %s
            ORDER BY created_at DESC",
            $email
        ));

        // Format data
        $customer->id = (int) $customer->id;
        $customer->total_orders = (int) $customer->total_orders;
        $customer->total_spent = (float) $customer->total_spent;
        $customer->addresses = $addresses;
        $customer->recent_orders = $orders;

        return [
            'customer' => $customer,
            'timestamp' => current_time('mysql')
        ];
    }

    /**
     * Get customer addresses
     *
     * @param array $params URI parameters (expects 'email')
     * @return array Customer addresses data
     */
    public function get_customer_addresses($params) {
        if (!isset($params['email'])) {
            return ['error' => 'Customer email is required'];
        }

        $email = sanitize_email($params['email']);

        if (!is_email($email)) {
            return ['error' => 'Invalid email address'];
        }

        global $wpdb;

        // Get customer ID
        $customer_id = $wpdb->get_var($wpdb->prepare(
            "SELECT id FROM {$wpdb->prefix}ggmc_customers WHERE email = %s",
            $email
        ));

        if (!$customer_id) {
            return ['error' => 'Customer not found'];
        }

        // Get addresses
        $addresses = $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM {$wpdb->prefix}ggmc_customer_addresses WHERE customer_id = %d",
            $customer_id
        ));

        return [
            'customer_email' => $email,
            'addresses' => $addresses,
            'count' => count($addresses),
            'timestamp' => current_time('mysql')
        ];
    }

    /**
     * Get customer statistics
     *
     * @param array $params URI parameters
     * @return array Customer statistics
     */
    public function get_customer_statistics($params = []) {
        global $wpdb;

        // Total customers
        $total_customers = $wpdb->get_var(
            "SELECT COUNT(*) FROM {$wpdb->prefix}ggmc_customers"
        );

        // New customers (last 30 days)
        $new_customers = $wpdb->get_var(
            "SELECT COUNT(*) FROM {$wpdb->prefix}ggmc_customers
            WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)"
        );

        // Active customers (ordered in last 90 days)
        $active_customers = $wpdb->get_var(
            "SELECT COUNT(DISTINCT customer_email) FROM {$wpdb->prefix}ggmc_orders
            WHERE created_at >= DATE_SUB(NOW(), INTERVAL 90 DAY)"
        );

        // Top customers by spend
        $top_customers = $wpdb->get_results(
            "SELECT
                email,
                first_name,
                last_name,
                total_orders,
                total_spent
            FROM {$wpdb->prefix}ggmc_customers
            ORDER BY total_spent DESC
            LIMIT 10"
        );

        // Customer lifetime value distribution
        $ltv_distribution = $wpdb->get_results(
            "SELECT
                CASE
                    WHEN total_spent < 100 THEN 'Under $100'
                    WHEN total_spent < 500 THEN '$100-$500'
                    WHEN total_spent < 1000 THEN '$500-$1000'
                    WHEN total_spent < 5000 THEN '$1000-$5000'
                    ELSE 'Over $5000'
                END as range,
                COUNT(*) as customer_count
            FROM {$wpdb->prefix}ggmc_customers
            GROUP BY range
            ORDER BY MIN(total_spent)"
        );

        // Average orders per customer
        $avg_orders = $wpdb->get_var(
            "SELECT AVG(total_orders) FROM {$wpdb->prefix}ggmc_customers WHERE total_orders > 0"
        );

        // Average customer value
        $avg_customer_value = $wpdb->get_var(
            "SELECT AVG(total_spent) FROM {$wpdb->prefix}ggmc_customers WHERE total_spent > 0"
        );

        return [
            'overview' => [
                'total_customers' => (int) $total_customers,
                'new_customers_30d' => (int) $new_customers,
                'active_customers_90d' => (int) $active_customers,
                'average_orders_per_customer' => (float) $avg_orders,
                'average_customer_lifetime_value' => (float) $avg_customer_value
            ],
            'top_customers' => $top_customers,
            'lifetime_value_distribution' => $ltv_distribution,
            'timestamp' => current_time('mysql')
        ];
    }
}
