<?php
/**
 * 247ChatMate — Agency Bundle Licence Helpers
 * Checkpoint: AGENCYBUNDLELICENCELOCK1
 *
 * Purpose:
 * - Let an approved agency add paid LemonSqueezy bundle licences to its Agency Hub.
 * - Map approved LemonSqueezy variant IDs to client-seat counts.
 * - Store bundle licence records locally as masked rows for admin display.
 * - Keep remote LemonSqueezy status authoritative and local toggle advisory only.
 *
 * Does not:
 * - Assign seats to client sites.
 * - Export/import setup JSON.
 * - Give client sites the agency master LemonSqueezy key.
 * - Change frontend widget, chips, WhatsApp handoff, lead emails or weekly summary.
 */

defined('ABSPATH') || exit;

if (!defined('MATEWA_AGENCY_BUNDLE_LICENCES_OPTION')) {
    define('MATEWA_AGENCY_BUNDLE_LICENCES_OPTION', 'matewa_agency_bundle_licences');
}

if (!function_exists('matewa_agency_bundle_plan_map')) {
    function matewa_agency_bundle_plan_map() {
        return array(
            'agency_3_monthly' => array(
                'label'        => 'Agency 3 Monthly',
                'variant_id'   => '1753022',
                'item_id'      => '1119726',
                'billing'      => 'Monthly',
                'price'        => '£69/month',
                'seats'        => 3,
                'checkout_url' => 'https://247chatmate.lemonsqueezy.com/checkout/buy/95bf0311-9105-438e-b4a5-ded0d545ee9d',
            ),
            'agency_3_annual' => array(
                'label'        => 'Agency 3 Annual',
                'variant_id'   => '1753053',
                'item_id'      => '1119752',
                'billing'      => 'Annual',
                'price'        => '£690/year',
                'seats'        => 3,
                'checkout_url' => 'https://247chatmate.lemonsqueezy.com/checkout/buy/dfb072ed-eb3d-421e-8574-6d32eb1c115a',
            ),
            'agency_10_monthly' => array(
                'label'        => 'Agency 10 Monthly',
                'variant_id'   => '1753062',
                'item_id'      => '1119759',
                'billing'      => 'Monthly',
                'price'        => '£190/month',
                'seats'        => 10,
                'checkout_url' => 'https://247chatmate.lemonsqueezy.com/checkout/buy/71fa1a32-d783-42ef-8c08-b76a31abb642',
            ),
            'agency_10_annual' => array(
                'label'        => 'Agency 10 Annual',
                'variant_id'   => '1753076',
                'item_id'      => '1119769',
                'billing'      => 'Annual',
                'price'        => '£1,900/year',
                'seats'        => 10,
                'checkout_url' => 'https://247chatmate.lemonsqueezy.com/checkout/buy/caf33ac0-d83d-42cc-acbd-ef8754835391',
            ),
        );
    }
}

if (!function_exists('matewa_agency_bundle_get_default_checkout_url')) {
    function matewa_agency_bundle_get_default_checkout_url() {
        $plans = matewa_agency_bundle_plan_map();
        return isset($plans['agency_3_monthly']['checkout_url']) ? (string) $plans['agency_3_monthly']['checkout_url'] : 'https://247chatmate.lemonsqueezy.com/';
    }
}

if (!function_exists('matewa_agency_bundle_hash_value')) {
    function matewa_agency_bundle_hash_value($value) {
        $value = trim((string) $value);

        if ('' === $value) {
            return '';
        }

        if (function_exists('wp_salt')) {
            return hash_hmac('sha256', $value, wp_salt('auth'));
        }

        return hash('sha256', $value);
    }
}

if (!function_exists('matewa_agency_bundle_mask_key')) {
    function matewa_agency_bundle_mask_key($license_key) {
        $license_key = trim((string) $license_key);
        $clean = preg_replace('/\s+/', '', $license_key);

        if ('' === $clean) {
            return 'Saved key hidden';
        }

        $last = substr($clean, -4);
        if (false === $last || '' === $last) {
            $last = 'key';
        }

        return '••••-••••-' . strtoupper($last);
    }
}

