<?php
/**
 * 247ChatMate — Agency Client Setup Pack Helpers
 * Checkpoint: AGENCYCLIENTPACKROWACTIONSLOCK1
 *
 * Purpose:
 * - Let an approved agency create manual client setup-pack rows.
 * - Assign one available paid agency bundle seat to each manual client pack.
 * - Capture the client details needed for a later JSON export/import checkpoint.
 * - Duplicate the Visitor Buttons category/business-type/chip defaults into client setup packs only.
 * - Keep remote sending/widget-scope payload namespaced so agency setup does not alter the agency site's live widget.
 * - Let agencies edit/delete manual setup packs while preserving seat counts.
 * - Capture separate client admin and leads email addresses for later routing/reporting.
 * - Export a portable client-site setup JSON payload for later import into the end-user WordPress plugin.
 *
 * Does not:
 * - Export or import setup JSON.
 * - Install anything on client sites.
 * - Parse PDFs.
 * - Change frontend widget, saved Visitor Buttons settings, chips, WhatsApp handoff, lead emails or weekly summary.
 */

defined('ABSPATH') || exit;

if (!defined('MATEWA_AGENCY_CLIENT_PACKS_OPTION')) {
    define('MATEWA_AGENCY_CLIENT_PACKS_OPTION', 'matewa_agency_client_setup_packs');
}

if (!function_exists('matewa_agency_client_pack_hash_value')) {
    function matewa_agency_client_pack_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_client_pack_normalise_domain')) {
    function matewa_agency_client_pack_normalise_domain($value) {
        $value = strtolower(trim((string) $value));
        $value = preg_replace('/^https?:\/\//i', '', $value);
        $value = preg_replace('/^www\./i', '', (string) $value);
        $value = preg_replace('/\/.*$/', '', (string) $value);
        $value = preg_replace('/[^a-z0-9\.\-]/', '', (string) $value);
        $value = preg_replace('/\.+/', '.', (string) $value);
        return trim((string) $value, '.-');
    }
}

if (!function_exists('matewa_agency_client_pack_clean_phone')) {
    function matewa_agency_client_pack_clean_phone($value) {
        $value = trim((string) $value);
        $value = preg_replace('/[^0-9\+]/', '', $value);
        return sanitize_text_field((string) $value);
    }
}


