<?php
/**
 * GGM Commerce Customer Tools
 *
 * MCP Tools for customer management
 * Tools are executable actions that AI can invoke
 *
 * @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_Tools {

    /**
     * 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_tools();
    }

    /**
     * Register all customer tools
     */
    private function register_tools() {
        // List customers
        $this->server->register_tool(
            'list_customers',
            'List customers with optional filtering',
            [
                'type' => 'object',
                'properties' => [
                    'search' => [
                        'type' => 'string',
                        'description' => 'Search by name, email, or phone'
                    ],
                    'account_type' => [
                        'type' => 'string',
                        'description' => 'Filter by account type',
                        'enum' => ['individual', 'business', 'all'],
                        'default' => 'all'
                    ],
                    'sort_by' => [
                        'type' => 'string',
                        'description' => 'Sort field',
                        'enum' => ['created_at', 'last_order_date', 'total_spent', 'total_orders', 'last_name'],
                        'default' => 'created_at'
                    ],
                    'sort_order' => [
                        'type' => 'string',
                        'description' => 'Sort direction',
                        'enum' => ['asc', 'desc'],
                        'default' => 'desc'
                    ],
                    'limit' => [
                        'type' => 'integer',
                        'description' => 'Maximum results',
                        'minimum' => 1,
                        'maximum' => 100,
                        'default' => 50
                    ]
                ]
            ],
            [$this, 'list_customers']
        );

        // Get customer
        $this->server->register_tool(
            'get_customer',
            'Get detailed customer information including addresses',
            [
                'type' => 'object',
                'properties' => [
                    'customer_id' => [
                        'type' => 'integer',
                        'description' => 'Customer ID',
                        'minimum' => 1
                    ],
                    'email' => [
                        'type' => 'string',
                        'description' => 'Customer email (alternative to ID)'
                    ]
                ]
            ],
            [$this, 'get_customer']
        );

        // Create customer
        $this->server->register_tool(
            'create_customer',
            'Create a new customer',
            [
                'type' => 'object',
                'properties' => [
                    'email' => [
                        'type' => 'string',
                        'description' => 'Customer email (required)'
                    ],
                    'first_name' => [
                        'type' => 'string',
                        'description' => 'First name (required)'
                    ],
                    'last_name' => [
                        'type' => 'string',
                        'description' => 'Last name (required)'
                    ],
                    'phone' => [
                        'type' => 'string',
                        'description' => 'Phone number'
                    ],
                    'company' => [
                        'type' => 'string',
                        'description' => 'Company name (for business accounts)'
                    ],
                    'account_type' => [
                        'type' => 'string',
                        'description' => 'Account type',
                        'enum' => ['individual', 'business'],
                        'default' => 'individual'
                    ],
                    'tax_id' => [
                        'type' => 'string',
                        'description' => 'Tax ID/VAT number (for business accounts)'
                    ],
                    'is_tax_exempt' => [
                        'type' => 'boolean',
                        'description' => 'Whether customer is tax exempt',
                        'default' => false
                    ]
                ],
                'required' => ['email', 'first_name', 'last_name']
            ],
            [$this, 'create_customer']
        );

        // Update customer
        $this->server->register_tool(
            'update_customer',
            'Update customer information',
            [
                'type' => 'object',
                'properties' => [
                    'customer_id' => [
                        'type' => 'integer',
                        'description' => 'Customer ID (required)',
                        'minimum' => 1
                    ],
                    'email' => [
                        'type' => 'string',
                        'description' => 'New email address'
                    ],
                    'first_name' => [
                        'type' => 'string',
                        'description' => 'First name'
                    ],
                    'last_name' => [
                        'type' => 'string',
                        'description' => 'Last name'
                    ],
                    'phone' => [
                        'type' => 'string',
                        'description' => 'Phone number'
                    ],
                    'company' => [
                        'type' => 'string',
                        'description' => 'Company name'
                    ],
                    'account_type' => [
                        'type' => 'string',
                        'description' => 'Account type',
                        'enum' => ['individual', 'business']
                    ],
                    'tax_id' => [
                        'type' => 'string',
                        'description' => 'Tax ID/VAT number'
                    ],
                    'is_tax_exempt' => [
                        'type' => 'boolean',
                        'description' => 'Tax exempt status'
                    ]
                ],
                'required' => ['customer_id']
            ],
            [$this, 'update_customer']
        );

        // Add customer address
        $this->server->register_tool(
            'add_customer_address',
            'Add a new address to customer',
            [
                'type' => 'object',
                'properties' => [
                    'customer_id' => [
                        'type' => 'integer',
                        'description' => 'Customer ID (required)',
                        'minimum' => 1
                    ],
                    'address_type' => [
                        'type' => 'string',
                        'description' => 'Address type',
                        'enum' => ['billing', 'shipping'],
                        'default' => 'shipping'
                    ],
                    'address_name' => [
                        'type' => 'string',
                        'description' => 'Friendly name for this address (e.g., "Home", "Office")'
                    ],
                    'first_name' => [
                        'type' => 'string',
                        'description' => 'First name'
                    ],
                    'last_name' => [
                        'type' => 'string',
                        'description' => 'Last name'
                    ],
                    'company' => [
                        'type' => 'string',
                        'description' => 'Company name'
                    ],
                    'address_line_1' => [
                        'type' => 'string',
                        'description' => 'Street address line 1 (required)'
                    ],
                    'address_line_2' => [
                        'type' => 'string',
                        'description' => 'Street address line 2'
                    ],
                    'city' => [
                        'type' => 'string',
                        'description' => 'City (required)'
                    ],
                    'state' => [
                        'type' => 'string',
                        'description' => 'State/Province/Region'
                    ],
                    'postcode' => [
                        'type' => 'string',
                        'description' => 'Postal/ZIP code (required)'
                    ],
                    'country' => [
                        'type' => 'string',
                        'description' => 'Country code (required, e.g., "GB", "US")'
                    ],
                    'phone' => [
                        'type' => 'string',
                        'description' => 'Phone number for this address'
                    ],
                    'is_default' => [
                        'type' => 'boolean',
                        'description' => 'Set as default address for this type',
                        'default' => false
                    ]
                ],
                'required' => ['customer_id', 'address_line_1', 'city', 'postcode', 'country']
            ],
            [$this, 'add_customer_address']
        );

        // Update customer address
        $this->server->register_tool(
            'update_customer_address',
            'Update an existing customer address',
            [
                'type' => 'object',
                'properties' => [
                    'address_id' => [
                        'type' => 'integer',
                        'description' => 'Address ID (required)',
                        'minimum' => 1
                    ],
                    'address_name' => [
                        'type' => 'string',
                        'description' => 'Friendly name for this address'
                    ],
                    'first_name' => [
                        'type' => 'string',
                        'description' => 'First name'
                    ],
                    'last_name' => [
                        'type' => 'string',
                        'description' => 'Last name'
                    ],
                    'company' => [
                        'type' => 'string',
                        'description' => 'Company name'
                    ],
                    'address_line_1' => [
                        'type' => 'string',
                        'description' => 'Street address line 1'
                    ],
                    'address_line_2' => [
                        'type' => 'string',
                        'description' => 'Street address line 2'
                    ],
                    'city' => [
                        'type' => 'string',
                        'description' => 'City'
                    ],
                    'state' => [
                        'type' => 'string',
                        'description' => 'State/Province/Region'
                    ],
                    'postcode' => [
                        'type' => 'string',
                        'description' => 'Postal/ZIP code'
                    ],
                    'country' => [
                        'type' => 'string',
                        'description' => 'Country code'
                    ],
                    'phone' => [
                        'type' => 'string',
                        'description' => 'Phone number'
                    ],
                    'is_default' => [
                        'type' => 'boolean',
                        'description' => 'Set as default address'
                    ]
                ],
                'required' => ['address_id']
            ],
            [$this, 'update_customer_address']
        );

        // Delete customer address
        $this->server->register_tool(
            'delete_customer_address',
            'Delete a customer address',
            [
                'type' => 'object',
                'properties' => [
                    'address_id' => [
                        'type' => 'integer',
                        'description' => 'Address ID (required)',
                        'minimum' => 1
                    ]
                ],
                'required' => ['address_id']
            ],
            [$this, 'delete_customer_address']
        );

        // Get customer orders
        $this->server->register_tool(
            'get_customer_orders',
            'Get order history for a customer',
            [
                'type' => 'object',
                'properties' => [
                    'customer_id' => [
                        'type' => 'integer',
                        'description' => 'Customer ID',
                        'minimum' => 1
                    ],
                    'email' => [
                        'type' => 'string',
                        'description' => 'Customer email (alternative to ID)'
                    ],
                    'limit' => [
                        'type' => 'integer',
                        'description' => 'Maximum orders to return',
                        'minimum' => 1,
                        'maximum' => 100,
                        'default' => 20
                    ]
                ]
            ],
            [$this, 'get_customer_orders']
        );
    }

    /**
     * List customers
     */
    public function list_customers($args) {
        global $wpdb;

        $where = ['1=1'];
        $params = [];

        // Search filter
        if (!empty($args['search'])) {
            $search = '%' . $wpdb->esc_like($args['search']) . '%';
            $where[] = "(email LIKE %s OR first_name LIKE %s OR last_name LIKE %s OR phone LIKE %s)";
            $params[] = $search;
            $params[] = $search;
            $params[] = $search;
            $params[] = $search;
        }

        // Account type filter
        if (!empty($args['account_type']) && $args['account_type'] !== 'all') {
            $where[] = "account_type = %s";
            $params[] = sanitize_key($args['account_type']);
        }

        $where_clause = implode(' AND ', $where);

        // Sorting
        $allowed_sort = ['created_at', 'last_order_date', 'total_spent', 'total_orders', 'last_name'];
        $sort_by = in_array($args['sort_by'] ?? 'created_at', $allowed_sort, true)
            ? $args['sort_by']
            : 'created_at';
        $sort_order = strtoupper($args['sort_order'] ?? 'desc') === 'ASC' ? 'ASC' : 'DESC';

        $limit = min(100, max(1, intval($args['limit'] ?? 50)));

        $sql = "SELECT * FROM {$wpdb->prefix}ggmc_customers WHERE {$where_clause} ORDER BY {$sort_by} {$sort_order} LIMIT {$limit}";

        if (!empty($params)) {
            $customers = $wpdb->get_results($wpdb->prepare($sql, ...$params));
        } else {
            $customers = $wpdb->get_results($sql);
        }

        $result = array_map(function($c) {
            return [
                'id' => (int) $c->id,
                'email' => $c->email,
                'first_name' => $c->first_name,
                'last_name' => $c->last_name,
                'full_name' => trim($c->first_name . ' ' . $c->last_name),
                'phone' => $c->phone,
                'company' => $c->company,
                'account_type' => $c->account_type ?? 'individual',
                'total_orders' => (int) $c->total_orders,
                'total_spent' => (float) $c->total_spent,
                'last_order_date' => $c->last_order_date,
                'created_at' => $c->created_at
            ];
        }, $customers);

        return [
            'success' => true,
            'customers' => $result,
            'count' => count($result)
        ];
    }

    /**
     * Get customer details
     */
    public function get_customer($args) {
        global $wpdb;

        if (empty($args['customer_id']) && empty($args['email'])) {
            return ['success' => false, 'error' => 'Customer ID or email is required'];
        }

        if (!empty($args['email'])) {
            $customer = $wpdb->get_row($wpdb->prepare(
                "SELECT * FROM {$wpdb->prefix}ggmc_customers WHERE email = %s",
                sanitize_email($args['email'])
            ));
        } else {
            $customer = $wpdb->get_row($wpdb->prepare(
                "SELECT * FROM {$wpdb->prefix}ggmc_customers WHERE id = %d",
                (int) $args['customer_id']
            ));
        }

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

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

        return [
            'success' => true,
            'customer' => [
                'id' => (int) $customer->id,
                'user_id' => (int) $customer->user_id,
                'email' => $customer->email,
                'first_name' => $customer->first_name,
                'last_name' => $customer->last_name,
                'full_name' => trim($customer->first_name . ' ' . $customer->last_name),
                'phone' => $customer->phone,
                'company' => $customer->company,
                'account_type' => $customer->account_type ?? 'individual',
                'tax_id' => $customer->tax_id,
                'is_tax_exempt' => (bool) $customer->is_tax_exempt,
                'total_orders' => (int) $customer->total_orders,
                'total_spent' => (float) $customer->total_spent,
                'last_order_date' => $customer->last_order_date,
                'created_at' => $customer->created_at,
                'addresses' => array_map(function($a) {
                    return [
                        'id' => (int) $a->id,
                        'address_type' => $a->address_type,
                        'address_name' => $a->address_name ?? '',
                        'first_name' => $a->first_name,
                        'last_name' => $a->last_name,
                        'company' => $a->company,
                        'address_line_1' => $a->address_line_1,
                        'address_line_2' => $a->address_line_2,
                        'city' => $a->city,
                        'state' => $a->state,
                        'postcode' => $a->postcode,
                        'country' => $a->country,
                        'phone' => $a->phone,
                        'is_default' => (bool) $a->is_default
                    ];
                }, $addresses)
            ]
        ];
    }

    /**
     * Create customer
     */
    public function create_customer($args) {
        global $wpdb;

        if (empty($args['email']) || empty($args['first_name']) || empty($args['last_name'])) {
            return ['success' => false, 'error' => 'Email, first name, and last name are required'];
        }

        $email = sanitize_email($args['email']);
        if (!is_email($email)) {
            return ['success' => false, 'error' => 'Invalid email address'];
        }

        // Check if customer exists
        $existing = $wpdb->get_var($wpdb->prepare(
            "SELECT id FROM {$wpdb->prefix}ggmc_customers WHERE email = %s",
            $email
        ));

        if ($existing) {
            return ['success' => false, 'error' => 'Customer with this email already exists', 'existing_id' => (int) $existing];
        }

        $data = [
            'email' => $email,
            'first_name' => sanitize_text_field($args['first_name']),
            'last_name' => sanitize_text_field($args['last_name']),
            'phone' => sanitize_text_field($args['phone'] ?? ''),
            'company' => sanitize_text_field($args['company'] ?? ''),
            'account_type' => sanitize_key($args['account_type'] ?? 'individual'),
            'tax_id' => sanitize_text_field($args['tax_id'] ?? ''),
            'is_tax_exempt' => !empty($args['is_tax_exempt']) ? 1 : 0,
            'created_at' => current_time('mysql'),
            'updated_at' => current_time('mysql')
        ];

        $inserted = $wpdb->insert("{$wpdb->prefix}ggmc_customers", $data);

        if (!$inserted) {
            return ['success' => false, 'error' => 'Failed to create customer'];
        }

        return [
            'success' => true,
            'customer_id' => $wpdb->insert_id,
            'message' => 'Customer created successfully'
        ];
    }

    /**
     * Update customer
     */
    public function update_customer($args) {
        global $wpdb;

        if (empty($args['customer_id'])) {
            return ['success' => false, 'error' => 'Customer ID is required'];
        }

        $customer_id = (int) $args['customer_id'];

        // Check customer exists
        $exists = $wpdb->get_var($wpdb->prepare(
            "SELECT id FROM {$wpdb->prefix}ggmc_customers WHERE id = %d",
            $customer_id
        ));

        if (!$exists) {
            return ['success' => false, 'error' => 'Customer not found'];
        }

        $data = [];
        $format = [];

        if (isset($args['email'])) {
            $email = sanitize_email($args['email']);
            if (!is_email($email)) {
                return ['success' => false, 'error' => 'Invalid email address'];
            }
            // Check email not used by another customer
            $email_exists = $wpdb->get_var($wpdb->prepare(
                "SELECT id FROM {$wpdb->prefix}ggmc_customers WHERE email = %s AND id != %d",
                $email,
                $customer_id
            ));
            if ($email_exists) {
                return ['success' => false, 'error' => 'Email already used by another customer'];
            }
            $data['email'] = $email;
            $format[] = '%s';
        }

        if (isset($args['first_name'])) {
            $data['first_name'] = sanitize_text_field($args['first_name']);
            $format[] = '%s';
        }

        if (isset($args['last_name'])) {
            $data['last_name'] = sanitize_text_field($args['last_name']);
            $format[] = '%s';
        }

        if (isset($args['phone'])) {
            $data['phone'] = sanitize_text_field($args['phone']);
            $format[] = '%s';
        }

        if (isset($args['company'])) {
            $data['company'] = sanitize_text_field($args['company']);
            $format[] = '%s';
        }

        if (isset($args['account_type'])) {
            $data['account_type'] = sanitize_key($args['account_type']);
            $format[] = '%s';
        }

        if (isset($args['tax_id'])) {
            $data['tax_id'] = sanitize_text_field($args['tax_id']);
            $format[] = '%s';
        }

        if (isset($args['is_tax_exempt'])) {
            $data['is_tax_exempt'] = $args['is_tax_exempt'] ? 1 : 0;
            $format[] = '%d';
        }

        if (empty($data)) {
            return ['success' => false, 'error' => 'No data to update'];
        }

        $data['updated_at'] = current_time('mysql');
        $format[] = '%s';

        $updated = $wpdb->update(
            "{$wpdb->prefix}ggmc_customers",
            $data,
            ['id' => $customer_id],
            $format,
            ['%d']
        );

        if ($updated === false) {
            return ['success' => false, 'error' => 'Failed to update customer'];
        }

        return [
            'success' => true,
            'message' => 'Customer updated successfully'
        ];
    }

    /**
     * Add customer address
     */
    public function add_customer_address($args) {
        global $wpdb;

        if (empty($args['customer_id'])) {
            return ['success' => false, 'error' => 'Customer ID is required'];
        }

        if (empty($args['address_line_1']) || empty($args['city']) || empty($args['postcode']) || empty($args['country'])) {
            return ['success' => false, 'error' => 'Address line 1, city, postcode, and country are required'];
        }

        $customer_id = (int) $args['customer_id'];

        // Check customer exists
        $customer = $wpdb->get_row($wpdb->prepare(
            "SELECT id, first_name, last_name FROM {$wpdb->prefix}ggmc_customers WHERE id = %d",
            $customer_id
        ));

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

        $address_type = sanitize_key($args['address_type'] ?? 'shipping');
        $is_default = !empty($args['is_default']);

        // If this is default, unset other defaults of same type
        if ($is_default) {
            $wpdb->update(
                "{$wpdb->prefix}ggmc_customer_addresses",
                ['is_default' => 0],
                ['customer_id' => $customer_id, 'address_type' => $address_type],
                ['%d'],
                ['%d', '%s']
            );
        }

        $data = [
            'customer_id' => $customer_id,
            'address_type' => $address_type,
            'address_name' => sanitize_text_field($args['address_name'] ?? ''),
            'first_name' => sanitize_text_field($args['first_name'] ?? $customer->first_name),
            'last_name' => sanitize_text_field($args['last_name'] ?? $customer->last_name),
            'company' => sanitize_text_field($args['company'] ?? ''),
            'address_line_1' => sanitize_text_field($args['address_line_1']),
            'address_line_2' => sanitize_text_field($args['address_line_2'] ?? ''),
            'city' => sanitize_text_field($args['city']),
            'state' => sanitize_text_field($args['state'] ?? ''),
            'postcode' => sanitize_text_field($args['postcode']),
            'country' => sanitize_text_field($args['country']),
            'phone' => sanitize_text_field($args['phone'] ?? ''),
            'is_default' => $is_default ? 1 : 0,
            'created_at' => current_time('mysql'),
            'updated_at' => current_time('mysql')
        ];

        $inserted = $wpdb->insert("{$wpdb->prefix}ggmc_customer_addresses", $data);

        if (!$inserted) {
            return ['success' => false, 'error' => 'Failed to add address'];
        }

        return [
            'success' => true,
            'address_id' => $wpdb->insert_id,
            'message' => 'Address added successfully'
        ];
    }

    /**
     * Update customer address
     */
    public function update_customer_address($args) {
        global $wpdb;

        if (empty($args['address_id'])) {
            return ['success' => false, 'error' => 'Address ID is required'];
        }

        $address_id = (int) $args['address_id'];

        // Check address exists
        $address = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM {$wpdb->prefix}ggmc_customer_addresses WHERE id = %d",
            $address_id
        ));

        if (!$address) {
            return ['success' => false, 'error' => 'Address not found'];
        }

        $data = [];
        $format = [];

        $text_fields = ['address_name', 'first_name', 'last_name', 'company', 'address_line_1', 'address_line_2', 'city', 'state', 'postcode', 'country', 'phone'];
        foreach ($text_fields as $field) {
            if (isset($args[$field])) {
                $data[$field] = sanitize_text_field($args[$field]);
                $format[] = '%s';
            }
        }

        if (isset($args['is_default'])) {
            $is_default = !empty($args['is_default']);

            // If setting as default, unset other defaults of same type
            if ($is_default) {
                $wpdb->update(
                    "{$wpdb->prefix}ggmc_customer_addresses",
                    ['is_default' => 0],
                    ['customer_id' => $address->customer_id, 'address_type' => $address->address_type],
                    ['%d'],
                    ['%d', '%s']
                );
            }

            $data['is_default'] = $is_default ? 1 : 0;
            $format[] = '%d';
        }

        if (empty($data)) {
            return ['success' => false, 'error' => 'No data to update'];
        }

        $data['updated_at'] = current_time('mysql');
        $format[] = '%s';

        $updated = $wpdb->update(
            "{$wpdb->prefix}ggmc_customer_addresses",
            $data,
            ['id' => $address_id],
            $format,
            ['%d']
        );

        if ($updated === false) {
            return ['success' => false, 'error' => 'Failed to update address'];
        }

        return [
            'success' => true,
            'message' => 'Address updated successfully'
        ];
    }

    /**
     * Delete customer address
     */
    public function delete_customer_address($args) {
        global $wpdb;

        if (empty($args['address_id'])) {
            return ['success' => false, 'error' => 'Address ID is required'];
        }

        $deleted = $wpdb->delete(
            "{$wpdb->prefix}ggmc_customer_addresses",
            ['id' => (int) $args['address_id']],
            ['%d']
        );

        if (!$deleted) {
            return ['success' => false, 'error' => 'Address not found or already deleted'];
        }

        return [
            'success' => true,
            'message' => 'Address deleted successfully'
        ];
    }

    /**
     * Get customer orders
     */
    public function get_customer_orders($args) {
        global $wpdb;

        if (empty($args['customer_id']) && empty($args['email'])) {
            return ['success' => false, 'error' => 'Customer ID or email is required'];
        }

        // Get customer email
        if (!empty($args['customer_id'])) {
            $email = $wpdb->get_var($wpdb->prepare(
                "SELECT email FROM {$wpdb->prefix}ggmc_customers WHERE id = %d",
                (int) $args['customer_id']
            ));
            if (!$email) {
                return ['success' => false, 'error' => 'Customer not found'];
            }
        } else {
            $email = sanitize_email($args['email']);
        }

        $limit = min(100, max(1, intval($args['limit'] ?? 20)));

        $orders = $wpdb->get_results($wpdb->prepare(
            "SELECT id, order_number, total_amount, currency, status, payment_status,
                    shipping_method, shipping_cost, created_at, updated_at
             FROM {$wpdb->prefix}ggmc_orders
             WHERE customer_email = %s
             ORDER BY created_at DESC
             LIMIT %d",
            $email,
            $limit
        ));

        $result = array_map(function($o) {
            return [
                'id' => (int) $o->id,
                'order_number' => $o->order_number,
                'total_amount' => (float) $o->total_amount,
                'currency' => $o->currency,
                'status' => $o->status,
                'payment_status' => $o->payment_status,
                'shipping_method' => $o->shipping_method,
                'shipping_cost' => (float) $o->shipping_cost,
                'created_at' => $o->created_at,
                'updated_at' => $o->updated_at
            ];
        }, $orders);

        return [
            'success' => true,
            'customer_email' => $email,
            'orders' => $result,
            'count' => count($result)
        ];
    }
}