if (!function_exists('matewa_agency_bundle_get_records')) {
    function matewa_agency_bundle_get_records() {
        $records = get_option(MATEWA_AGENCY_BUNDLE_LICENCES_OPTION, array());

        if (!is_array($records)) {
            return array();
        }

        $safe_records = array();

        foreach ($records as $record) {
            if (!is_array($record)) {
                continue;
            }

            $bundle_id = isset($record['bundle_id']) ? sanitize_key((string) $record['bundle_id']) : '';
            if ('' === $bundle_id) {
                continue;
            }

            $safe_records[] = array(
                'bundle_id'      => $bundle_id,
                'license_key'    => isset($record['license_key']) ? trim((string) $record['license_key']) : '',
                'license_hash'   => isset($record['license_hash']) ? sanitize_text_field((string) $record['license_hash']) : '',
                'masked_key'     => isset($record['masked_key']) ? sanitize_text_field((string) $record['masked_key']) : 'Saved key hidden',
                'local_enabled'  => !empty($record['local_enabled']),
                'valid'          => !empty($record['valid']),
                'status'         => isset($record['status']) ? sanitize_key((string) $record['status']) : 'not_checked',
                'message'        => isset($record['message']) ? sanitize_text_field((string) $record['message']) : '',
                'plan_key'       => isset($record['plan_key']) ? sanitize_key((string) $record['plan_key']) : '',
                'plan_label'     => isset($record['plan_label']) ? sanitize_text_field((string) $record['plan_label']) : '',
                'variant_id'     => isset($record['variant_id']) ? sanitize_text_field((string) $record['variant_id']) : '',
                'item_id'        => isset($record['item_id']) ? sanitize_text_field((string) $record['item_id']) : '',
                'billing'        => isset($record['billing']) ? sanitize_text_field((string) $record['billing']) : '',
                'price'          => isset($record['price']) ? sanitize_text_field((string) $record['price']) : '',
                'seats'          => isset($record['seats']) ? absint($record['seats']) : 0,
                'used_seats'     => isset($record['used_seats']) ? absint($record['used_seats']) : 0,
                'available_seats'=> isset($record['available_seats']) ? absint($record['available_seats']) : 0,
                'renews_at'      => isset($record['renews_at']) ? sanitize_text_field((string) $record['renews_at']) : '',
                'expires_at'     => isset($record['expires_at']) ? sanitize_text_field((string) $record['expires_at']) : '',
                'renewal_status' => isset($record['renewal_status']) ? sanitize_key((string) $record['renewal_status']) : 'unknown',
                'instance_id'    => isset($record['instance_id']) ? sanitize_text_field((string) $record['instance_id']) : '',
                'instance_name'  => isset($record['instance_name']) ? sanitize_text_field((string) $record['instance_name']) : '',
                'checked_at'     => isset($record['checked_at']) ? (int) $record['checked_at'] : 0,
                'created_at'     => isset($record['created_at']) ? (int) $record['created_at'] : 0,
                'updated_at'     => isset($record['updated_at']) ? (int) $record['updated_at'] : 0,
            );
        }

        return $safe_records;
    }
}

if (!function_exists('matewa_agency_bundle_store_records')) {
    function matewa_agency_bundle_store_records($records) {
        $records = is_array($records) ? array_values($records) : array();
        update_option(MATEWA_AGENCY_BUNDLE_LICENCES_OPTION, $records, false);
        return true;
    }
}

if (!function_exists('matewa_agency_bundle_find_plan_by_variant_id')) {
    function matewa_agency_bundle_find_plan_by_variant_id($variant_id) {
        $variant_id = trim((string) $variant_id);
        $plans = matewa_agency_bundle_plan_map();

        foreach ($plans as $plan_key => $plan) {
            if ($variant_id !== '' && isset($plan['variant_id']) && hash_equals((string) $plan['variant_id'], $variant_id)) {
                $plan['plan_key'] = $plan_key;
                return $plan;
            }
        }

        return array();
    }
}

if (!function_exists('matewa_agency_bundle_find_plan_by_variant_name')) {
    function matewa_agency_bundle_find_plan_by_variant_name($variant_name) {
        $variant_name = strtolower(trim((string) $variant_name));

        if ('' === $variant_name) {
            return array();
        }

        $plans = matewa_agency_bundle_plan_map();

        foreach ($plans as $plan_key => $plan) {
            $label = isset($plan['label']) ? strtolower(trim((string) $plan['label'])) : '';
            if ('' !== $label && false !== strpos($variant_name, $label)) {
                $plan['plan_key'] = $plan_key;
                return $plan;
            }
        }

        return array();
    }
}