if (!function_exists('matewa_agency_client_pack_clean_page_url')) {
    function matewa_agency_client_pack_clean_page_url($value, $client_domain = '') {
        $value = trim((string) $value);
        if ('' === $value) {
            return '';
        }

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

        $parts = wp_parse_url($value);
        if (!is_array($parts) || empty($parts['host'])) {
            return '';
        }

        $scheme = isset($parts['scheme']) ? strtolower((string) $parts['scheme']) : 'https';
        if (!in_array($scheme, array('http', 'https'), true)) {
            return '';
        }

        $host = strtolower((string) $parts['host']);
        $host = preg_replace('/^www\./', '', $host);
        $client_domain = matewa_agency_client_pack_normalise_domain($client_domain);
        if ('' !== $client_domain && $host !== $client_domain) {
            return '';
        }

        $path = isset($parts['path']) ? (string) $parts['path'] : '/';
        $path = '/' . ltrim($path, '/');
        $path = preg_replace('#/+#', '/', $path);
        $path = untrailingslashit($path);
        if ('' === $path) {
            $path = '/';
        }

        $blocked_extensions = array('jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'pdf', 'zip', 'mp4', 'mov', 'mp3', 'css', 'js', 'json', 'xml');
        $extension = strtolower(pathinfo($path, PATHINFO_EXTENSION));
        if ('' !== $extension && in_array($extension, $blocked_extensions, true)) {
            return '';
        }

        $blocked_fragments = array('/wp-admin', '/wp-login', '/wp-json', '/feed', '/cart', '/checkout', '/my-account');
        foreach ($blocked_fragments as $blocked_fragment) {
            if (0 === strpos($path, $blocked_fragment)) {
                return '';
            }
        }

        return esc_url_raw($scheme . '://' . $host . ('/' === $path ? '/' : trailingslashit($path)));
    }
}

if (!function_exists('matewa_agency_client_pack_clean_page_item')) {
    function matewa_agency_client_pack_clean_page_item($item, $client_domain = '') {
        $item = is_array($item) ? $item : array();
        $url = matewa_agency_client_pack_clean_page_url($item['url'] ?? '', $client_domain);
        if ('' === $url) {
            return array();
        }

        $title = sanitize_text_field((string) ($item['title'] ?? ''));
        if ('' === $title) {
            $path = wp_parse_url($url, PHP_URL_PATH);
            $path = trim((string) $path, '/');
            $title = '' === $path ? 'Homepage' : ucwords(str_replace(array('-', '_', '/'), ' ', $path));
        }

        return array(
            'url'    => $url,
            'title'  => $title,
            'source' => sanitize_key((string) ($item['source'] ?? 'manual')),
        );
    }
}

if (!function_exists('matewa_agency_client_pack_clean_page_list')) {
    function matewa_agency_client_pack_clean_page_list($items, $client_domain = '', $limit = 30) {
        $items = is_array($items) ? array_values($items) : array();
        $out = array();
        $seen = array();
        $limit = max(1, min(60, absint($limit)));

        foreach ($items as $item) {
            $clean = matewa_agency_client_pack_clean_page_item($item, $client_domain);
            if (empty($clean['url'])) {
                continue;
            }

            $key = strtolower((string) $clean['url']);
            if (isset($seen[$key])) {
                continue;
            }

            $seen[$key] = true;
            $out[] = $clean;
            if (count($out) >= $limit) {
                break;
            }
        }

        return $out;
    }
}

if (!function_exists('matewa_agency_client_pack_select_pages_from_urls')) {
    function matewa_agency_client_pack_select_pages_from_urls($urls, $detected_pages, $client_domain = '') {
        $urls = is_array($urls) ? array_values($urls) : array();
        $detected_pages = matewa_agency_client_pack_clean_page_list($detected_pages, $client_domain, 60);
        $lookup = array();

        foreach ($detected_pages as $page) {
            $lookup[strtolower((string) $page['url'])] = $page;
        }

        $selected = array();
        foreach ($urls as $url) {
            $clean_url = matewa_agency_client_pack_clean_page_url(wp_unslash($url), $client_domain);
            if ('' === $clean_url) {
                continue;
            }

            $key = strtolower((string) $clean_url);
            $selected[] = $lookup[$key] ?? array(
                'url'    => $clean_url,
                'title'  => '',
                'source' => 'manual',
            );
        }

        return matewa_agency_client_pack_clean_page_list($selected, $client_domain, 30);
    }
}

if (!function_exists('matewa_agency_client_pack_page_urls')) {
    function matewa_agency_client_pack_page_urls($pages) {
        $pages = is_array($pages) ? $pages : array();
        $urls = array();
        foreach ($pages as $page) {
            if (is_array($page) && !empty($page['url'])) {
                $urls[] = strtolower((string) $page['url']);
            }
        }
        return array_values(array_unique($urls));
    }
}

if (!function_exists('matewa_agency_client_pack_is_public_scan_host')) {
    function matewa_agency_client_pack_is_public_scan_host($domain) {
        $domain = matewa_agency_client_pack_normalise_domain($domain);
        if ('' === $domain) {
            return false;
        }

        if (in_array($domain, array('localhost', 'local'), true)) {
            return false;
        }

        if (filter_var($domain, FILTER_VALIDATE_IP)) {
            return !filter_var($domain, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) ? false : true;
        }

        if (function_exists('gethostbynamel')) {
            $addresses = @gethostbynamel($domain);
            if (is_array($addresses)) {
                foreach ($addresses as $address) {
                    if (filter_var($address, FILTER_VALIDATE_IP) && !filter_var($address, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
                        return false;
                    }
                }
            }
        }

        return true;
    }
}

if (!function_exists('matewa_agency_client_pack_add_scanned_page')) {
    function matewa_agency_client_pack_add_scanned_page(&$pages, $url, $title, $source, $client_domain) {
        $clean = matewa_agency_client_pack_clean_page_item(array(
            'url'    => $url,
            'title'  => $title,
            'source' => $source,
        ), $client_domain);

        if (empty($clean['url'])) {
            return;
        }

        $key = strtolower((string) $clean['url']);
        if (!isset($pages[$key])) {
            $pages[$key] = $clean;
        }
    }
}

if (!function_exists('matewa_agency_client_pack_remote_url_matches_domain')) {
    function matewa_agency_client_pack_remote_url_matches_domain($url, $client_domain = '') {
        $url = trim((string) $url);
        if ('' === $url) {
            return false;
        }

        $parts = wp_parse_url($url);
        if (!is_array($parts) || empty($parts['host'])) {
            return false;
        }

        $scheme = isset($parts['scheme']) ? strtolower((string) $parts['scheme']) : '';
        if (!in_array($scheme, array('http', 'https'), true)) {
            return false;
        }

        $host = strtolower((string) $parts['host']);
        $host = preg_replace('/^www\./', '', $host);
        $client_domain = matewa_agency_client_pack_normalise_domain($client_domain);

        return '' === $client_domain || hash_equals($client_domain, $host);
    }
}

if (!function_exists('matewa_agency_client_pack_remote_get')) {
    function matewa_agency_client_pack_remote_get($url, $client_domain = '') {
        if (!matewa_agency_client_pack_remote_url_matches_domain($url, $client_domain)) {
            return '';
        }

        $response = wp_remote_get($url, array(
            'timeout'             => 8,
            'redirection'         => 3,
            'limit_response_size' => 524288,
            'reject_unsafe_urls'  => true,
            'user-agent'          => '247ChatMate agency page scanner/' . (defined('MATEWA_VERSION') ? MATEWA_VERSION : '1.0'),
        ));

        if (is_wp_error($response)) {
            return '';
        }

        $code = (int) wp_remote_retrieve_response_code($response);
        if ($code < 200 || $code >= 400) {
            return '';
        }

        $body = wp_remote_retrieve_body($response);
        return is_string($body) ? $body : '';
    }
}

if (!function_exists('matewa_agency_client_pack_scan_pages_for_domain')) {
    function matewa_agency_client_pack_scan_pages_for_domain($domain) {
        $domain = matewa_agency_client_pack_normalise_domain($domain);
        if ('' === $domain) {
            return array('ok' => false, 'pages' => array(), 'message' => 'Add a client domain before scanning pages.');
        }

        if (!matewa_agency_client_pack_is_public_scan_host($domain)) {
            return array('ok' => false, 'pages' => array(), 'message' => 'This domain cannot be scanned safely. Use a public client domain.');
        }

        $pages = array();
        $home_url = esc_url_raw('https://' . $domain . '/');
        matewa_agency_client_pack_add_scanned_page($pages, $home_url, 'Homepage', 'homepage', $domain);

        $sitemap_candidates = array(
            'https://' . $domain . '/sitemap.xml',
            'https://' . $domain . '/sitemap_index.xml',
            'https://' . $domain . '/wp-sitemap-posts-page-1.xml',
        );

        foreach ($sitemap_candidates as $sitemap_url) {
            $xml = matewa_agency_client_pack_remote_get($sitemap_url, $domain);
            if ('' === $xml) {
                continue;
            }

            if (preg_match_all('/<loc>\s*([^<]+)\s*<\/loc>/i', $xml, $matches)) {
                foreach ($matches[1] as $loc_url) {
                    $loc_url = html_entity_decode((string) $loc_url, ENT_QUOTES, 'UTF-8');
                    if (false !== stripos($loc_url, 'sitemap') && preg_match('/\.xml(?:\?|$)/i', $loc_url)) {
                        $nested_xml = matewa_agency_client_pack_remote_get($loc_url, $domain);
                        if ('' !== $nested_xml && preg_match_all('/<loc>\s*([^<]+)\s*<\/loc>/i', $nested_xml, $nested_matches)) {
                            foreach ($nested_matches[1] as $nested_url) {
                                matewa_agency_client_pack_add_scanned_page($pages, html_entity_decode((string) $nested_url, ENT_QUOTES, 'UTF-8'), '', 'sitemap', $domain);
                                if (count($pages) >= 30) {
                                    break 3;
                                }
                            }
                        }
                        continue;
                    }

                    matewa_agency_client_pack_add_scanned_page($pages, $loc_url, '', 'sitemap', $domain);
                    if (count($pages) >= 30) {
                        break 2;
                    }
                }
            }
        }

        $rest_body = matewa_agency_client_pack_remote_get('https://' . $domain . '/wp-json/wp/v2/pages?per_page=30&_fields=link,title', $domain);
        if ('' !== $rest_body) {
            $decoded = json_decode($rest_body, true);
            if (is_array($decoded)) {
                foreach ($decoded as $page) {
                    if (!is_array($page)) {
                        continue;
                    }
                    $title = '';
                    if (isset($page['title']['rendered'])) {
                        $title = wp_strip_all_tags((string) $page['title']['rendered']);
                    }
                    matewa_agency_client_pack_add_scanned_page($pages, $page['link'] ?? '', $title, 'wp_rest', $domain);
                    if (count($pages) >= 30) {
                        break;
                    }
                }
            }
        }

        $home_html = matewa_agency_client_pack_remote_get($home_url, $domain);
        if ('' !== $home_html && preg_match_all('/<a\s+[^>]*href=["\']([^"\']+)["\'][^>]*>(.*?)<\/a>/is', $home_html, $anchor_matches, PREG_SET_ORDER)) {
            foreach ($anchor_matches as $anchor_match) {
                $href = trim(html_entity_decode((string) ($anchor_match[1] ?? ''), ENT_QUOTES, 'UTF-8'));
                if ('' === $href || 0 === strpos($href, '#') || 0 === stripos($href, 'mailto:') || 0 === stripos($href, 'tel:')) {
                    continue;
                }

                if (0 === strpos($href, '/')) {
                    $href = 'https://' . $domain . $href;
                }

                $title = wp_strip_all_tags((string) ($anchor_match[2] ?? ''));
                matewa_agency_client_pack_add_scanned_page($pages, $href, $title, 'homepage_nav', $domain);
                if (count($pages) >= 30) {
                    break;
                }
            }
        }

        $clean_pages = matewa_agency_client_pack_clean_page_list(array_values($pages), $domain, 30);

        return array(
            'ok'      => !empty($clean_pages),
            'pages'   => $clean_pages,
            'message' => !empty($clean_pages) ? sprintf('Found %d public page%s.', count($clean_pages), 1 === count($clean_pages) ? '' : 's') : 'No public pages were discovered. You can still save specific pages manually later.',
        );
    }
}

if (!function_exists('matewa_agency_client_pack_allowed_page_mode')) {
    function matewa_agency_client_pack_allowed_page_mode($value) {
        $value = sanitize_key((string) $value);
        $allowed = array('all_pages', 'homepage', 'specific_pages');
        return in_array($value, $allowed, true) ? $value : 'all_pages';
    }
}

if (!function_exists('matewa_agency_client_pack_page_mode_label')) {
    function matewa_agency_client_pack_page_mode_label($value) {
        $value = matewa_agency_client_pack_allowed_page_mode($value);
        $labels = array(
            'all_pages'      => 'All pages',
            'homepage'       => 'Homepage only',
            'specific_pages' => 'Specific pages later',
        );
        return $labels[$value] ?? 'All pages';
    }
}

if (!function_exists('matewa_agency_client_pack_allowed_chip_mode')) {
    function matewa_agency_client_pack_allowed_chip_mode($value) {
        $value = sanitize_key((string) $value);
        $allowed = array('defaults', 'custom', 'edit_later');
        return in_array($value, $allowed, true) ? $value : 'defaults';
    }
}

if (!function_exists('matewa_agency_client_pack_chip_mode_label')) {
    function matewa_agency_client_pack_chip_mode_label($value) {
        $value = matewa_agency_client_pack_allowed_chip_mode($value);
        $labels = array(
            'defaults'   => 'Default chips',
            'custom'     => 'Saved chips',
            'edit_later' => 'Edit later',
        );
        return $labels[$value] ?? 'Default chips';
    }
}


if (!function_exists('matewa_agency_client_pack_clean_chip_label')) {
    function matewa_agency_client_pack_clean_chip_label($value) {
        $max_lines = defined('MATEWA_CHIP_MAX_LINES') ? (int) MATEWA_CHIP_MAX_LINES : 2;
        $max_line_chars = defined('MATEWA_CHIP_MAX_LINE_CHARS') ? (int) MATEWA_CHIP_MAX_LINE_CHARS : 20;
        $max_total_chars = defined('MATEWA_CHIP_MAX_TOTAL_CHARS') ? (int) MATEWA_CHIP_MAX_TOTAL_CHARS : 34;

        $value = wp_strip_all_tags((string) $value);
        $value = html_entity_decode($value, ENT_QUOTES, 'UTF-8');
        $value = str_replace(array("\r\n", "\r"), "\n", $value);
        $value = str_replace("\t", ' ', $value);

        $raw_lines = preg_split('/\n/u', $value);
        if (!is_array($raw_lines)) {
            $raw_lines = array();
        }

        $clean_lines = array();

        foreach ($raw_lines as $line) {
            if (count($clean_lines) >= max(1, $max_lines)) {
                break;
            }

            $line = (string) $line;
            $line = preg_replace('/^[ ]+/u', '', $line);
            $line = preg_replace('/[ ]+$/u', '', $line);

            if ('' === $line) {
                continue;
            }

            if (function_exists('mb_strlen') && function_exists('mb_substr')) {
                if (mb_strlen($line, 'UTF-8') > $max_line_chars) {
                    $line = mb_substr($line, 0, $max_line_chars, 'UTF-8');
                }
            } elseif (strlen($line) > $max_line_chars) {
                $line = substr($line, 0, $max_line_chars);
            }

            $clean_lines[] = $line;
        }

        $value = implode("\n", $clean_lines);

        if (function_exists('mb_strlen') && function_exists('mb_substr')) {
            if (mb_strlen($value, 'UTF-8') > $max_total_chars) {
                $value = mb_substr($value, 0, $max_total_chars, 'UTF-8');
            }
        } elseif (strlen($value) > $max_total_chars) {
            $value = substr($value, 0, $max_total_chars);
        }

        return sanitize_textarea_field((string) $value);
    }
}

if (!function_exists('matewa_agency_client_pack_clean_chip_labels')) {
    function matewa_agency_client_pack_clean_chip_labels($posted_labels, $default_labels = array()) {
        $posted_labels = is_array($posted_labels) ? array_values($posted_labels) : array();
        $default_labels = is_array($default_labels) ? array_values($default_labels) : array();
        $out = array();
        $max = max(1, min(6, max(count($posted_labels), count($default_labels))));

        for ($i = 0; $i < $max; $i++) {
            $posted = isset($posted_labels[$i]) ? matewa_agency_client_pack_clean_chip_label(wp_unslash($posted_labels[$i])) : '';
            $fallback = isset($default_labels[$i]) ? matewa_agency_client_pack_clean_chip_label($default_labels[$i]) : '';

            if ('' === $posted) {
                $posted = $fallback;
            }

            if ('' !== $posted) {
                $out[] = $posted;
            }
        }

        if (empty($out)) {
            $out = array('Get a quote', 'Pricing', 'Availability', 'Ask a question', 'Book a job', 'Something else');
        }

        return array_values(array_slice($out, 0, 6));
    }
}

if (!function_exists('matewa_agency_client_pack_get_chip_labels_for_vertical')) {
    function matewa_agency_client_pack_get_chip_labels_for_vertical($vertical_key) {
        $vertical_key = sanitize_key((string) $vertical_key);
        $labels = array();

        if (function_exists('matewa_get_vertical_chip_labels')) {
            $labels = (array) matewa_get_vertical_chip_labels($vertical_key);
        }

        if (empty($labels) && function_exists('matewa_get_vertical_config') && function_exists('matewa_catalog_resolve_intent_label')) {
            $config = matewa_get_vertical_config($vertical_key);
            $chips = isset($config['chips']) && is_array($config['chips']) ? $config['chips'] : array();
            foreach ($chips as $intent_key) {
                $labels[] = matewa_catalog_resolve_intent_label((string) $intent_key);
            }
        }

        if (empty($labels)) {
            $labels = array('Get a quote', 'Pricing', 'Availability', 'Ask a question', 'Book a job', 'Something else');
        }

        return matewa_agency_client_pack_clean_chip_labels($labels, $labels);
    }
}

if (!function_exists('matewa_agency_client_pack_get_intent_keys_for_vertical')) {
    function matewa_agency_client_pack_get_intent_keys_for_vertical($vertical_key) {
        $vertical_key = sanitize_key((string) $vertical_key);
        $intent_keys = array();

        if ('' !== $vertical_key && function_exists('matewa_get_vertical_config')) {
            $config = matewa_get_vertical_config($vertical_key);
            $chips = isset($config['chips']) && is_array($config['chips']) ? array_values($config['chips']) : array();
            foreach ($chips as $intent_key) {
                $intent_key = is_string($intent_key) ? trim($intent_key) : '';
                if ('' !== $intent_key) {
                    $intent_keys[] = $intent_key;
                }
            }
        }

        return array_values(array_unique(array_filter($intent_keys)));
    }
}

if (!function_exists('matewa_agency_client_pack_build_chip_override_map')) {
    function matewa_agency_client_pack_build_chip_override_map($vertical_key, $labels) {
        $vertical_key = sanitize_key((string) $vertical_key);
        $labels = is_array($labels) ? array_values($labels) : array();
        $intent_keys = matewa_agency_client_pack_get_intent_keys_for_vertical($vertical_key);
        $map = array();

        foreach (array_slice($labels, 0, 6) as $index => $label) {
            $clean_label = matewa_agency_client_pack_clean_chip_label($label);
            if ('' === $clean_label) {
                continue;
            }

            $intent_key = isset($intent_keys[$index]) ? (string) $intent_keys[$index] : '';
            if ('' === $intent_key) {
                continue;
            }

            $map[$intent_key] = $clean_label;
        }

        return $map;
    }
}

if (!function_exists('matewa_agency_client_pack_get_selector_data')) {
    function matewa_agency_client_pack_get_selector_data() {
        $catalog = function_exists('matewa_get_vertical_catalog_data')
            ? matewa_get_vertical_catalog_data()
            : (function_exists('matewa_get_verticals') ? (array) matewa_get_verticals() : array());

        $verticals = isset($catalog['verticals']) && is_array($catalog['verticals']) ? $catalog['verticals'] : array();
        $categories = isset($catalog['categories']) && is_array($catalog['categories']) ? $catalog['categories'] : array();
        $default_vertical = isset($catalog['default_vertical']) ? sanitize_key((string) $catalog['default_vertical']) : 'general';

        $selector = function_exists('matewa_build_vertical_selector_data')
            ? matewa_build_vertical_selector_data($verticals, $categories)
            : array('categories' => array(), 'flat' => array(), 'vertical_to_category' => array());

        $categories_out = array();
        $flat = isset($selector['flat']) && is_array($selector['flat']) ? $selector['flat'] : array();
        $vertical_to_category = isset($selector['vertical_to_category']) && is_array($selector['vertical_to_category']) ? $selector['vertical_to_category'] : array();
        $selector_categories = isset($selector['categories']) && is_array($selector['categories']) ? $selector['categories'] : array();

        foreach ($selector_categories as $category_key => $category_data) {
            $category_key = sanitize_key((string) $category_key);
            if ('' === $category_key || !is_array($category_data)) {
                continue;
            }

            $category_label = isset($category_data['label']) ? sanitize_text_field((string) $category_data['label']) : ucwords(str_replace('_', ' ', $category_key));
            $options = isset($category_data['options']) && is_array($category_data['options']) ? $category_data['options'] : array();
            $clean_options = array();

            foreach ($options as $vertical_key => $vertical_data) {
                $vertical_key = sanitize_key((string) $vertical_key);
                if ('' === $vertical_key) {
                    continue;
                }

                $label = '';
                if (is_array($vertical_data) && isset($vertical_data['display_label'])) {
                    $label = sanitize_text_field((string) $vertical_data['display_label']);
                }
                if ('' === $label && function_exists('matewa_get_vertical_display_label')) {
                    $label = sanitize_text_field((string) matewa_get_vertical_display_label($vertical_key));
                }
                if ('' === $label) {
                    $label = ucwords(str_replace('_', ' ', $vertical_key));
                }

                $chips = matewa_agency_client_pack_get_chip_labels_for_vertical($vertical_key);

                $clean_options[$vertical_key] = array(
                    'key'           => $vertical_key,
                    'display_label' => $label,
                    'chips'         => $chips,
                );
            }

            if (!empty($clean_options)) {
                $categories_out[$category_key] = array(
                    'key'     => $category_key,
                    'label'   => $category_label,
                    'options' => $clean_options,
                );
            }
        }

        if (empty($categories_out)) {
            $fallback_key = isset($verticals[$default_vertical]) ? $default_vertical : 'general';
            $fallback_label = function_exists('matewa_get_vertical_display_label') ? matewa_get_vertical_display_label($fallback_key) : 'General';
            $categories_out['general'] = array(
                'key'     => 'general',
                'label'   => 'General',
                'options' => array(
                    $fallback_key => array(
                        'key'           => $fallback_key,
                        'display_label' => sanitize_text_field((string) $fallback_label),
                        'chips'         => matewa_agency_client_pack_get_chip_labels_for_vertical($fallback_key),
                    ),
                ),
            );
            $vertical_to_category[$fallback_key] = 'general';
        }

        if (!isset($flat[$default_vertical])) {
            $first_category = reset($categories_out);
            $first_options = is_array($first_category) && isset($first_category['options']) && is_array($first_category['options']) ? $first_category['options'] : array();
            $first_key = !empty($first_options) ? (string) array_key_first($first_options) : 'general';
            $default_vertical = sanitize_key($first_key);
        }

        $default_category = isset($vertical_to_category[$default_vertical]) ? sanitize_key((string) $vertical_to_category[$default_vertical]) : '';
        if ('' === $default_category || !isset($categories_out[$default_category])) {
            foreach ($categories_out as $category_key => $category_data) {
                if (isset($category_data['options'][$default_vertical])) {
                    $default_category = sanitize_key((string) $category_key);
                    break;
                }
            }
        }
        if ('' === $default_category || !isset($categories_out[$default_category])) {
            $default_category = sanitize_key((string) array_key_first($categories_out));
        }

        return array(
            'categories'       => $categories_out,
            'default_category' => $default_category,
            'default_vertical' => $default_vertical,
        );
    }
}

if (!function_exists('matewa_agency_client_pack_resolve_vertical_selection')) {
    function matewa_agency_client_pack_resolve_vertical_selection($category_key, $vertical_key) {
        $selector = matewa_agency_client_pack_get_selector_data();
        $categories = isset($selector['categories']) && is_array($selector['categories']) ? $selector['categories'] : array();

        $category_key = sanitize_key((string) $category_key);
        $vertical_key = sanitize_key((string) $vertical_key);

        if ('' === $category_key || !isset($categories[$category_key])) {
            $category_key = isset($selector['default_category']) ? sanitize_key((string) $selector['default_category']) : '';
        }

        $options = isset($categories[$category_key]['options']) && is_array($categories[$category_key]['options']) ? $categories[$category_key]['options'] : array();

        if ('' === $vertical_key || !isset($options[$vertical_key])) {
            $vertical_key = isset($selector['default_vertical']) && isset($options[$selector['default_vertical']])
                ? sanitize_key((string) $selector['default_vertical'])
                : sanitize_key((string) array_key_first($options));
        }

        $category_label = isset($categories[$category_key]['label']) ? sanitize_text_field((string) $categories[$category_key]['label']) : 'General';
        $vertical_label = isset($options[$vertical_key]['display_label']) ? sanitize_text_field((string) $options[$vertical_key]['display_label']) : 'General';
        $chips = isset($options[$vertical_key]['chips']) && is_array($options[$vertical_key]['chips']) ? $options[$vertical_key]['chips'] : array();
        $chips = matewa_agency_client_pack_clean_chip_labels($chips, $chips);

        return array(
            'category_key'   => $category_key,
            'category_label' => $category_label,
            'vertical_key'   => $vertical_key,
            'vertical_label' => $vertical_label,
            'chips'          => $chips,
        );
    }
}

if (!function_exists('matewa_agency_client_pack_get_records')) {
    function matewa_agency_client_pack_get_records() {
        $records = get_option(MATEWA_AGENCY_CLIENT_PACKS_OPTION, array());

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

        $safe_records = array();

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

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

            $safe_records[] = array(
                'setup_pack_id'     => $pack_id,
                'agency_id'         => isset($record['agency_id']) ? sanitize_key((string) $record['agency_id']) : '',
                'client_business'   => isset($record['client_business']) ? sanitize_text_field((string) $record['client_business']) : '',
                'client_domain'     => isset($record['client_domain']) ? matewa_agency_client_pack_normalise_domain((string) $record['client_domain']) : '',
                'client_admin_email'=> isset($record['client_admin_email']) ? sanitize_email((string) $record['client_admin_email']) : '',
                'whatsapp_number'   => isset($record['whatsapp_number']) ? matewa_agency_client_pack_clean_phone((string) $record['whatsapp_number']) : '',
                'leads_email'       => isset($record['leads_email']) ? sanitize_email((string) $record['leads_email']) : '',
                'industry'          => isset($record['industry']) ? sanitize_text_field((string) $record['industry']) : '',
                'business_category' => isset($record['business_category']) ? sanitize_text_field((string) $record['business_category']) : '',
                'business_category_key' => isset($record['business_category_key']) ? sanitize_key((string) $record['business_category_key']) : '',
                'business_type'     => isset($record['business_type']) ? sanitize_text_field((string) $record['business_type']) : '',
                'business_type_key' => isset($record['business_type_key']) ? sanitize_key((string) $record['business_type_key']) : '',
                'page_mode'         => isset($record['page_mode']) ? matewa_agency_client_pack_allowed_page_mode((string) $record['page_mode']) : 'all_pages',
                'detected_pages'    => isset($record['detected_pages']) ? matewa_agency_client_pack_clean_page_list((array) $record['detected_pages'], isset($record['client_domain']) ? (string) $record['client_domain'] : '', 30) : array(),
                'selected_pages'    => isset($record['selected_pages']) ? matewa_agency_client_pack_clean_page_list((array) $record['selected_pages'], isset($record['client_domain']) ? (string) $record['client_domain'] : '', 30) : array(),
                'chip_mode'         => isset($record['chip_mode']) ? matewa_agency_client_pack_allowed_chip_mode((string) $record['chip_mode']) : 'defaults',
                'visitor_buttons'   => isset($record['visitor_buttons']) ? matewa_agency_client_pack_clean_chip_labels((array) $record['visitor_buttons'], (array) $record['visitor_buttons']) : array(),
                'assigned_bundle_id'=> isset($record['assigned_bundle_id']) ? sanitize_key((string) $record['assigned_bundle_id']) : '',
                'seat_status'       => isset($record['seat_status']) ? sanitize_key((string) $record['seat_status']) : 'assigned',
                'licence_status'    => isset($record['licence_status']) ? sanitize_key((string) $record['licence_status']) : 'draft',
                'expires_at'        => isset($record['expires_at']) ? sanitize_text_field((string) $record['expires_at']) : '',
                'renews_at'         => isset($record['renews_at']) ? sanitize_text_field((string) $record['renews_at']) : '',
                'status'            => isset($record['status']) ? sanitize_key((string) $record['status']) : 'draft',
                '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_client_pack_get_record_by_id')) {
    function matewa_agency_client_pack_get_record_by_id($pack_id) {
        $pack_id = sanitize_key((string) $pack_id);
        if ('' === $pack_id) {
            return array();
        }

        foreach (matewa_agency_client_pack_get_records() as $record) {
            $record_id = isset($record['setup_pack_id']) ? sanitize_key((string) $record['setup_pack_id']) : '';
            if (hash_equals($record_id, $pack_id)) {
                return $record;
            }
        }

        return array();
    }
}

if (!function_exists('matewa_agency_client_pack_release_bundle_seat')) {
    function matewa_agency_client_pack_release_bundle_seat($bundle_id) {
        $bundle_id = sanitize_key((string) $bundle_id);
        if ('' === $bundle_id || !function_exists('matewa_agency_bundle_get_records') || !function_exists('matewa_agency_bundle_store_records')) {
            return false;
        }

        $bundle_records = matewa_agency_bundle_get_records();
        $changed = false;

        foreach ($bundle_records as $index => $bundle) {
            if (!is_array($bundle)) {
                continue;
            }

            $current_id = isset($bundle['bundle_id']) ? sanitize_key((string) $bundle['bundle_id']) : '';
            if (!hash_equals($current_id, $bundle_id)) {
                continue;
            }

            $seats = isset($bundle['seats']) ? absint($bundle['seats']) : 0;
            $used = isset($bundle['used_seats']) ? absint($bundle['used_seats']) : 0;
            $used = max(0, $used - 1);

            $bundle_records[$index]['used_seats'] = $used;
            $bundle_records[$index]['available_seats'] = max(0, $seats - $used);
            $bundle_records[$index]['updated_at'] = time();
            $changed = true;
            break;
        }

        if ($changed) {
            matewa_agency_bundle_store_records($bundle_records);
        }

        return $changed;
    }
}


if (!function_exists('matewa_agency_client_pack_reconcile_bundle_seats')) {
    function matewa_agency_client_pack_reconcile_bundle_seats($client_pack_records = null) {
        if (!function_exists('matewa_agency_bundle_get_records') || !function_exists('matewa_agency_bundle_store_records')) {
            return false;
        }

        $client_pack_records = null === $client_pack_records
            ? matewa_agency_client_pack_get_records()
            : (is_array($client_pack_records) ? array_values($client_pack_records) : array());

        $assigned_counts = array();

        foreach ($client_pack_records as $pack) {
            if (!is_array($pack)) {
                continue;
            }

            $bundle_id = isset($pack['assigned_bundle_id']) ? sanitize_key((string) $pack['assigned_bundle_id']) : '';
            $seat_status = isset($pack['seat_status']) ? sanitize_key((string) $pack['seat_status']) : 'assigned';

            if ('' === $bundle_id || 'assigned' !== $seat_status) {
                continue;
            }

            if (!isset($assigned_counts[$bundle_id])) {
                $assigned_counts[$bundle_id] = 0;
            }

            $assigned_counts[$bundle_id]++;
        }

        $bundle_records = matewa_agency_bundle_get_records();
        if (!is_array($bundle_records)) {
            return false;
        }

        $changed = false;

        foreach ($bundle_records as $index => $bundle) {
            if (!is_array($bundle)) {
                continue;
            }

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

            $seats = isset($bundle['seats']) ? absint($bundle['seats']) : 0;
            $next_used = isset($assigned_counts[$bundle_id]) ? absint($assigned_counts[$bundle_id]) : 0;
            $next_used = max(0, min($seats, $next_used));
            $next_available = max(0, $seats - $next_used);
            $current_used = isset($bundle['used_seats']) ? absint($bundle['used_seats']) : 0;
            $current_available = isset($bundle['available_seats']) ? absint($bundle['available_seats']) : 0;

            if ($current_used !== $next_used || $current_available !== $next_available) {
                $bundle_records[$index]['used_seats'] = $next_used;
                $bundle_records[$index]['available_seats'] = $next_available;
                $bundle_records[$index]['updated_at'] = time();
                $changed = true;
            }
        }

        if ($changed) {
            matewa_agency_bundle_store_records($bundle_records);
        }

        return $changed;
    }
}

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

if (!function_exists('matewa_agency_client_pack_count_records')) {
    function matewa_agency_client_pack_count_records() {
        return count(matewa_agency_client_pack_get_records());
    }
}

if (!function_exists('matewa_agency_client_pack_get_summary')) {
    function matewa_agency_client_pack_get_summary() {
        $records = matewa_agency_client_pack_get_records();
        $ready = 0;
        $draft = 0;
        $needs_attention = 0;
        $assigned = 0;
        $expiring_soon = 0;

        foreach ($records as $record) {
            $status = isset($record['status']) ? sanitize_key((string) $record['status']) : 'draft';
            if ('ready' === $status) {
                $ready++;
            } elseif ('needs_attention' === $status) {
                $needs_attention++;
            } else {
                $draft++;
            }

            if (!empty($record['assigned_bundle_id']) && 'assigned' === ($record['seat_status'] ?? '')) {
                $assigned++;
            }

            $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'           => count($records),
            'ready'           => $ready,
            'draft'           => $draft,
            'needs_attention' => $needs_attention,
            'assigned'        => $assigned,
            'expiring_soon'   => $expiring_soon,
        );
    }
}


if (!function_exists('matewa_agency_client_pack_value_bucket_add')) {
    function matewa_agency_client_pack_value_bucket_add(&$buckets, $field, $value, $pack_id) {
        $field = sanitize_key((string) $field);
        $value = strtolower(trim((string) $value));
        $pack_id = sanitize_key((string) $pack_id);

        if ('' === $field || '' === $value || '' === $pack_id) {
            return;
        }

        if (!isset($buckets[$field])) {
            $buckets[$field] = array();
        }

        if (!isset($buckets[$field][$value])) {
            $buckets[$field][$value] = array();
        }

        $buckets[$field][$value][] = $pack_id;
    }
}

if (!function_exists('matewa_agency_client_pack_get_duplicate_flag_map')) {
    function matewa_agency_client_pack_get_duplicate_flag_map($records = null) {
        $records = null === $records
            ? matewa_agency_client_pack_get_records()
            : (is_array($records) ? array_values($records) : array());

        $flags = array();
        $buckets = array();

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

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

            $flags[$pack_id] = array();
            matewa_agency_client_pack_value_bucket_add($buckets, 'domain', $record['client_domain'] ?? '', $pack_id);
            matewa_agency_client_pack_value_bucket_add($buckets, 'whatsapp', $record['whatsapp_number'] ?? '', $pack_id);
            matewa_agency_client_pack_value_bucket_add($buckets, 'client_admin_email', $record['client_admin_email'] ?? '', $pack_id);
            matewa_agency_client_pack_value_bucket_add($buckets, 'leads_email', $record['leads_email'] ?? '', $pack_id);
        }

        $labels = array(
            'domain'             => 'Possible duplicate domain',
            'whatsapp'           => 'Possible duplicate WhatsApp',
            'client_admin_email' => 'Shared admin email',
            'leads_email'        => 'Shared leads email',
        );

        foreach ($buckets as $field => $values) {
            foreach ($values as $pack_ids) {
                $pack_ids = array_values(array_unique(array_map('sanitize_key', (array) $pack_ids)));
                if (count($pack_ids) < 2) {
                    continue;
                }

                foreach ($pack_ids as $pack_id) {
                    if (!isset($flags[$pack_id])) {
                        $flags[$pack_id] = array();
                    }

                    $flags[$pack_id][] = isset($labels[$field]) ? $labels[$field] : 'Possible duplicate';
                }
            }
        }

        foreach ($flags as $pack_id => $pack_flags) {
            $flags[$pack_id] = array_values(array_unique(array_filter(array_map('sanitize_text_field', (array) $pack_flags))));
        }

        return $flags;
    }
}

if (!function_exists('matewa_agency_client_pack_get_foundation_summary')) {
    function matewa_agency_client_pack_get_foundation_summary($records = null) {
        $records = null === $records
            ? matewa_agency_client_pack_get_records()
            : (is_array($records) ? array_values($records) : array());

        $duplicate_flags = matewa_agency_client_pack_get_duplicate_flag_map($records);
        $total = count($records);
        $ready = 0;
        $needs_review = 0;
        $weekly_ready = 0;
        $json_pending = 0;
        $pdf_review_later = 0;
        $duplicate_pack_count = 0;

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

            $pack_id = isset($record['setup_pack_id']) ? sanitize_key((string) $record['setup_pack_id']) : '';
            $status = isset($record['status']) ? sanitize_key((string) $record['status']) : 'draft';

            if ('ready' === $status) {
                $ready++;
            } else {
                $needs_review++;
            }

            if (isset($record['leads_email']) && is_email((string) $record['leads_email'])) {
                $weekly_ready++;
            }

            if ('' !== $pack_id && !empty($duplicate_flags[$pack_id])) {
                $duplicate_pack_count++;
                $needs_review++;
            }

            $json_pending++;
            $pdf_review_later++;
        }

        return array(
            'total'                => $total,
            'ready'                => $ready,
            'needs_review'         => $needs_review,
            'weekly_ready'         => $weekly_ready,
            'json_pending'         => $json_pending,
            'pdf_review_later'     => $pdf_review_later,
            'duplicate_pack_count' => $duplicate_pack_count,
            'duplicate_flags'      => $duplicate_flags,
        );
    }
}

if (!function_exists('matewa_agency_client_pack_find_available_bundle_index')) {
    function matewa_agency_client_pack_find_available_bundle_index($bundle_records) {
        foreach ((array) $bundle_records as $index => $bundle) {
            if (!is_array($bundle)) {
                continue;
            }

            $valid = !empty($bundle['valid']);
            $enabled = !empty($bundle['local_enabled']);
            $seats = isset($bundle['seats']) ? absint($bundle['seats']) : 0;
            $used = isset($bundle['used_seats']) ? absint($bundle['used_seats']) : 0;

            if ($valid && $enabled && $seats > $used) {
                return $index;
            }
        }

        return -1;
    }
}

if (!function_exists('matewa_agency_client_pack_resolve_status')) {
    function matewa_agency_client_pack_resolve_status($data) {
        $required = array('client_business', 'client_domain', 'client_admin_email', 'whatsapp_number', 'leads_email', 'business_type');

        foreach ($required as $key) {
            if (empty($data[$key])) {
                return 'needs_attention';
            }
        }

        return 'ready';
    }
}

if (!function_exists('matewa_agency_client_pack_handle_admin_action')) {
    function matewa_agency_client_pack_handle_admin_action($post) {
        $post = is_array($post) ? $post : array();
        $action = isset($post['matewa_agency_client_pack_action']) ? sanitize_key((string) wp_unslash($post['matewa_agency_client_pack_action'])) : '';
        $delete_target = isset($post['matewa_agency_client_pack_delete_id']) ? sanitize_key((string) wp_unslash($post['matewa_agency_client_pack_delete_id'])) : '';

        if ('' !== $delete_target) {
            $action = 'delete';
        }

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

        if (!function_exists('matewa_agency_hub_is_active') || !matewa_agency_hub_is_active()) {
            return array('code' => 'client_pack_agency_required', 'message' => 'Agency Hub access is required before managing client setup packs.');
        }

        if ('delete' === $action) {
            if ('' === $delete_target) {
                return array('code' => 'client_pack_not_found', 'message' => 'Client setup pack could not be found.');
            }

            $existing_packs = matewa_agency_client_pack_get_records();
            $next_packs = array();
            $deleted = false;
            $released_bundle_id = '';

            foreach ($existing_packs as $pack) {
                $pack_id = isset($pack['setup_pack_id']) ? sanitize_key((string) $pack['setup_pack_id']) : '';
                if (hash_equals($pack_id, $delete_target)) {
                    $deleted = true;
                    $released_bundle_id = isset($pack['assigned_bundle_id']) ? sanitize_key((string) $pack['assigned_bundle_id']) : '';
                    continue;
                }
                $next_packs[] = $pack;
            }

            if (!$deleted) {
                return array('code' => 'client_pack_not_found', 'message' => 'Client setup pack could not be found.');
            }

            matewa_agency_client_pack_store_records($next_packs);
            if ('' !== $released_bundle_id) {
                matewa_agency_client_pack_release_bundle_seat($released_bundle_id);
            }
            matewa_agency_client_pack_reconcile_bundle_seats($next_packs);

            return array('code' => 'client_pack_deleted', 'message' => 'Client setup pack deleted and one client seat released.');
        }

        if (!in_array($action, array('create', 'save'), true)) {
            return array('code' => 'client_pack_unknown_action', 'message' => 'Unknown client setup pack action.');
        }

        $target_pack_id = isset($post['matewa_agency_client_pack_id']) ? sanitize_key((string) wp_unslash($post['matewa_agency_client_pack_id'])) : '';
        if ('save' === $action && '' === $target_pack_id) {
            return array('code' => 'client_pack_not_found', 'message' => 'Client setup pack could not be found.');
        }

        $client_business = isset($post['matewa_agency_client_business']) ? sanitize_text_field((string) wp_unslash($post['matewa_agency_client_business'])) : '';
        $client_domain = isset($post['matewa_agency_client_domain']) ? matewa_agency_client_pack_normalise_domain((string) wp_unslash($post['matewa_agency_client_domain'])) : '';
        $client_admin_email = isset($post['matewa_agency_client_admin_email']) ? sanitize_email((string) wp_unslash($post['matewa_agency_client_admin_email'])) : '';
        $whatsapp_number = isset($post['matewa_agency_client_whatsapp']) ? matewa_agency_client_pack_clean_phone((string) wp_unslash($post['matewa_agency_client_whatsapp'])) : '';
        $leads_email = isset($post['matewa_agency_client_leads_email']) ? sanitize_email((string) wp_unslash($post['matewa_agency_client_leads_email'])) : '';
        $industry = isset($post['matewa_agency_client_industry']) ? sanitize_text_field((string) wp_unslash($post['matewa_agency_client_industry'])) : '';
        $business_category_key = isset($post['matewa_agency_client_business_category_key']) ? sanitize_key((string) wp_unslash($post['matewa_agency_client_business_category_key'])) : '';
        $business_type_key = isset($post['matewa_agency_client_business_type_key']) ? sanitize_key((string) wp_unslash($post['matewa_agency_client_business_type_key'])) : '';
        $vertical_selection = matewa_agency_client_pack_resolve_vertical_selection($business_category_key, $business_type_key);
        $business_category_key = $vertical_selection['category_key'];
        $business_category = $vertical_selection['category_label'];
        $business_type_key = $vertical_selection['vertical_key'];
        $business_type = $vertical_selection['vertical_label'];
        $default_chip_labels = $vertical_selection['chips'];
        $posted_chip_labels = isset($post['matewa_agency_client_chip_labels']) && is_array($post['matewa_agency_client_chip_labels']) ? $post['matewa_agency_client_chip_labels'] : array();
        $visitor_buttons = matewa_agency_client_pack_clean_chip_labels($posted_chip_labels, $default_chip_labels);
        $page_mode = isset($post['matewa_agency_client_page_mode']) ? matewa_agency_client_pack_allowed_page_mode((string) wp_unslash($post['matewa_agency_client_page_mode'])) : 'all_pages';
        $chip_mode = 'custom';

        if ('' === $industry) {
            $industry = $business_category;
        }

        if ('' === $client_business || '' === $client_domain || '' === $client_admin_email || '' === $whatsapp_number || '' === $leads_email || '' === $business_type) {
            return array('code' => 'client_pack_missing_fields', 'message' => 'Complete business name, domain, Client admin email, WhatsApp mobile/cell number, Client leads email and business type.');
        }

        if (!is_email($client_admin_email)) {
            return array('code' => 'client_pack_invalid_admin_email', 'message' => 'Enter a valid Client admin email address for this client.');
        }

        if (!is_email($leads_email)) {
            return array('code' => 'client_pack_invalid_email', 'message' => 'Enter a valid Client leads email address for this client.');
        }

        $existing_packs = matewa_agency_client_pack_get_records();
        $existing_index = -1;
        foreach ($existing_packs as $index => $pack) {
            $pack_id = isset($pack['setup_pack_id']) ? sanitize_key((string) $pack['setup_pack_id']) : '';
            if ('save' === $action && hash_equals($pack_id, $target_pack_id)) {
                $existing_index = (int) $index;
                continue;
            }
            if (isset($pack['client_domain']) && hash_equals((string) $pack['client_domain'], $client_domain)) {
                return array('code' => 'client_pack_duplicate_domain', 'message' => 'A setup pack already exists for this client domain.');
            }
        }

        if ('save' === $action && $existing_index < 0) {
            return array('code' => 'client_pack_not_found', 'message' => 'Client setup pack could not be found.');
        }

        $existing_detected_pages = array();
        if ('save' === $action && $existing_index >= 0 && isset($existing_packs[$existing_index]['detected_pages']) && is_array($existing_packs[$existing_index]['detected_pages'])) {
            $existing_detected_pages = matewa_agency_client_pack_clean_page_list($existing_packs[$existing_index]['detected_pages'], $client_domain, 30);
        }
        $posted_selected_page_urls = isset($post['matewa_agency_client_specific_pages']) && is_array($post['matewa_agency_client_specific_pages'])
            ? $post['matewa_agency_client_specific_pages']
            : array();
        $selected_pages = matewa_agency_client_pack_select_pages_from_urls($posted_selected_page_urls, $existing_detected_pages, $client_domain);

        $now = time();
        $data = array(
            'client_business'   => $client_business,
            'client_domain'     => $client_domain,
            'client_admin_email'=> $client_admin_email,
            'whatsapp_number'   => $whatsapp_number,
            'leads_email'       => $leads_email,
            'industry'          => $industry,
            'business_category' => $business_category,
            'business_category_key' => $business_category_key,
            'business_type'     => $business_type,
            'business_type_key' => $business_type_key,
            'page_mode'         => $page_mode,
            'detected_pages'    => $existing_detected_pages,
            'selected_pages'    => $selected_pages,
            'chip_mode'         => $chip_mode,
            'visitor_buttons'   => $visitor_buttons,
        );

        if ('save' === $action) {
            $existing = $existing_packs[$existing_index];
            $existing_packs[$existing_index] = array_merge($existing, $data, array(
                'status'     => matewa_agency_client_pack_resolve_status($data),
                'updated_at' => $now,
            ));
            matewa_agency_client_pack_store_records($existing_packs);
            return array('code' => 'client_pack_saved', 'message' => 'Client setup pack updated.');
        }

        $bundle_records = function_exists('matewa_agency_bundle_get_records') ? matewa_agency_bundle_get_records() : array();
        $bundle_index = matewa_agency_client_pack_find_available_bundle_index($bundle_records);

        if ($bundle_index < 0 || empty($bundle_records[$bundle_index]) || !is_array($bundle_records[$bundle_index])) {
            return array('code' => 'client_pack_no_seats', 'message' => 'No active client seats are available. Add or enable an agency bundle before creating a setup pack.');
        }

        $bundle = $bundle_records[$bundle_index];
        $bundle_id = isset($bundle['bundle_id']) ? sanitize_key((string) $bundle['bundle_id']) : '';
        $bundle_used = isset($bundle['used_seats']) ? absint($bundle['used_seats']) : 0;
        $bundle_seats = isset($bundle['seats']) ? absint($bundle['seats']) : 0;
        $agency_summary = function_exists('matewa_agency_entitlement_get_summary') ? matewa_agency_entitlement_get_summary() : array();
        $agency_summary = is_array($agency_summary) ? $agency_summary : array();
        $agency_id = isset($agency_summary['agency_id']) ? sanitize_key((string) $agency_summary['agency_id']) : '';
        $pack_id = 'pack_' . substr(matewa_agency_client_pack_hash_value($agency_id . '|' . $client_domain . '|' . $now), 0, 12);

        $record = array_merge(array(
            'setup_pack_id'     => $pack_id,
            'agency_id'         => $agency_id,
            'assigned_bundle_id'=> $bundle_id,
            'seat_status'       => 'assigned',
            'licence_status'    => 'draft',
            'expires_at'        => isset($bundle['expires_at']) ? sanitize_text_field((string) $bundle['expires_at']) : '',
            'renews_at'         => isset($bundle['renews_at']) ? sanitize_text_field((string) $bundle['renews_at']) : '',
            'status'            => matewa_agency_client_pack_resolve_status($data),
            'created_at'        => $now,
            'updated_at'        => $now,
        ), $data);

        $existing_packs[] = $record;
        matewa_agency_client_pack_store_records($existing_packs);

        $bundle_records[$bundle_index]['used_seats'] = min($bundle_seats, $bundle_used + 1);
        $bundle_records[$bundle_index]['available_seats'] = max(0, $bundle_seats - absint($bundle_records[$bundle_index]['used_seats']));
        $bundle_records[$bundle_index]['updated_at'] = $now;

        if (function_exists('matewa_agency_bundle_store_records')) {
            matewa_agency_bundle_store_records($bundle_records);
        }

        return array('code' => 'client_pack_created', 'message' => 'Client setup pack created and one client seat assigned.');
    }
}


if (!function_exists('matewa_agency_client_pack_build_export_payload')) {
    function matewa_agency_client_pack_build_export_payload($record) {
        $record = is_array($record) ? $record : array();
        $visitor_buttons = array();
        $button_labels = isset($record['visitor_buttons']) && is_array($record['visitor_buttons']) ? array_values($record['visitor_buttons']) : array();

        $business_type_key_for_chips = isset($record['business_type_key']) ? sanitize_key((string) $record['business_type_key']) : '';
        $intent_keys_for_chips = matewa_agency_client_pack_get_intent_keys_for_vertical($business_type_key_for_chips);
        foreach (array_slice($button_labels, 0, 6) as $index => $label) {
            $intent_key = isset($intent_keys_for_chips[$index]) ? (string) $intent_keys_for_chips[$index] : '';
            $visitor_button = array(
                'position' => ((int) $index) + 1,
                'label'    => matewa_agency_client_pack_clean_chip_label($label),
            );
            if ('' !== $intent_key) {
                $visitor_button['intent_key'] = $intent_key;
            }
            $visitor_buttons[] = $visitor_button;
        }

        $page_mode = isset($record['page_mode']) ? matewa_agency_client_pack_allowed_page_mode((string) $record['page_mode']) : 'all_pages';
        $chip_mode = isset($record['chip_mode']) ? matewa_agency_client_pack_allowed_chip_mode((string) $record['chip_mode']) : 'custom';
        $status = isset($record['status']) ? sanitize_key((string) $record['status']) : 'draft';
        $setup_pack_id = isset($record['setup_pack_id']) ? sanitize_key((string) $record['setup_pack_id']) : '';
        $agency_id = isset($record['agency_id']) ? sanitize_key((string) $record['agency_id']) : '';
        $client_domain = isset($record['client_domain']) ? matewa_agency_client_pack_normalise_domain((string) $record['client_domain']) : '';
        $client_business = isset($record['client_business']) ? sanitize_text_field((string) $record['client_business']) : '';
        $client_admin_email = isset($record['client_admin_email']) ? sanitize_email((string) $record['client_admin_email']) : '';
        $client_leads_email = isset($record['leads_email']) ? sanitize_email((string) $record['leads_email']) : '';
        $whatsapp_number = isset($record['whatsapp_number']) ? matewa_agency_client_pack_clean_phone((string) $record['whatsapp_number']) : '';
        $business_category_key = isset($record['business_category_key']) ? sanitize_key((string) $record['business_category_key']) : '';
        $business_category = isset($record['business_category']) ? sanitize_text_field((string) $record['business_category']) : '';
        $business_type_key = isset($record['business_type_key']) ? sanitize_key((string) $record['business_type_key']) : '';
        $business_type = isset($record['business_type']) ? sanitize_text_field((string) $record['business_type']) : '';
        $industry = isset($record['industry']) ? sanitize_text_field((string) $record['industry']) : '';

        $chip_overrides = array();
        if ('' !== $business_type_key && !empty($button_labels)) {
            $chip_override_map = matewa_agency_client_pack_build_chip_override_map($business_type_key, $button_labels);
            if (!empty($chip_override_map)) {
                $chip_overrides[$business_type_key] = $chip_override_map;
            }
        }

        $detected_pages = isset($record['detected_pages']) && is_array($record['detected_pages']) ? matewa_agency_client_pack_clean_page_list($record['detected_pages'], $client_domain, 30) : array();
        $specific_pages = isset($record['selected_pages']) && is_array($record['selected_pages']) ? matewa_agency_client_pack_clean_page_list($record['selected_pages'], $client_domain, 30) : array();
        $widget_display_mode = 'all';
        $widget_include_homepage = '0';
        if ('homepage' === $page_mode) {
            $widget_display_mode = 'selected';
            $widget_include_homepage = '1';
        } elseif ('specific_pages' === $page_mode) {
            $widget_display_mode = 'selected';
            $widget_include_homepage = '0';
        }

        return array(
            'export_type'    => '247chatmate_agency_client_setup_pack',
            'schema_version' => '1.2',
            'checkpoint'     => 'AGENCYCLIENTSEATENTITLEMENTIMPORT1',
            'generated_at'   => gmdate('c'),
            'generated_by'   => array(
                'site_name' => sanitize_text_field((string) get_bloginfo('name')),
                'site_url'  => esc_url_raw((string) home_url('/')),
            ),
            'agency_source' => array(
                'agency_id'                    => $agency_id,
                'agency_admin_email'           => sanitize_email((string) get_option('matewa_marketing_email', get_option('admin_email'))),
                'agency_support_email'         => sanitize_email((string) get_option('matewa_leads_email', get_option('admin_email'))),
                'source_site_url'              => esc_url_raw((string) home_url('/')),
                'master_licence_exported'      => false,
                'central_storage_required'     => false,
                'client_site_becomes_source'   => true,
                'note'                         => 'This export is a portable setup payload. Agency master licence keys are intentionally not included.',
            ),
            'client_target' => array(
                'setup_pack_id' => $setup_pack_id,
                'domain'        => $client_domain,
                'site_url_hint' => '' !== $client_domain ? esc_url_raw('https://' . $client_domain . '/') : '',
                'business_name' => $client_business,
                'status'        => $status,
                'created_at'    => isset($record['created_at']) ? (int) $record['created_at'] : 0,
                'updated_at'    => isset($record['updated_at']) ? (int) $record['updated_at'] : 0,
            ),
            'client_site_storage' => array(
                'intended_location'     => 'end_user_wordpress_site',
                'storage_strategy'      => 'import_into_local_wordpress_options',
                'source_of_truth_after_import' => 'client_site_plugin_options',
                'central_json_dependency' => false,
                'import_checkpoint'     => 'AGENCYREMOTESENDINGWIDGETSCOPE1',
                'audit_option_hint'     => 'matewa_agency_imported_setup_pack_meta',
                'payload_option_hint'   => 'matewa_agency_imported_setup_pack_payload',
            ),
            'routing' => array(
                'client_admin_email' => $client_admin_email,
                'client_leads_email' => $client_leads_email,
                'whatsapp_number'    => $whatsapp_number,
            ),
            'business_profile' => array(
                'industry'              => $industry,
                'business_category_key' => $business_category_key,
                'business_category'     => $business_category,
                'business_type_key'     => $business_type_key,
                'business_type'         => $business_type,
            ),
            'placement' => array(
                'page_mode'       => $page_mode,
                'page_mode_label' => matewa_agency_client_pack_page_mode_label($page_mode),
                'specific_pages'  => $specific_pages,
                'detected_pages'  => $detected_pages,
                'note'            => !empty($specific_pages) ? 'Specific page URLs were selected by the agency and should be resolved on the client WordPress site during import.' : 'Specific page URLs can be scanned and selected from the Agency Hub before export.',
            ),
            'remote_sending' => array(
                'scope_source' => 'agency_client_setup_pack',
                'uses_frontend_widget_scope' => true,
                'does_not_change_agency_site_widget' => true,
                'client_widget_scope' => array(
                    'enabled' => '1',
                    'display_mode' => $widget_display_mode,
                    'include_homepage' => $widget_include_homepage,
                    'page_mode' => $page_mode,
                    'page_mode_label' => matewa_agency_client_pack_page_mode_label($page_mode),
                    'specific_pages' => $specific_pages,
                    'detected_pages' => $detected_pages,
                    'pending_page_urls' => array_values(array_filter(array_map(static function ($page) {
                        return is_array($page) && isset($page['url']) ? esc_url_raw((string) $page['url']) : '';
                    }, $specific_pages))),
                ),
                'transport' => array(
                    'route' => 'one_time_setup_key_remote_push',
                    'requires_installed_client_plugin' => true,
                    'requires_https' => true,
                    'wordpress_admin_password_required' => false,
                    'licence_activation_included' => false,
                ),
            ),
            'visitor_buttons' => array(
                'mode'    => $chip_mode,
                'buttons' => $visitor_buttons,
            ),
            'client_option_map' => array(
                'matewa_business_name'              => $client_business,
                'matewa_number'                     => $whatsapp_number,
                'matewa_marketing_email'            => $client_admin_email,
                'matewa_leads_email'                => $client_leads_email,
                'matewa_industry'                   => $industry,
                'matewa_vertical_category_selected' => $business_category_key,
                'matewa_vertical_selected'          => $business_type_key,
                'matewa_chip_label_overrides'       => $chip_overrides,
                'matewa_widget_settings'            => array(
                    'display_mode' => $widget_display_mode,
                    'include_homepage' => $widget_include_homepage,
                    'agency_page_mode' => $page_mode,
                    'agency_placement_pending' => ('specific_pages' === $page_mode && empty($specific_pages)),
                    'agency_placement_note' => !empty($specific_pages) ? 'Specific page URLs selected by the agency setup pack.' : ('specific_pages' === $page_mode ? 'Specific pages requested, but no page URLs selected yet. Keep placement pending.' : 'Placement mapped from agency setup pack.'),
                    'pending_page_urls' => array_values(array_filter(array_map(static function ($page) {
                        return is_array($page) && isset($page['url']) ? esc_url_raw((string) $page['url']) : '';
                    }, $specific_pages))),
                    'pending_page_targets' => $specific_pages,
                ),
            ),
            'seat' => array(
                'assigned_bundle_id' => isset($record['assigned_bundle_id']) ? sanitize_key((string) $record['assigned_bundle_id']) : '',
                'seat_status'        => isset($record['seat_status']) ? sanitize_key((string) $record['seat_status']) : 'assigned',
                'licence_status'     => isset($record['licence_status']) ? sanitize_key((string) $record['licence_status']) : 'draft',
                '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']) : '',
                'client_licence_key_included' => false,
            ),
            'client_entitlement' => array(
                'agency_managed' => true,
                'status' => 'active',
                'mode' => 'agency_client_seat',
                'assigned_bundle_id' => isset($record['assigned_bundle_id']) ? sanitize_key((string) $record['assigned_bundle_id']) : '',
                'seat_status' => isset($record['seat_status']) ? sanitize_key((string) $record['seat_status']) : 'assigned',
                'licence_status' => 'agency_managed',
                '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']) : '',
                'client_licence_key_included' => false,
                'master_licence_exported' => false,
                'note' => 'This client is covered by the assigned agency bundle seat. No agency master licence key is exported.',
            ),
            'compatibility' => array(
                'minimum_import_schema' => '1.0',
                'current_export_schema' => '1.2',
                'backwards_compatible'  => true,
                'unknown_fields_policy' => 'ignore_unknown_preserve_payload',
            ),
            'import_notes' => array(
                'This JSON is designed to be imported into the end-user/client WordPress plugin installation.',
                'After import, the client site should store and run from its own local plugin options, not from the agency website.',
                'It does not install the widget, activate a paid client licence, or expose the agency master licence key.',
                'Client setup import remains a separate locked checkpoint.',
            ),
        );
    }
}

if (!function_exists('matewa_agency_client_pack_export_filename')) {
    function matewa_agency_client_pack_export_filename($record) {
        $record = is_array($record) ? $record : array();
        $domain = isset($record['client_domain']) ? matewa_agency_client_pack_normalise_domain((string) $record['client_domain']) : '';
        $pack_id = isset($record['setup_pack_id']) ? sanitize_key((string) $record['setup_pack_id']) : '';
        $safe_name = '' !== $domain ? $domain : ('' !== $pack_id ? $pack_id : 'client');
        $safe_name = strtolower((string) $safe_name);
        $safe_name = preg_replace('/[^a-z0-9]+/', '-', $safe_name);
        $safe_name = trim((string) $safe_name, '-');

        if ('' === $safe_name) {
            $safe_name = 'client';
        }

        return '247chatmate-client-site-setup-' . $safe_name . '-' . gmdate('Ymd-His') . '.json';
    }
}

if (!function_exists('matewa_agency_client_pack_export_url')) {
    function matewa_agency_client_pack_export_url($pack_id) {
        $pack_id = sanitize_key((string) $pack_id);
        if ('' === $pack_id) {
            return '';
        }

        $url = add_query_arg(
            array(
                'action'  => 'matewa_agency_export_client_setup_pack',
                'pack_id' => $pack_id,
            ),
            admin_url('admin-post.php')
        );

        return wp_nonce_url($url, 'matewa_agency_client_pack_export_' . $pack_id);
    }
}