if (!function_exists('matewa_agency_bundle_pick_first_string')) {
    function matewa_agency_bundle_pick_first_string($source, $keys) {
        if (!is_array($source)) {
            return '';
        }

        foreach ((array) $keys as $key) {
            if (isset($source[$key]) && is_scalar($source[$key]) && '' !== trim((string) $source[$key])) {
                return trim((string) $source[$key]);
            }
        }

        return '';
    }
}

if (!function_exists('matewa_agency_bundle_extract_response_meta')) {
    function matewa_agency_bundle_extract_response_meta($body) {
        $body = is_array($body) ? $body : array();
        $license = isset($body['license_key']) && is_array($body['license_key']) ? $body['license_key'] : array();
        $meta = isset($body['meta']) && is_array($body['meta']) ? $body['meta'] : array();

        $variant_id = matewa_agency_bundle_pick_first_string($license, array('variant_id', 'variant'));
        if ('' === $variant_id) {
            $variant_id = matewa_agency_bundle_pick_first_string($meta, array('variant_id', 'variant'));
        }

        $variant_name = matewa_agency_bundle_pick_first_string($license, array('variant_name', 'variant'));
        if ('' === $variant_name) {
            $variant_name = matewa_agency_bundle_pick_first_string($meta, array('variant_name'));
        }

        $item_id = matewa_agency_bundle_pick_first_string($license, array('id', 'key_id', 'license_key_id'));
        $status = matewa_agency_bundle_pick_first_string($license, array('status'));
        $expires_at = matewa_agency_bundle_pick_first_string($license, array('expires_at', 'expiration_date'));
        $renews_at = matewa_agency_bundle_pick_first_string($license, array('renews_at', 'renewal_date'));

        $instance = isset($body['instance']) && is_array($body['instance']) ? $body['instance'] : array();
        $instance_id = matewa_agency_bundle_pick_first_string($instance, array('id'));
        $instance_name = matewa_agency_bundle_pick_first_string($instance, array('name'));

        return array(
            'variant_id'   => sanitize_text_field($variant_id),
            'variant_name' => sanitize_text_field($variant_name),
            'item_id'      => sanitize_text_field($item_id),
            'status'       => sanitize_key($status),
            'expires_at'   => sanitize_text_field($expires_at),
            'renews_at'    => sanitize_text_field($renews_at),
            'instance_id'  => sanitize_text_field($instance_id),
            'instance_name'=> sanitize_text_field($instance_name),
        );
    }
}

if (!function_exists('matewa_agency_bundle_instance_name')) {
    function matewa_agency_bundle_instance_name() {
        if (function_exists('matewa_license_instance_name')) {
            return substr(matewa_license_instance_name() . ' Agency Bundle', 0, 90);
        }

        $host = function_exists('home_url') ? wp_parse_url(home_url('/'), PHP_URL_HOST) : 'wordpress-site';
        $host = is_string($host) ? sanitize_text_field($host) : 'wordpress-site';
        return substr('247ChatMate Agency Bundle - ' . $host, 0, 90);
    }
}

if (!function_exists('matewa_agency_bundle_http_result')) {
    function matewa_agency_bundle_http_result($code, $message, $extra = array()) {
        $result = array(
            'success'    => false,
            'valid'      => false,
            'code'       => sanitize_key((string) $code),
            'message'    => sanitize_text_field((string) $message),
            'checked_at' => time(),
        );

        return array_merge($result, is_array($extra) ? $extra : array());
    }
}

if (!function_exists('matewa_agency_bundle_validate_with_lemonsqueezy')) {
    function matewa_agency_bundle_validate_with_lemonsqueezy($license_key, $existing_instance_id = '') {
        $license_key = trim((string) $license_key);
        $existing_instance_id = sanitize_text_field((string) $existing_instance_id);

        if ('' === $license_key) {
            return matewa_agency_bundle_http_result('missing_key', 'Enter an agency bundle licence key.');
        }

        $instance_id = $existing_instance_id;
        $instance_name = matewa_agency_bundle_instance_name();

        if ('' === $instance_id) {
            $activate_response = wp_remote_post(
                'https://api.lemonsqueezy.com/v1/licenses/activate',
                array(
                    'timeout' => 8,
                    'headers' => array(
                        'Accept'       => 'application/json',
                        'Content-Type' => 'application/x-www-form-urlencoded',
                    ),
                    'body'    => array(
                        'license_key'   => $license_key,
                        'instance_name' => $instance_name,
                    ),
                )
            );

            if (is_wp_error($activate_response)) {
                return matewa_agency_bundle_http_result('activation_request_error', 'Agency bundle activation request failed. Try again later.');
            }

            $activate_status = (int) wp_remote_retrieve_response_code($activate_response);
            $activate_body = json_decode(wp_remote_retrieve_body($activate_response), true);

            if (!is_array($activate_body)) {
                return matewa_agency_bundle_http_result('activation_invalid_response', 'Agency bundle activation returned an invalid response.');
            }

            if (200 !== $activate_status || empty($activate_body['activated'])) {
                $error = '';
                if (!empty($activate_body['error']) && is_string($activate_body['error'])) {
                    $error = sanitize_text_field($activate_body['error']);
                }

                return matewa_agency_bundle_http_result(
                    'activation_failed',
                    '' !== $error ? $error : 'Agency bundle activation failed. Check the key or activation limit.'
                );
            }

            $activate_meta = matewa_agency_bundle_extract_response_meta($activate_body);
            $instance_id = isset($activate_meta['instance_id']) ? sanitize_text_field((string) $activate_meta['instance_id']) : '';
            $instance_name = isset($activate_meta['instance_name']) && '' !== $activate_meta['instance_name'] ? sanitize_text_field($activate_meta['instance_name']) : $instance_name;

            if ('' === $instance_id) {
                return matewa_agency_bundle_http_result('activation_missing_instance', 'Agency bundle activated, but no site instance was returned.');
            }
        }

        $validate_response = wp_remote_post(
            'https://api.lemonsqueezy.com/v1/licenses/validate',
            array(
                'timeout' => 8,
                'headers' => array(
                    'Accept'       => 'application/json',
                    'Content-Type' => 'application/x-www-form-urlencoded',
                ),
                'body'    => array(
                    'license_key' => $license_key,
                    'instance_id' => $instance_id,
                ),
            )
        );

        if (is_wp_error($validate_response)) {
            return matewa_agency_bundle_http_result('validation_request_error', 'Agency bundle validation request failed. Try again later.', array('instance_id' => $instance_id, 'instance_name' => $instance_name));
        }

        $validate_status = (int) wp_remote_retrieve_response_code($validate_response);
        $validate_body = json_decode(wp_remote_retrieve_body($validate_response), true);

        if (!is_array($validate_body)) {
            return matewa_agency_bundle_http_result('validation_invalid_response', 'Agency bundle validation returned an invalid response.', array('instance_id' => $instance_id, 'instance_name' => $instance_name));
        }

        $meta = matewa_agency_bundle_extract_response_meta($validate_body);
        $status = isset($meta['status']) ? sanitize_key((string) $meta['status']) : '';
        $valid = !empty($validate_body['valid']);
        $blocked_statuses = array('cancelled', 'canceled', 'refunded', 'expired', 'disabled', 'deactivated');

        if (in_array($status, $blocked_statuses, true)) {
            $valid = false;
        }

        $plan = matewa_agency_bundle_find_plan_by_variant_id($meta['variant_id'] ?? '');
        if (empty($plan)) {
            $plan = matewa_agency_bundle_find_plan_by_variant_name($meta['variant_name'] ?? '');
        }

        if (empty($plan)) {
            return matewa_agency_bundle_http_result(
                'unsupported_variant',
                'This licence is valid but is not an agency bundle variant.',
                array(
                    'instance_id'   => $instance_id,
                    'instance_name' => $instance_name,
                    'variant_id'    => sanitize_text_field((string) ($meta['variant_id'] ?? '')),
                    'remote_status' => $status,
                )
            );
        }

        $message = 'Agency bundle licence validated.';
        if (!$valid) {
            if (!empty($validate_body['error']) && is_string($validate_body['error'])) {
                $message = sanitize_text_field($validate_body['error']);
            } elseif ('' !== $status) {
                $message = 'Agency bundle status is ' . str_replace('_', ' ', $status) . '.';
            } else {
                $message = 'Agency bundle licence is not active.';
            }
        }

        return array(
            'success'        => $valid,
            'valid'          => $valid,
            'code'           => $valid ? 'bundle_valid' : ('' !== $status ? $status : 'bundle_invalid'),
            'message'        => $message,
            'checked_at'     => time(),
            'instance_id'    => $instance_id,
            'instance_name'  => $instance_name,
            'remote_status'  => $status,
            'plan_key'       => sanitize_key((string) ($plan['plan_key'] ?? '')),
            'plan_label'     => sanitize_text_field((string) ($plan['label'] ?? 'Agency bundle')),
            'variant_id'     => sanitize_text_field((string) ($plan['variant_id'] ?? '')),
            'item_id'        => sanitize_text_field((string) ($plan['item_id'] ?? '')),
            'billing'        => sanitize_text_field((string) ($plan['billing'] ?? '')),
            'price'          => sanitize_text_field((string) ($plan['price'] ?? '')),
            'seats'          => isset($plan['seats']) ? absint($plan['seats']) : 0,
            'checkout_url'   => esc_url_raw((string) ($plan['checkout_url'] ?? '')),
            'renews_at'      => sanitize_text_field((string) ($meta['renews_at'] ?? '')),
            'expires_at'     => sanitize_text_field((string) ($meta['expires_at'] ?? '')),
            'renewal_status' => $valid ? 'set_to_renew' : 'check_billing',
        );
    }
}