if (!function_exists('matewa_agency_client_pack_scan_pages_url')) {
    function matewa_agency_client_pack_scan_pages_url($pack_id) {
        $pack_id = sanitize_key((string) $pack_id);
        if ('' === $pack_id) {
            return '';
        }

        $url = add_query_arg(
            array(
                'action'  => 'matewa_agency_scan_client_pages',
                'pack_id' => $pack_id,
            ),
            admin_url('admin-post.php')
        );

        return wp_nonce_url($url, 'matewa_agency_client_pack_scan_pages_' . $pack_id);
    }
}

if (!function_exists('matewa_agency_client_pack_scan_redirect')) {
    function matewa_agency_client_pack_scan_redirect($notice_code, $pack_id = '') {
        $args = array(
            'page'                              => '247chatmate',
            'matewa_saved_section'             => 'agency',
            'matewa_agency_client_pack_notice' => sanitize_key((string) $notice_code),
        );

        $pack_id = sanitize_key((string) $pack_id);
        if ('' !== $pack_id) {
            $args['matewa_agency_edit_pack'] = $pack_id;
        }

        wp_safe_redirect(add_query_arg($args, admin_url('admin.php')) . '#matewa-agency-client-pack-editor');
        exit;
    }
}

if (!function_exists('matewa_agency_client_pack_handle_page_scan')) {
    function matewa_agency_client_pack_handle_page_scan() {
        if (!is_admin() || !current_user_can('manage_options')) {
            wp_die(esc_html__('You do not have permission to scan client pages.', '247chatmate'));
        }

        $pack_id = isset($_GET['pack_id']) ? sanitize_key((string) wp_unslash($_GET['pack_id'])) : '';
        if ('' === $pack_id) {
            matewa_agency_client_pack_scan_redirect('client_pack_not_found');
        }

        check_admin_referer('matewa_agency_client_pack_scan_pages_' . $pack_id);

        if (!function_exists('matewa_agency_hub_is_active') || !matewa_agency_hub_is_active()) {
            matewa_agency_client_pack_scan_redirect('client_pack_agency_required', $pack_id);
        }

        $records = matewa_agency_client_pack_get_records();
        $found_index = -1;
        foreach ($records as $index => $record) {
            $record_id = isset($record['setup_pack_id']) ? sanitize_key((string) $record['setup_pack_id']) : '';
            if (hash_equals($record_id, $pack_id)) {
                $found_index = (int) $index;
                break;
            }
        }

        if ($found_index < 0) {
            matewa_agency_client_pack_scan_redirect('client_pack_not_found', $pack_id);
        }

        $domain = isset($records[$found_index]['client_domain']) ? matewa_agency_client_pack_normalise_domain((string) $records[$found_index]['client_domain']) : '';
        $scan = matewa_agency_client_pack_scan_pages_for_domain($domain);
        $pages = isset($scan['pages']) && is_array($scan['pages']) ? matewa_agency_client_pack_clean_page_list($scan['pages'], $domain, 30) : array();

        if (empty($pages)) {
            matewa_agency_client_pack_scan_redirect('client_pack_pages_scan_empty', $pack_id);
        }

        $existing_selected = isset($records[$found_index]['selected_pages']) && is_array($records[$found_index]['selected_pages']) ? $records[$found_index]['selected_pages'] : array();
        $existing_selected_urls = matewa_agency_client_pack_page_urls($existing_selected);
        $new_selected = array();
        if (!empty($existing_selected_urls)) {
            $new_selected = matewa_agency_client_pack_select_pages_from_urls($existing_selected_urls, $pages, $domain);
        }

        $records[$found_index]['detected_pages'] = $pages;
        $records[$found_index]['selected_pages'] = $new_selected;
        $records[$found_index]['page_scan'] = array(
            'scanned_at' => time(),
            'count'      => count($pages),
            'source'     => 'agency_dashboard',
        );
        $records[$found_index]['updated_at'] = time();

        matewa_agency_client_pack_store_records($records);
        matewa_agency_client_pack_scan_redirect('client_pack_pages_scanned', $pack_id);
    }
}
add_action('admin_post_matewa_agency_scan_client_pages', 'matewa_agency_client_pack_handle_page_scan');