if (!function_exists('matewa_agency_bundle_record_from_validation')) {
    function matewa_agency_bundle_record_from_validation($license_key, $validation, $existing = array()) {
        $license_key = trim((string) $license_key);
        $validation = is_array($validation) ? $validation : array();
        $existing = is_array($existing) ? $existing : array();
        $now = time();
        $seats = isset($validation['seats']) ? absint($validation['seats']) : 0;
        $used = isset($existing['used_seats']) ? absint($existing['used_seats']) : 0;

        $bundle_id = isset($existing['bundle_id']) && '' !== sanitize_key((string) $existing['bundle_id'])
            ? sanitize_key((string) $existing['bundle_id'])
            : 'bundle_' . substr(matewa_agency_bundle_hash_value($license_key . '|' . $now), 0, 12);

        return array(
            'bundle_id'       => $bundle_id,
            'license_key'     => $license_key,
            'license_hash'    => matewa_agency_bundle_hash_value($license_key),
            'masked_key'      => matewa_agency_bundle_mask_key($license_key),
            'local_enabled'   => array_key_exists('local_enabled', $existing) ? !empty($existing['local_enabled']) : true,
            'valid'           => !empty($validation['valid']),
            'status'          => !empty($validation['valid']) ? 'active' : sanitize_key((string) ($validation['code'] ?? 'invalid')),
            'message'         => sanitize_text_field((string) ($validation['message'] ?? '')),
            'plan_key'        => sanitize_key((string) ($validation['plan_key'] ?? '')),
            'plan_label'      => sanitize_text_field((string) ($validation['plan_label'] ?? 'Agency bundle')),
            'variant_id'      => sanitize_text_field((string) ($validation['variant_id'] ?? '')),
            'item_id'         => sanitize_text_field((string) ($validation['item_id'] ?? '')),
            'billing'         => sanitize_text_field((string) ($validation['billing'] ?? '')),
            'price'           => sanitize_text_field((string) ($validation['price'] ?? '')),
            'seats'           => $seats,
            'used_seats'      => $used,
            'available_seats' => max(0, $seats - $used),
            'renews_at'       => sanitize_text_field((string) ($validation['renews_at'] ?? '')),
            'expires_at'      => sanitize_text_field((string) ($validation['expires_at'] ?? '')),
            'renewal_status'  => sanitize_key((string) ($validation['renewal_status'] ?? 'unknown')),
            'instance_id'     => sanitize_text_field((string) ($validation['instance_id'] ?? ($existing['instance_id'] ?? ''))),
            'instance_name'   => sanitize_text_field((string) ($validation['instance_name'] ?? ($existing['instance_name'] ?? ''))),
            'checked_at'      => isset($validation['checked_at']) ? (int) $validation['checked_at'] : $now,
            'created_at'      => isset($existing['created_at']) ? (int) $existing['created_at'] : $now,
            'updated_at'      => $now,
        );
    }
}

if (!function_exists('matewa_agency_bundle_find_record_index')) {
    function matewa_agency_bundle_find_record_index($records, $bundle_id = '', $license_hash = '') {
        $bundle_id = sanitize_key((string) $bundle_id);
        $license_hash = sanitize_text_field((string) $license_hash);

        foreach ((array) $records as $index => $record) {
            if (!is_array($record)) {
                continue;
            }

            if ('' !== $bundle_id && isset($record['bundle_id']) && hash_equals($bundle_id, sanitize_key((string) $record['bundle_id']))) {
                return $index;
            }

            if ('' !== $license_hash && isset($record['license_hash']) && hash_equals($license_hash, sanitize_text_field((string) $record['license_hash']))) {
                return $index;
            }
        }

        return -1;
    }
}

if (!function_exists('matewa_agency_bundle_handle_admin_action')) {
    function matewa_agency_bundle_handle_admin_action($post) {
        $post = is_array($post) ? $post : array();
        $action = isset($post['matewa_agency_bundle_action']) ? sanitize_key((string) $post['matewa_agency_bundle_action']) : '';

        if ('' === $action) {
            return array('code' => '', 'message' => '');
        }

        if (!function_exists('matewa_agency_hub_is_active') || !matewa_agency_hub_is_active()) {
            return array('code' => 'agency_required', 'message' => 'Agency Hub access is required before adding client bundle licences.');
        }

        $records = matewa_agency_bundle_get_records();
        $bundle_id = isset($post['matewa_agency_bundle_id']) ? sanitize_key((string) $post['matewa_agency_bundle_id']) : '';

        if ('add' === $action) {
            $license_key = isset($post['matewa_agency_bundle_license_key']) ? trim(sanitize_text_field((string) $post['matewa_agency_bundle_license_key'])) : '';

            if ('' === $license_key) {
                return array('code' => 'bundle_missing_key', 'message' => 'Enter an agency bundle licence key.');
            }

            $license_hash = matewa_agency_bundle_hash_value($license_key);
            $existing_index = matewa_agency_bundle_find_record_index($records, '', $license_hash);
            $existing = $existing_index >= 0 && isset($records[$existing_index]) && is_array($records[$existing_index]) ? $records[$existing_index] : array();
            $existing_instance_id = isset($existing['instance_id']) ? sanitize_text_field((string) $existing['instance_id']) : '';

            $validation = matewa_agency_bundle_validate_with_lemonsqueezy($license_key, $existing_instance_id);
            $record = matewa_agency_bundle_record_from_validation($license_key, $validation, $existing);

            if ($existing_index >= 0) {
                $records[$existing_index] = $record;
            } else {
                $records[] = $record;
            }

            matewa_agency_bundle_store_records($records);

            return array(
                'code'    => !empty($validation['valid']) ? 'bundle_saved' : sanitize_key((string) ($validation['code'] ?? 'bundle_invalid')),
                'message' => sanitize_text_field((string) ($validation['message'] ?? 'Agency bundle checked.')),
            );
        }

        $index = matewa_agency_bundle_find_record_index($records, $bundle_id, '');
        if ($index < 0 || !isset($records[$index]) || !is_array($records[$index])) {
            return array('code' => 'bundle_not_found', 'message' => 'Agency bundle record was not found.');
        }

        if ('toggle_on' === $action || 'toggle_off' === $action) {
            $records[$index]['local_enabled'] = ('toggle_on' === $action);
            $records[$index]['updated_at'] = time();
            matewa_agency_bundle_store_records($records);

            return array(
                'code'    => 'toggle_on' === $action ? 'bundle_enabled' : 'bundle_paused',
                'message' => 'toggle_on' === $action ? 'Agency bundle enabled locally.' : 'Agency bundle paused locally.',
            );
        }

        if ('recheck' === $action) {
            $license_key = isset($records[$index]['license_key']) ? trim((string) $records[$index]['license_key']) : '';
            $instance_id = isset($records[$index]['instance_id']) ? sanitize_text_field((string) $records[$index]['instance_id']) : '';

            if ('' === $license_key) {
                return array('code' => 'bundle_missing_saved_key', 'message' => 'Saved agency bundle key is missing. Re-enter the key.');
            }

            $validation = matewa_agency_bundle_validate_with_lemonsqueezy($license_key, $instance_id);
            $records[$index] = matewa_agency_bundle_record_from_validation($license_key, $validation, $records[$index]);
            matewa_agency_bundle_store_records($records);

            return array(
                'code'    => !empty($validation['valid']) ? 'bundle_rechecked' : sanitize_key((string) ($validation['code'] ?? 'bundle_invalid')),
                'message' => sanitize_text_field((string) ($validation['message'] ?? 'Agency bundle rechecked.')),
            );
        }

        return array('code' => 'bundle_unknown_action', 'message' => 'Unknown agency bundle action.');
    }
}