if (!function_exists('matewa_agency_client_pack_export_redirect')) {
    function matewa_agency_client_pack_export_redirect($notice_code) {
        $notice_code = sanitize_key((string) $notice_code);
        $redirect = add_query_arg(
            array(
                'page'                             => '247chatmate',
                'matewa_saved_section'             => 'agency',
                'matewa_agency_client_pack_notice' => $notice_code,
            ),
            admin_url('admin.php')
        );

        wp_safe_redirect($redirect . '#matewa-agency-client-packs');
        exit;
    }
}

if (!function_exists('matewa_agency_client_pack_handle_export_download')) {
    function matewa_agency_client_pack_handle_export_download() {
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('You do not have permission to export this setup pack.', '247chatmate'));
        }

        $pack_id = isset($_GET['pack_id']) ? sanitize_key((string) wp_unslash($_GET['pack_id'])) : '';
        if ('' === $pack_id) {
            matewa_agency_client_pack_export_redirect('client_pack_export_not_found');
        }

        check_admin_referer('matewa_agency_client_pack_export_' . $pack_id);

        if (!function_exists('matewa_agency_hub_is_active') || !matewa_agency_hub_is_active()) {
            matewa_agency_client_pack_export_redirect('client_pack_agency_required');
        }

        $record = matewa_agency_client_pack_get_record_by_id($pack_id);
        if (empty($record) || !is_array($record)) {
            matewa_agency_client_pack_export_redirect('client_pack_export_not_found');
        }

        $payload = matewa_agency_client_pack_build_export_payload($record);
        $json = wp_json_encode($payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        if (!is_string($json) || '' === $json) {
            matewa_agency_client_pack_export_redirect('client_pack_export_failed');
        }

        if (function_exists('nocache_headers')) {
            nocache_headers();
        }

        while (ob_get_level() > 0) {
            ob_end_clean();
        }

        header('Content-Type: application/json; charset=utf-8');
        header('Content-Disposition: attachment; filename="' . matewa_agency_client_pack_export_filename($record) . '"');
        header('X-Content-Type-Options: nosniff');
        echo $json;
        exit;
    }
}