if (!function_exists('matewa_agency_bundle_get_seat_summary')) {
    function matewa_agency_bundle_get_seat_summary() {
        if (function_exists('matewa_agency_client_pack_reconcile_bundle_seats')) {
            matewa_agency_client_pack_reconcile_bundle_seats();
        }

        $records = matewa_agency_bundle_get_records();
        $total = 0;
        $used = 0;
        $active_count = 0;
        $paused_count = 0;
        $needs_attention = 0;
        $expiring_soon = 0;

        foreach ($records as $record) {
            $is_valid = !empty($record['valid']);
            $is_enabled = !empty($record['local_enabled']);
            $seats = isset($record['seats']) ? absint($record['seats']) : 0;
            $record_used = isset($record['used_seats']) ? absint($record['used_seats']) : 0;

            if ($is_valid && $is_enabled) {
                $active_count++;
                $total += $seats;
                $used += min($record_used, $seats);
            } elseif ($is_valid && !$is_enabled) {
                $paused_count++;
            } elseif (!$is_valid) {
                $needs_attention++;
            }

            $expiry = '';
            if (!empty($record['expires_at'])) {
                $expiry = (string) $record['expires_at'];
            } elseif (!empty($record['renews_at'])) {
                $expiry = (string) $record['renews_at'];
            }

            if ('' !== $expiry) {
                $ts = strtotime($expiry);
                if ($ts && $ts >= time() && $ts <= time() + (30 * DAY_IN_SECONDS)) {
                    $expiring_soon++;
                }
            }
        }

        return array(
            'total'           => max(0, $total),
            'used'            => max(0, $used),
            'available'       => max(0, $total - $used),
            'active_bundles'  => $active_count,
            'paused_bundles'  => $paused_count,
            'bundle_count'    => count($records),
            'needs_attention' => $needs_attention,
            'expiring_soon'   => $expiring_soon,
        );
    }
}

if (!function_exists('matewa_agency_bundle_notice_message')) {
    function matewa_agency_bundle_notice_message($code = '') {
        $code = sanitize_key((string) $code);

        $messages = array(
            'bundle_saved'              => 'Agency bundle licence saved and validated.',
            'bundle_rechecked'          => 'Agency bundle licence rechecked.',
            'bundle_enabled'            => 'Agency bundle enabled locally.',
            'bundle_paused'             => 'Agency bundle paused locally.',
            'bundle_missing_key'        => 'Enter an agency bundle licence key.',
            'unsupported_variant'       => 'This key is valid but is not an agency bundle variant.',
            'activation_failed'         => 'Agency bundle activation failed. Check the key or activation limit.',
            'activation_request_error'  => 'Agency bundle activation could not be reached. Try again later.',
            'validation_request_error'  => 'Agency bundle validation could not be reached. Try again later.',
            'agency_required'           => 'Agency Hub access is required before adding bundle licences.',
            'bundle_not_found'          => 'Agency bundle record was not found.',
            'bundle_missing_saved_key'  => 'Saved agency bundle key is missing. Re-enter the key.',
        );

        return isset($messages[$code]) ? $messages[$code] : ('' !== $code ? 'Agency bundle status: ' . str_replace('_', ' ', $code) . '.' : '');
    }
}