add_action('admin_post_matewa_agency_export_client_setup_pack', 'matewa_agency_client_pack_handle_export_download');

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

        $messages = array(
            'client_pack_created'          => 'Client setup pack created and one client seat assigned.',
            'client_pack_saved'            => 'Client setup pack updated.',
            'client_pack_deleted'          => 'Client setup pack deleted and one client seat released.',
            'client_pack_not_found'        => 'Client setup pack could not be found.',
            'client_pack_missing_fields'   => 'Complete business name, domain, Client admin email, WhatsApp mobile/cell number, Client leads email and business type.',
            'client_pack_invalid_admin_email' => 'Enter a valid Client admin email address for this client.',
            'client_pack_invalid_email'    => 'Enter a valid Client leads email address for this client.',
            'client_pack_duplicate_domain' => 'A setup pack already exists for this client domain.',
            'client_pack_no_seats'         => 'No active client seats are available. Add or enable an agency bundle before creating a setup pack.',
            'client_pack_agency_required'  => 'Agency Hub access is required before creating client setup packs.',
            'client_pack_export_not_found' => 'Client setup pack export could not be found.',
            'client_pack_export_failed'    => 'Client setup pack export could not be generated. Try again after saving the setup pack.',
            'client_pack_pages_scanned'     => 'Client pages scanned. Review and tick the pages to include, then save the setup pack.',
            'client_pack_pages_scan_empty'  => 'No public pages were discovered. Check the domain or add page details manually later.',
        );

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