<?php
/**
 * 247ChatMate — Agency Hub overview and bundle licence intake
 * Checkpoint: AGENCYCLIENTPACKROWACTIONSLOCK1
 *
 * Purpose:
 * - Render Agency Hub overview, bundle licence purchase links and masked bundle records.
 * - Allow approved agencies to add/recheck/pause paid LemonSqueezy bundle licences.
 * - Render Agency Hub overview, bundle licence purchase links, masked bundle records and manual client setup packs.
 * - Duplicate the Visitor Buttons category/business-type/chip data into client setup packs only.
 * - Add aligned 3x2 chip summaries plus edit/delete row actions for manual setup packs.
 * - Capture separate client admin and client leads email addresses for later routing/reporting.
 *
 * Does not:
 * - Export/import setup JSON.
 * - Install anything on client sites.
 * - Change frontend widget, saved Visitor Buttons settings, chips, WhatsApp handoff, lead emails or weekly summary.
 */

defined('ABSPATH') || exit;

$matewa_agency_summary = function_exists('matewa_agency_entitlement_get_summary')
    ? matewa_agency_entitlement_get_summary()
    : [];
$matewa_agency_summary = is_array($matewa_agency_summary) ? $matewa_agency_summary : [];

$matewa_agency_bundle_records = function_exists('matewa_agency_bundle_get_records')
    ? matewa_agency_bundle_get_records()
    : [];
$matewa_agency_bundle_records = is_array($matewa_agency_bundle_records) ? $matewa_agency_bundle_records : [];

$matewa_agency_bundle_summary = function_exists('matewa_agency_bundle_get_seat_summary')
    ? matewa_agency_bundle_get_seat_summary()
    : [];
$matewa_agency_bundle_summary = is_array($matewa_agency_bundle_summary) ? $matewa_agency_bundle_summary : [];

$matewa_agency_bundle_plans = function_exists('matewa_agency_bundle_plan_map')
    ? matewa_agency_bundle_plan_map()
    : [];
$matewa_agency_bundle_plans = is_array($matewa_agency_bundle_plans) ? $matewa_agency_bundle_plans : [];

$matewa_agency_client_pack_records = function_exists('matewa_agency_client_pack_get_records')
    ? matewa_agency_client_pack_get_records()
    : [];
$matewa_agency_client_pack_records = is_array($matewa_agency_client_pack_records) ? $matewa_agency_client_pack_records : [];

$matewa_agency_client_pack_summary = function_exists('matewa_agency_client_pack_get_summary')
    ? matewa_agency_client_pack_get_summary()
    : [];
$matewa_agency_client_pack_summary = is_array($matewa_agency_client_pack_summary) ? $matewa_agency_client_pack_summary : [];

$matewa_agency_foundation_summary = function_exists('matewa_agency_client_pack_get_foundation_summary')
    ? matewa_agency_client_pack_get_foundation_summary($matewa_agency_client_pack_records)
    : [];
$matewa_agency_foundation_summary = is_array($matewa_agency_foundation_summary) ? $matewa_agency_foundation_summary : [];
$matewa_agency_client_duplicate_flags = isset($matewa_agency_foundation_summary['duplicate_flags']) && is_array($matewa_agency_foundation_summary['duplicate_flags'])
    ? $matewa_agency_foundation_summary['duplicate_flags']
    : (function_exists('matewa_agency_client_pack_get_duplicate_flag_map') ? matewa_agency_client_pack_get_duplicate_flag_map($matewa_agency_client_pack_records) : []);
$matewa_agency_duplicate_pack_count = isset($matewa_agency_foundation_summary['duplicate_pack_count']) ? absint($matewa_agency_foundation_summary['duplicate_pack_count']) : 0;
$matewa_agency_json_pending_count = isset($matewa_agency_foundation_summary['json_pending']) ? absint($matewa_agency_foundation_summary['json_pending']) : count($matewa_agency_client_pack_records);
$matewa_agency_pdf_review_later_count = isset($matewa_agency_foundation_summary['pdf_review_later']) ? absint($matewa_agency_foundation_summary['pdf_review_later']) : count($matewa_agency_client_pack_records);
$matewa_agency_weekly_ready_count = isset($matewa_agency_foundation_summary['weekly_ready']) ? absint($matewa_agency_foundation_summary['weekly_ready']) : 0;

$matewa_agency_admin_email = sanitize_email((string) get_option('matewa_agency_admin_email', ''));
$matewa_agency_roundup_email = sanitize_email((string) get_option('matewa_agency_roundup_email', ''));
$matewa_agency_routing_ready = is_email($matewa_agency_admin_email) && is_email($matewa_agency_roundup_email);

$matewa_agency_name = isset($matewa_agency_summary['agency_name']) && '' !== trim((string) $matewa_agency_summary['agency_name'])
    ? sanitize_text_field((string) $matewa_agency_summary['agency_name'])
    : 'Agency account';
$matewa_agency_id = isset($matewa_agency_summary['agency_id']) ? sanitize_key((string) $matewa_agency_summary['agency_id']) : '';
$matewa_agency_status = isset($matewa_agency_summary['status']) && '' !== trim((string) $matewa_agency_summary['status'])
    ? sanitize_key((string) $matewa_agency_summary['status'])
    : 'active';

$matewa_agency_own_site_client_seats = isset($matewa_agency_summary['client_seats']) ? absint($matewa_agency_summary['client_seats']) : 0;
$matewa_agency_client_seats = isset($matewa_agency_bundle_summary['total']) ? absint($matewa_agency_bundle_summary['total']) : 0;
$matewa_agency_used_seats = isset($matewa_agency_bundle_summary['used']) ? absint($matewa_agency_bundle_summary['used']) : 0;
$matewa_agency_available_seats = isset($matewa_agency_bundle_summary['available']) ? absint($matewa_agency_bundle_summary['available']) : max(0, $matewa_agency_client_seats - $matewa_agency_used_seats);
$matewa_agency_setup_packs = isset($matewa_agency_client_pack_summary['total']) ? absint($matewa_agency_client_pack_summary['total']) : count($matewa_agency_client_pack_records);
$matewa_agency_expiring_soon = isset($matewa_agency_bundle_summary['expiring_soon']) ? absint($matewa_agency_bundle_summary['expiring_soon']) : 0;
$matewa_agency_expiring_soon += isset($matewa_agency_client_pack_summary['expiring_soon']) ? absint($matewa_agency_client_pack_summary['expiring_soon']) : 0;
$matewa_agency_needs_attention = isset($matewa_agency_bundle_summary['needs_attention']) ? absint($matewa_agency_bundle_summary['needs_attention']) : 0;
$matewa_agency_needs_attention += isset($matewa_agency_client_pack_summary['needs_attention']) ? absint($matewa_agency_client_pack_summary['needs_attention']) : 0;
$matewa_agency_needs_attention += $matewa_agency_duplicate_pack_count;
if (!$matewa_agency_routing_ready) {
    $matewa_agency_needs_attention++;
}
if (0 === $matewa_agency_client_seats && 0 === count($matewa_agency_bundle_records)) {
    $matewa_agency_needs_attention = max(1, $matewa_agency_needs_attention);
}

$matewa_agency_expiry = isset($matewa_agency_summary['access_expiry']) ? sanitize_text_field((string) $matewa_agency_summary['access_expiry']) : '';
$matewa_agency_checked_at = isset($matewa_agency_summary['checked_at']) ? (int) $matewa_agency_summary['checked_at'] : 0;
$matewa_agency_checked_label = $matewa_agency_checked_at > 0
    ? wp_date((string) get_option('date_format', 'Y-m-d') . ' ' . (string) get_option('time_format', 'H:i'), $matewa_agency_checked_at)
    : 'Not recorded';
$matewa_agency_status_label = ucwords(str_replace('_', ' ', $matewa_agency_status));
$matewa_agency_client_stage_note = $matewa_agency_client_seats > 0
    ? ($matewa_agency_setup_packs > 0 ? 'Client setup packs are being created.' : 'Bundle seats are ready. Create the first client setup pack.')
    : 'Buy an agency bundle before assigning client seats.';

$matewa_agency_bundle_notice_code = isset($_GET['matewa_agency_bundle_notice']) && is_scalar($_GET['matewa_agency_bundle_notice'])
    ? sanitize_key(wp_unslash($_GET['matewa_agency_bundle_notice']))
    : '';
$matewa_agency_bundle_notice_message = '';
if ('' !== $matewa_agency_bundle_notice_code) {
    $matewa_agency_bundle_notice_message = function_exists('matewa_agency_bundle_notice_message')
        ? matewa_agency_bundle_notice_message($matewa_agency_bundle_notice_code)
        : str_replace('_', ' ', $matewa_agency_bundle_notice_code);
}
$matewa_agency_bundle_notice_type = in_array($matewa_agency_bundle_notice_code, ['bundle_saved', 'bundle_rechecked', 'bundle_enabled', 'bundle_paused'], true) ? 'success' : 'warning';

$matewa_agency_client_pack_notice_code = isset($_GET['matewa_agency_client_pack_notice']) && is_scalar($_GET['matewa_agency_client_pack_notice'])
    ? sanitize_key(wp_unslash($_GET['matewa_agency_client_pack_notice']))
    : '';
$matewa_agency_client_pack_notice_message = '';
if ('' !== $matewa_agency_client_pack_notice_code) {
    $matewa_agency_client_pack_notice_message = function_exists('matewa_agency_client_pack_notice_message')
        ? matewa_agency_client_pack_notice_message($matewa_agency_client_pack_notice_code)
        : str_replace('_', ' ', $matewa_agency_client_pack_notice_code);
}
$matewa_agency_client_pack_notice_type = in_array($matewa_agency_client_pack_notice_code, ['client_pack_created', 'client_pack_saved', 'client_pack_deleted'], true) ? 'success' : 'warning';

$matewa_agency_setup_request_notice_code = isset($_GET['matewa_agency_setup_request_notice']) && is_scalar($_GET['matewa_agency_setup_request_notice'])
    ? sanitize_key(wp_unslash($_GET['matewa_agency_setup_request_notice']))
    : '';
$matewa_agency_setup_request_notice_map = array(
    'setup_request_sent'          => 'Client setup request email sent.',
    'setup_request_missing_email' => 'Add a valid client admin email before sending the setup request.',
    'setup_request_failed'        => 'The setup request could not be sent. Check WordPress mail settings or try copy message instead.',
);
$matewa_agency_setup_request_notice_message = isset($matewa_agency_setup_request_notice_map[$matewa_agency_setup_request_notice_code])
    ? $matewa_agency_setup_request_notice_map[$matewa_agency_setup_request_notice_code]
    : ('' !== $matewa_agency_setup_request_notice_code ? str_replace('_', ' ', $matewa_agency_setup_request_notice_code) : '');
$matewa_agency_setup_request_notice_type = 'setup_request_sent' === $matewa_agency_setup_request_notice_code ? 'success' : 'warning';

$matewa_agency_routing_notice_code = isset($_GET['matewa_agency_routing_notice']) && is_scalar($_GET['matewa_agency_routing_notice'])
    ? sanitize_key(wp_unslash($_GET['matewa_agency_routing_notice']))
    : '';
$matewa_agency_routing_notice_map = array(
    'agency_routing_sent_both'    => 'Agency routing test sent to both agency email inboxes.',
    'agency_routing_sent_admin'   => 'Agency routing test sent to the agency admin email only. Add a valid roundup email to send to both.',
    'agency_routing_sent_roundup' => 'Agency routing test sent to the agency roundup email only. Add a valid admin email to send to both.',
    'agency_routing_missing_email'=> 'Add at least one valid agency email before using Send now.',
    'agency_routing_failed'       => 'The agency routing test could not be sent. Check WordPress mail settings or try again.',
    'agency_roundup_sent'         => 'Agency routing test sent to the roundup email.',
    'agency_roundup_missing_email'=> 'Add a valid agency roundup email before using Send now.',
    'agency_roundup_failed'       => 'The agency routing test could not be sent. Check WordPress mail settings or try again.',
);
$matewa_agency_routing_notice_message = isset($matewa_agency_routing_notice_map[$matewa_agency_routing_notice_code])
    ? $matewa_agency_routing_notice_map[$matewa_agency_routing_notice_code]
    : ('' !== $matewa_agency_routing_notice_code ? str_replace('_', ' ', $matewa_agency_routing_notice_code) : '');
$matewa_agency_routing_success_codes = array('agency_routing_sent_both', 'agency_routing_sent_admin', 'agency_routing_sent_roundup', 'agency_roundup_sent');
$matewa_agency_routing_notice_type = in_array($matewa_agency_routing_notice_code, $matewa_agency_routing_success_codes, true) ? 'success' : 'warning';
$matewa_agency_routing_sent = in_array($matewa_agency_routing_notice_code, $matewa_agency_routing_success_codes, true);

$matewa_agency_setup_request_client_name = isset($_GET['matewa_setup_request_client_name']) && is_scalar($_GET['matewa_setup_request_client_name'])
    ? sanitize_text_field(wp_unslash($_GET['matewa_setup_request_client_name']))
    : '';
$matewa_agency_setup_request_client_email = isset($_GET['matewa_setup_request_client_email']) && is_scalar($_GET['matewa_setup_request_client_email'])
    ? sanitize_email(wp_unslash($_GET['matewa_setup_request_client_email']))
    : '';
$matewa_agency_setup_request_client_domain = isset($_GET['matewa_setup_request_client_domain']) && is_scalar($_GET['matewa_setup_request_client_domain'])
    ? sanitize_text_field(wp_unslash($_GET['matewa_setup_request_client_domain']))
    : '';
$matewa_agency_setup_request_agency_name = '' !== trim((string) get_option('matewa_business_name', ''))
    ? sanitize_text_field((string) get_option('matewa_business_name', ''))
    : 'your agency';
$matewa_agency_setup_request_message = "Hi" . ('' !== $matewa_agency_setup_request_client_name ? ' ' . $matewa_agency_setup_request_client_name : '') . ",

"
    . "We are setting up your 247ChatMate WhatsApp lead capture on your website. Please reply with the details below so we can prepare your setup pack.

"
    . "1. Business name
"
    . "2. Website/domain
"
    . "3. WhatsApp mobile/cell number for customer enquiries
"
    . "4. Main admin email
"
    . "5. Leads email for enquiry alerts
"
    . "6. Pages where the widget should appear
"
    . "7. Business type/category
"
    . "8. Preferred visitor buttons or common customer questions
"
    . "9. Any Google Business Profile, Instagram or review links you want included later

"
    . "Once we have this, we will create your client setup pack and confirm anything unclear before installation.

"
    . "Thanks,
"
    . $matewa_agency_setup_request_agency_name;

$matewa_agency_format_date = static function ($value) {
    $value = trim((string) $value);
    if ('' === $value) {
        return 'Not returned yet';
    }

    $timestamp = strtotime($value);
    if (!$timestamp) {
        return $value;
    }

    return wp_date((string) get_option('date_format', 'Y-m-d'), $timestamp);
};


$matewa_agency_client_selector_data = function_exists('matewa_agency_client_pack_get_selector_data')
    ? matewa_agency_client_pack_get_selector_data()
    : array();
$matewa_agency_client_selector_categories = isset($matewa_agency_client_selector_data['categories']) && is_array($matewa_agency_client_selector_data['categories'])
    ? $matewa_agency_client_selector_data['categories']
    : array();
$matewa_agency_client_default_category = isset($matewa_agency_client_selector_data['default_category']) ? sanitize_key((string) $matewa_agency_client_selector_data['default_category']) : '';
$matewa_agency_client_default_vertical = isset($matewa_agency_client_selector_data['default_vertical']) ? sanitize_key((string) $matewa_agency_client_selector_data['default_vertical']) : '';

if ('' === $matewa_agency_client_default_category || !isset($matewa_agency_client_selector_categories[$matewa_agency_client_default_category])) {
    $matewa_agency_client_default_category = !empty($matewa_agency_client_selector_categories) ? sanitize_key((string) array_key_first($matewa_agency_client_selector_categories)) : 'general';
}
$matewa_agency_client_default_options = isset($matewa_agency_client_selector_categories[$matewa_agency_client_default_category]['options']) && is_array($matewa_agency_client_selector_categories[$matewa_agency_client_default_category]['options'])
    ? $matewa_agency_client_selector_categories[$matewa_agency_client_default_category]['options']
    : array();
if ('' === $matewa_agency_client_default_vertical || !isset($matewa_agency_client_default_options[$matewa_agency_client_default_vertical])) {
    $matewa_agency_client_default_vertical = !empty($matewa_agency_client_default_options) ? sanitize_key((string) array_key_first($matewa_agency_client_default_options)) : 'general';
}
$matewa_agency_client_default_category_label = isset($matewa_agency_client_selector_categories[$matewa_agency_client_default_category]['label'])
    ? sanitize_text_field((string) $matewa_agency_client_selector_categories[$matewa_agency_client_default_category]['label'])
    : 'General';
$matewa_agency_client_default_vertical_label = isset($matewa_agency_client_default_options[$matewa_agency_client_default_vertical]['display_label'])
    ? sanitize_text_field((string) $matewa_agency_client_default_options[$matewa_agency_client_default_vertical]['display_label'])
    : 'General';
$matewa_agency_client_default_chips = isset($matewa_agency_client_default_options[$matewa_agency_client_default_vertical]['chips']) && is_array($matewa_agency_client_default_options[$matewa_agency_client_default_vertical]['chips'])
    ? array_values($matewa_agency_client_default_options[$matewa_agency_client_default_vertical]['chips'])
    : array('Get a quote', 'Pricing', 'Availability', 'Ask a question', 'Book a job', 'Something else');

$matewa_agency_client_edit_pack_id = isset($_GET['matewa_agency_edit_pack']) && is_scalar($_GET['matewa_agency_edit_pack'])
    ? sanitize_key(wp_unslash($_GET['matewa_agency_edit_pack']))
    : '';
$matewa_agency_client_edit_pack = '' !== $matewa_agency_client_edit_pack_id && function_exists('matewa_agency_client_pack_get_record_by_id')
    ? matewa_agency_client_pack_get_record_by_id($matewa_agency_client_edit_pack_id)
    : array();
$matewa_agency_client_is_editing = !empty($matewa_agency_client_edit_pack);

if ($matewa_agency_client_is_editing) {
    $edit_category_key = isset($matewa_agency_client_edit_pack['business_category_key']) ? sanitize_key((string) $matewa_agency_client_edit_pack['business_category_key']) : '';
    $edit_vertical_key = isset($matewa_agency_client_edit_pack['business_type_key']) ? sanitize_key((string) $matewa_agency_client_edit_pack['business_type_key']) : '';

    if ('' !== $edit_category_key && isset($matewa_agency_client_selector_categories[$edit_category_key])) {
        $matewa_agency_client_default_category = $edit_category_key;
        $matewa_agency_client_default_options = isset($matewa_agency_client_selector_categories[$matewa_agency_client_default_category]['options']) && is_array($matewa_agency_client_selector_categories[$matewa_agency_client_default_category]['options'])
            ? $matewa_agency_client_selector_categories[$matewa_agency_client_default_category]['options']
            : array();
    }

    if ('' !== $edit_vertical_key && isset($matewa_agency_client_default_options[$edit_vertical_key])) {
        $matewa_agency_client_default_vertical = $edit_vertical_key;
    }

    $matewa_agency_client_default_category_label = isset($matewa_agency_client_selector_categories[$matewa_agency_client_default_category]['label'])
        ? sanitize_text_field((string) $matewa_agency_client_selector_categories[$matewa_agency_client_default_category]['label'])
        : 'General';
    $matewa_agency_client_default_vertical_label = isset($matewa_agency_client_default_options[$matewa_agency_client_default_vertical]['display_label'])
        ? sanitize_text_field((string) $matewa_agency_client_default_options[$matewa_agency_client_default_vertical]['display_label'])
        : 'General';

    if (isset($matewa_agency_client_edit_pack['visitor_buttons']) && is_array($matewa_agency_client_edit_pack['visitor_buttons']) && !empty($matewa_agency_client_edit_pack['visitor_buttons'])) {
        $matewa_agency_client_default_chips = array_values($matewa_agency_client_edit_pack['visitor_buttons']);
    }
}

$matewa_agency_client_form_values = array(
    'client_business'    => $matewa_agency_client_is_editing && isset($matewa_agency_client_edit_pack['client_business']) ? sanitize_text_field((string) $matewa_agency_client_edit_pack['client_business']) : '',
    'client_domain'      => $matewa_agency_client_is_editing && isset($matewa_agency_client_edit_pack['client_domain']) ? sanitize_text_field((string) $matewa_agency_client_edit_pack['client_domain']) : '',
    'client_admin_email' => $matewa_agency_client_is_editing && isset($matewa_agency_client_edit_pack['client_admin_email']) ? sanitize_email((string) $matewa_agency_client_edit_pack['client_admin_email']) : '',
    'whatsapp_number'    => $matewa_agency_client_is_editing && isset($matewa_agency_client_edit_pack['whatsapp_number']) ? sanitize_text_field((string) $matewa_agency_client_edit_pack['whatsapp_number']) : '',
    'leads_email'        => $matewa_agency_client_is_editing && isset($matewa_agency_client_edit_pack['leads_email']) ? sanitize_email((string) $matewa_agency_client_edit_pack['leads_email']) : '',
    'page_mode'       => $matewa_agency_client_is_editing && isset($matewa_agency_client_edit_pack['page_mode']) && function_exists('matewa_agency_client_pack_allowed_page_mode') ? matewa_agency_client_pack_allowed_page_mode($matewa_agency_client_edit_pack['page_mode']) : 'all_pages',
);
?>

<div class="matewa-agency-hub-shell" aria-label="Agency Hub overview">
    <section class="matewa-agency-hub-hero" aria-label="Agency account status">
        <div>
            <span class="matewa-agency-hub-kicker">Agency active</span>
            <h3>Agency plan live</h3>
            <p>Your agency site is unlocked. Add client licences when you’re ready to roll this out to customers.</p>
            <div class="matewa-agency-hub-hero-actions" aria-label="Agency licence purchase actions">
                <a class="button button-primary" href="<?php echo esc_url(function_exists('matewa_agency_bundle_get_default_checkout_url') ? matewa_agency_bundle_get_default_checkout_url() : 'https://247chatmate.lemonsqueezy.com/'); ?>" target="_blank" rel="noopener noreferrer">Buy client licences</a>
                <a class="button button-secondary" href="#matewa-agency-bundle-licences">Manage licences</a>
            </div>
        </div>
        <div class="matewa-agency-hub-status-pill" aria-label="Paid client seats available to this agency account">
            <strong><?php echo esc_html((string) $matewa_agency_available_seats); ?></strong>
            <span>client seats available</span>
        </div>
    </section>

    <section class="matewa-agency-hub-stats" aria-label="Agency portfolio snapshot">
        <article class="matewa-agency-hub-stat-card">
            <span>Seats used</span>
            <strong><?php echo esc_html((string) $matewa_agency_used_seats); ?> / <?php echo esc_html((string) $matewa_agency_client_seats); ?></strong>
            <small><?php echo esc_html((string) $matewa_agency_available_seats); ?> available</small>
        </article>
        <article class="matewa-agency-hub-stat-card">
            <span>Expiring soon</span>
            <strong><?php echo esc_html((string) $matewa_agency_expiring_soon); ?></strong>
            <small>Expiry alerts come later</small>
        </article>
        <article class="matewa-agency-hub-stat-card">
            <span>Setup packs</span>
            <strong><?php echo esc_html((string) $matewa_agency_setup_packs); ?></strong>
            <small><?php echo $matewa_agency_setup_packs > 0 ? esc_html('Manual packs saved') : esc_html('Manual packs next'); ?></small>
        </article>
        <article class="matewa-agency-hub-stat-card <?php echo $matewa_agency_needs_attention > 0 ? 'is-warning' : 'is-ready'; ?>">
            <span>Needs attention</span>
            <strong><?php echo esc_html((string) $matewa_agency_needs_attention); ?></strong>
            <small><?php echo esc_html($matewa_agency_client_stage_note); ?></small>
        </article>
    </section>

    <section class="matewa-agency-client-board" aria-label="Agency reporting and automation foundation">
        <div class="matewa-agency-client-board-header">
            <div>
                <span class="matewa-agency-hub-kicker">Agency foundation</span>
                <h4>Reporting, setup and review controls</h4>
                <p>These controls prepare the agency reporting flow without sending weekly emails, parsing PDFs, or enforcing payment/grace automation yet.</p>
            </div>
            <div class="matewa-agency-client-board-actions" aria-label="Agency foundation status">
                <span class="matewa-agency-soft-pill <?php echo $matewa_agency_routing_ready ? esc_attr('is-ready') : esc_attr('is-warning'); ?>"><?php echo $matewa_agency_routing_ready ? esc_html('Routing ready') : esc_html('Routing needs email'); ?></span>
                <span class="matewa-agency-soft-pill">Automation parked</span>
            </div>
        </div>

        <?php if ('' !== $matewa_agency_setup_request_notice_message) : ?>
            <div class="matewa-agency-bundle-notice is-<?php echo esc_attr($matewa_agency_setup_request_notice_type); ?>" role="status" aria-live="polite">
                <?php echo esc_html($matewa_agency_setup_request_notice_message); ?>
            </div>
        <?php endif; ?>

        <div class="matewa-agency-client-pack-form matewa-agency-routing-panel<?php echo $matewa_agency_routing_sent ? esc_attr(' is-sent') : ''; ?>" aria-label="Agency email routing fields">
            <div class="matewa-agency-client-pack-form-head">
                <div>
                    <strong>Agency email routing</strong>
                    <span>Store the agency inboxes now. Weekly roundup sending remains a later locked checkpoint.</span>
                </div>
                <em><?php echo $matewa_agency_routing_sent ? esc_html('Sent') : ($matewa_agency_routing_ready ? esc_html('Ready') : esc_html('Needs setup')); ?></em>
            </div>
            <?php if ('' !== $matewa_agency_routing_notice_message) : ?>
                <div class="matewa-agency-bundle-notice is-<?php echo esc_attr($matewa_agency_routing_notice_type); ?>" role="status" aria-live="polite">
                    <?php echo esc_html($matewa_agency_routing_notice_message); ?>
                </div>
            <?php endif; ?>
            <div class="matewa-agency-client-pack-grid is-details">
                <label>
                    <span>Agency admin email</span>
                    <input type="email" name="matewa_agency_admin_email" placeholder="e.g. admin@agency.co.uk" value="<?php echo esc_attr($matewa_agency_admin_email); ?>" autocomplete="email">
                </label>
                <label>
                    <span>Agency roundup email</span>
                    <input type="email" name="matewa_agency_roundup_email" placeholder="e.g. reports@agency.co.uk" value="<?php echo esc_attr($matewa_agency_roundup_email); ?>" autocomplete="email">
                </label>
            </div>
            <div class="matewa-agency-client-pack-actions matewa-agency-routing-actions">
                <button type="submit" class="button button-primary matewa-agency-routing-save-button" name="matewa_agency_routing_action" value="save">Save agency routing</button>
                <button type="submit" class="button button-primary matewa-agency-routing-send-now-button<?php echo $matewa_agency_routing_sent ? esc_attr(' is-sent') : ''; ?>" name="matewa_agency_routing_action" value="send_roundup_now"><?php echo $matewa_agency_routing_sent ? esc_html('Sent') : esc_html('Send now'); ?></button>
                <small>Client lead alerts still use each setup pack’s Client leads email. These agency fields are for agency notices and future weekly client roundups. Use Send now to test the roundup inbox before live scheduled sending is enabled.</small>
            </div>
        </div>

        <div class="matewa-agency-client-pack-form matewa-agency-setup-request-panel" aria-label="Client setup request controls" data-matewa-agency-setup-request data-matewa-agency-name="<?php echo esc_attr($matewa_agency_setup_request_agency_name); ?>">
            <div class="matewa-agency-client-pack-form-head">
                <div>
                    <strong>Client setup request pack</strong>
                    <span>Send or copy the setup request the client fills in. PDF download/upload stays parked until the PDF mockups are signed off.</span>
                </div>
                <em>Agency action</em>
            </div>
            <div class="matewa-agency-client-pack-grid is-details">
                <label>
                    <span>Client contact name</span>
                    <input type="text" name="matewa_setup_request_client_name" placeholder="e.g. Jim" value="<?php echo esc_attr($matewa_agency_setup_request_client_name); ?>" data-matewa-setup-request-field="name" autocomplete="name">
                </label>
                <label>
                    <span>Client admin email</span>
                    <input type="email" name="matewa_setup_request_client_email" placeholder="e.g. admin@client.co.uk" value="<?php echo esc_attr($matewa_agency_setup_request_client_email); ?>" data-matewa-setup-request-field="email" autocomplete="email">
                </label>
                <label>
                    <span>Client domain</span>
                    <input type="text" name="matewa_setup_request_client_domain" placeholder="e.g. client.co.uk" value="<?php echo esc_attr($matewa_agency_setup_request_client_domain); ?>" data-matewa-setup-request-field="domain" autocomplete="url">
                </label>
            </div>
            <label class="matewa-agency-setup-request-message">
                <span>Setup request message</span>
                <textarea readonly rows="9" data-matewa-setup-request-message><?php echo esc_textarea($matewa_agency_setup_request_message); ?></textarea>
            </label>
            <div class="matewa-agency-setup-request-actions">
                <button type="button" class="button button-secondary" data-matewa-copy-setup-request>Copy setup message</button>
                <button type="submit" class="button button-primary matewa-agency-send-now-button" name="matewa_agency_setup_request_action" value="send_request">Send now</button>
                <button type="button" class="button button-secondary" disabled aria-disabled="true">Download blank setup PDF after signoff</button>
                <span class="matewa-agency-client-row-note" data-matewa-copy-setup-request-status aria-live="polite"></span>
            </div>
            <div class="matewa-agency-setup-request-dropzone" aria-label="Completed setup PDF upload parked">
                <strong>Upload completed setup PDF</strong>
                <span>Drag-and-drop extraction will be added after the setup PDF is signed off. For now, create or edit the setup pack manually from the client’s answers.</span>
            </div>
        </div>

        <div class="matewa-agency-hub-stats" aria-label="Agency foundation status cards">
            <article class="matewa-agency-hub-stat-card <?php echo $matewa_agency_routing_ready ? esc_attr('is-ready') : esc_attr('is-warning'); ?>">
                <span>Email routing</span>
                <strong><?php echo $matewa_agency_routing_ready ? esc_html('Ready') : esc_html('Needs setup'); ?></strong>
                <small>Agency admin + roundup inboxes</small>
            </article>
            <article class="matewa-agency-hub-stat-card">
                <span>Weekly roundup</span>
                <strong><?php echo esc_html((string) $matewa_agency_weekly_ready_count); ?></strong>
                <small>Client packs ready for future roundup</small>
            </article>
            <article class="matewa-agency-hub-stat-card <?php echo $matewa_agency_duplicate_pack_count > 0 ? esc_attr('is-warning') : esc_attr('is-ready'); ?>">
                <span>Review flags</span>
                <strong><?php echo esc_html((string) $matewa_agency_duplicate_pack_count); ?></strong>
                <small>Duplicate warnings only; not hard-blocked here</small>
            </article>
            <article class="matewa-agency-hub-stat-card">
                <span>Grace flow</span>
                <strong>Advisory</strong>
                <small>28-day flow placeholder; no client messaging yet</small>
            </article>
        </div>
    </section>

    <section id="matewa-agency-bundle-licences" class="matewa-agency-bundle-panel" aria-label="Agency bundle licences">
        <div class="matewa-agency-client-board-header">
            <div>
                <span class="matewa-agency-hub-kicker">Licence seats</span>
                <h4>Agency bundle licences</h4>
                <p>Buy client-seat bundles through LemonSqueezy, then paste the agency bundle licence key here. Saved keys stay masked in the dashboard.</p>
            </div>
            <div class="matewa-agency-client-board-actions" aria-label="Agency checkout links">
                <?php foreach ($matewa_agency_bundle_plans as $matewa_plan_key => $matewa_plan) : ?>
                    <?php
                    $matewa_plan_label = isset($matewa_plan['label']) ? sanitize_text_field((string) $matewa_plan['label']) : 'Agency bundle';
                    $matewa_plan_url = isset($matewa_plan['checkout_url']) ? esc_url((string) $matewa_plan['checkout_url']) : '';
                    $matewa_plan_price = isset($matewa_plan['price']) ? sanitize_text_field((string) $matewa_plan['price']) : '';
                    ?>
                    <?php if ('' !== $matewa_plan_url) : ?>
                        <a class="matewa-agency-soft-pill is-link" href="<?php echo esc_url($matewa_plan_url); ?>" target="_blank" rel="noopener noreferrer"><?php echo esc_html($matewa_plan_label); ?><?php echo '' !== $matewa_plan_price ? esc_html(' · ' . $matewa_plan_price) : ''; ?></a>
                    <?php endif; ?>
                <?php endforeach; ?>
            </div>
        </div>

        <?php if ('' !== $matewa_agency_bundle_notice_message) : ?>
            <div class="matewa-agency-bundle-notice is-<?php echo esc_attr($matewa_agency_bundle_notice_type); ?>" role="status" aria-live="polite">
                <?php echo esc_html($matewa_agency_bundle_notice_message); ?>
            </div>
        <?php endif; ?>

        <div class="matewa-agency-bundle-entry" aria-label="Add agency bundle licence">
            <label for="matewa_agency_bundle_license_key">
                <strong>Add agency bundle licence</strong>
                <span>Paste the licence key from LemonSqueezy. It will be hidden after save.</span>
            </label>
            <div class="matewa-agency-bundle-entry-controls">
                <textarea
                    id="matewa_agency_bundle_license_key"
                    name="matewa_agency_bundle_license_key"
                    rows="1"
                    autocomplete="new-password"
                    spellcheck="false"
                    placeholder="Paste agency bundle licence key"
                ></textarea>
                <button type="submit" class="button button-primary" name="matewa_agency_bundle_action" value="add">Activate bundle</button>
            </div>
            <small>Local toggle controls whether this agency account uses the bundle. LemonSqueezy status still decides whether the licence is actually valid.</small>
        </div>

        <div class="matewa-agency-client-table-wrap matewa-agency-bundle-table-wrap">
            <table class="matewa-agency-client-table matewa-agency-bundle-table">
                <thead>
                    <tr>
                        <th scope="col">Bundle</th>
                        <th scope="col">Status</th>
                        <th scope="col">Seats</th>
                        <th scope="col">Expiry / renewal</th>
                        <th scope="col">Local use</th>
                        <th scope="col">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($matewa_agency_bundle_records)) : ?>
                        <tr>
                            <td data-label="Bundle">
                                <strong>No paid bundle added yet</strong>
                                <span>Use Buy client licences, then paste the bundle key here.</span>
                            </td>
                            <td data-label="Status"><span class="matewa-agency-table-pill is-warning">Waiting</span></td>
                            <td data-label="Seats">0</td>
                            <td data-label="Expiry / renewal">—</td>
                            <td data-label="Local use">—</td>
                            <td data-label="Actions">Add bundle first</td>
                        </tr>
                    <?php else : ?>
                        <?php foreach ($matewa_agency_bundle_records as $matewa_bundle) : ?>
                            <?php
                            $matewa_bundle_id = isset($matewa_bundle['bundle_id']) ? sanitize_key((string) $matewa_bundle['bundle_id']) : '';
                            $matewa_bundle_label = isset($matewa_bundle['plan_label']) && '' !== trim((string) $matewa_bundle['plan_label']) ? sanitize_text_field((string) $matewa_bundle['plan_label']) : 'Agency bundle';
                            $matewa_bundle_masked = isset($matewa_bundle['masked_key']) ? sanitize_text_field((string) $matewa_bundle['masked_key']) : 'Saved key hidden';
                            $matewa_bundle_valid = !empty($matewa_bundle['valid']);
                            $matewa_bundle_enabled = !empty($matewa_bundle['local_enabled']);
                            $matewa_bundle_status = isset($matewa_bundle['status']) ? sanitize_key((string) $matewa_bundle['status']) : 'not_checked';
                            $matewa_bundle_status_label = $matewa_bundle_enabled ? ($matewa_bundle_valid ? 'Active' : ucwords(str_replace('_', ' ', $matewa_bundle_status))) : 'Paused locally';
                            $matewa_bundle_status_class = $matewa_bundle_enabled && $matewa_bundle_valid ? 'is-ready' : 'is-warning';
                            $matewa_bundle_seats = isset($matewa_bundle['seats']) ? absint($matewa_bundle['seats']) : 0;
                            $matewa_bundle_used = isset($matewa_bundle['used_seats']) ? absint($matewa_bundle['used_seats']) : 0;
                            $matewa_bundle_available = max(0, $matewa_bundle_seats - $matewa_bundle_used);
                            $matewa_bundle_date_source = !empty($matewa_bundle['renews_at']) ? $matewa_bundle['renews_at'] : ($matewa_bundle['expires_at'] ?? '');
                            $matewa_bundle_date_label = $matewa_agency_format_date($matewa_bundle_date_source);
                            $matewa_bundle_checked = !empty($matewa_bundle['checked_at']) ? wp_date((string) get_option('date_format', 'Y-m-d'), (int) $matewa_bundle['checked_at']) : 'Not checked';
                            ?>
                            <tr>
                                <td data-label="Bundle">
                                    <strong><?php echo esc_html($matewa_bundle_label); ?></strong>
                                    <span><?php echo esc_html($matewa_bundle_masked); ?> · Last checked <?php echo esc_html($matewa_bundle_checked); ?></span>
                                </td>
                                <td data-label="Status"><span class="matewa-agency-table-pill <?php echo esc_attr($matewa_bundle_status_class); ?>"><?php echo esc_html($matewa_bundle_status_label); ?></span></td>
                                <td data-label="Seats"><?php echo esc_html((string) $matewa_bundle_used); ?> / <?php echo esc_html((string) $matewa_bundle_seats); ?> used<br><span><?php echo esc_html((string) $matewa_bundle_available); ?> available</span></td>
                                <td data-label="Expiry / renewal"><?php echo esc_html($matewa_bundle_date_label); ?><br><span><?php echo $matewa_bundle_valid ? esc_html('Set to renew / active unless billing changes') : esc_html('Check billing'); ?></span></td>
                                <td data-label="Local use"><?php echo $matewa_bundle_enabled ? esc_html('On') : esc_html('Paused'); ?></td>
                                <td data-label="Actions">
                                    <?php if ('' !== $matewa_bundle_id) : ?>
                                        <button type="submit" class="button button-small" name="matewa_agency_bundle_action" value="recheck" onclick="document.getElementById('matewa-agency-bundle-id-field').value='<?php echo esc_js($matewa_bundle_id); ?>';">Recheck</button>
                                        <?php if ($matewa_bundle_enabled) : ?>
                                            <button type="submit" class="button button-small" name="matewa_agency_bundle_action" value="toggle_off" onclick="document.getElementById('matewa-agency-bundle-id-field').value='<?php echo esc_js($matewa_bundle_id); ?>';">Pause</button>
                                        <?php else : ?>
                                            <button type="submit" class="button button-small" name="matewa_agency_bundle_action" value="toggle_on" onclick="document.getElementById('matewa-agency-bundle-id-field').value='<?php echo esc_js($matewa_bundle_id); ?>';">Use</button>
                                        <?php endif; ?>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
            <input type="hidden" id="matewa-agency-bundle-id-field" name="matewa_agency_bundle_id" value="">
        </div>
    </section>

    <section class="matewa-agency-client-board" aria-label="Client setup packs board">
        <div class="matewa-agency-client-board-header">
            <div>
                <span class="matewa-agency-hub-kicker">Client onboarding</span>
                <h4>Client setup packs</h4>
                <p>Create manual setup packs for client sites. Export setup file, PDF attachment/review and live client install remain later locked checkpoints.</p>
            </div>
            <div class="matewa-agency-client-board-actions" aria-label="Client setup pack next actions">
                <span class="matewa-agency-soft-pill">Manual entry active</span>
                <span class="matewa-agency-soft-pill">Export file pending</span>
                <span class="matewa-agency-soft-pill">PDF review later</span>
            </div>
        </div>

        <?php if ('' !== $matewa_agency_client_pack_notice_message) : ?>
            <div class="matewa-agency-bundle-notice is-<?php echo esc_attr($matewa_agency_client_pack_notice_type); ?>" role="status" aria-live="polite">
                <?php echo esc_html($matewa_agency_client_pack_notice_message); ?>
            </div>
        <?php endif; ?>

        <div id="matewa-agency-client-pack-editor" class="matewa-agency-client-pack-form" aria-label="Create or edit manual client setup pack">
            <?php if ($matewa_agency_client_is_editing) : ?>
                <input type="hidden" name="matewa_agency_client_pack_id" value="<?php echo esc_attr($matewa_agency_client_edit_pack_id); ?>">
            <?php endif; ?>
            <div class="matewa-agency-client-pack-form-head">
                <div>
                    <strong><?php echo $matewa_agency_client_is_editing ? esc_html('Edit client setup pack') : esc_html('Add client setup pack'); ?></strong>
                    <span><?php echo $matewa_agency_client_is_editing ? esc_html('Update this client pack in the main Agency Hub window. The assigned seat is preserved.') : esc_html('Assign one available bundle seat and capture the details needed for the later setup JSON export.'); ?></span>
                </div>
                <em><?php echo esc_html((string) $matewa_agency_available_seats); ?> seats available</em>
            </div>

            <div class="matewa-agency-client-pack-section">
                <div class="matewa-agency-client-pack-section-head">
                    <span class="matewa-agency-client-pack-step">1</span>
                    <div>
                        <strong>Client details</strong>
                        <small>These details will later feed the client setup JSON.</small>
                    </div>
                </div>
                <div class="matewa-agency-client-pack-grid is-details">
                    <label>
                        <span>Client business name</span>
                        <input type="text" name="matewa_agency_client_business" placeholder="e.g. ABC Plumbing" value="<?php echo esc_attr($matewa_agency_client_form_values['client_business']); ?>" autocomplete="organization">
                    </label>
                    <label>
                        <span>Client domain</span>
                        <input type="text" name="matewa_agency_client_domain" placeholder="e.g. abcplumbing.co.uk" value="<?php echo esc_attr($matewa_agency_client_form_values['client_domain']); ?>" autocomplete="url">
                    </label>
                    <label>
                        <span>Client admin email</span>
                        <input type="email" name="matewa_agency_client_admin_email" placeholder="e.g. admin@client.co.uk" value="<?php echo esc_attr($matewa_agency_client_form_values['client_admin_email']); ?>" autocomplete="email">
                    </label>
                    <label>
                        <span>WhatsApp mobile/cell number</span>
                        <input type="text" name="matewa_agency_client_whatsapp" placeholder="e.g. 447900123456" value="<?php echo esc_attr($matewa_agency_client_form_values['whatsapp_number']); ?>" autocomplete="tel">
                    </label>
                    <label>
                        <span>Client leads email</span>
                        <input type="email" name="matewa_agency_client_leads_email" placeholder="e.g. enquiries@client.co.uk" value="<?php echo esc_attr($matewa_agency_client_form_values['leads_email']); ?>" autocomplete="email">
                    </label>
                    <label>
                        <span>Page visibility</span>
                        <select name="matewa_agency_client_page_mode">
                            <option value="all_pages" <?php selected($matewa_agency_client_form_values['page_mode'], 'all_pages'); ?>>All pages</option>
                            <option value="homepage" <?php selected($matewa_agency_client_form_values['page_mode'], 'homepage'); ?>>Homepage only</option>
                            <option value="specific_pages" <?php selected($matewa_agency_client_form_values['page_mode'], 'specific_pages'); ?>>Specific pages later</option>
                        </select>
                    </label>
                </div>
            </div>

            <div class="matewa-agency-client-pack-section matewa-agency-visitor-buttons-copy" data-matewa-agency-client-selector>
                <div class="matewa-agency-client-pack-section-head">
                    <span class="matewa-agency-client-pack-step">2</span>
                    <div>
                        <strong>Choose business type</strong>
                        <small>Choose in order, then edit the best starter buttons for this client.</small>
                    </div>
                </div>
                <div class="matewa-agency-client-pack-grid is-business-type">
                    <label>
                        <span>Category</span>
                        <select id="matewa_agency_client_business_category_key" name="matewa_agency_client_business_category_key" data-agency-client-category>
                            <?php foreach ($matewa_agency_client_selector_categories as $matewa_client_category_key => $matewa_client_category_data) : ?>
                                <?php
                                $matewa_client_category_key = sanitize_key((string) $matewa_client_category_key);
                                $matewa_client_category_label = isset($matewa_client_category_data['label']) ? sanitize_text_field((string) $matewa_client_category_data['label']) : 'General';
                                ?>
                                <option value="<?php echo esc_attr($matewa_client_category_key); ?>" <?php selected($matewa_agency_client_default_category, $matewa_client_category_key); ?>><?php echo esc_html($matewa_client_category_label); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </label>
                    <label>
                        <span>Business type</span>
                        <select id="matewa_agency_client_business_type_key" name="matewa_agency_client_business_type_key" data-agency-client-business-type>
                            <?php foreach ($matewa_agency_client_default_options as $matewa_client_vertical_key => $matewa_client_vertical_data) : ?>
                                <?php
                                $matewa_client_vertical_key = sanitize_key((string) $matewa_client_vertical_key);
                                $matewa_client_vertical_label = isset($matewa_client_vertical_data['display_label']) ? sanitize_text_field((string) $matewa_client_vertical_data['display_label']) : 'General';
                                ?>
                                <option value="<?php echo esc_attr($matewa_client_vertical_key); ?>" <?php selected($matewa_agency_client_default_vertical, $matewa_client_vertical_key); ?>><?php echo esc_html($matewa_client_vertical_label); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </label>
                </div>

                <div class="matewa-agency-client-helper matewa-agency-client-selector-helper">
                    <strong>Choose business type</strong>
                    <ul>
                        <li>Choose a category.</li>
                        <li>Choose your business type.</li>
                        <li>Edit the best starter buttons for this client.</li>
                    </ul>
                </div>

                <input type="hidden" name="matewa_agency_client_industry" data-agency-client-industry-label value="<?php echo esc_attr($matewa_agency_client_default_category_label); ?>">
                <input type="hidden" name="matewa_agency_client_business_category" data-agency-client-category-label value="<?php echo esc_attr($matewa_agency_client_default_category_label); ?>">
                <input type="hidden" name="matewa_agency_client_business_type" data-agency-client-business-label value="<?php echo esc_attr($matewa_agency_client_default_vertical_label); ?>">

                <div class="matewa-agency-client-chip-editor" aria-label="Editable copied Visitor Buttons for this client setup pack">
                    <div class="matewa-agency-client-chip-editor-head">
                        <strong>Visitor buttons — <span data-agency-client-chip-title><?php echo esc_html($matewa_agency_client_default_vertical_label); ?></span></strong>
                        <small>Edit the 6 quick-reply buttons for this client setup pack.</small>
                    </div>
                    <div class="matewa-agency-client-chip-grid" data-agency-client-chip-grid>
                        <?php foreach (array_slice($matewa_agency_client_default_chips, 0, 6) as $matewa_client_chip_label) : ?>
                            <div class="matewa-chip-editor-item">
                                <div class="matewa-chip-editor-chip">
                                    <textarea name="matewa_agency_client_chip_labels[]" maxlength="34" rows="2" autocomplete="off" aria-label="Visitor button label, maximum 34 characters over two visual rows"><?php echo esc_textarea($matewa_client_chip_label); ?></textarea>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                    <div class="matewa-agency-client-helper matewa-agency-client-chip-helper">
                        <strong>Edit buttons</strong>
                        <ul>
                            <li>Edit any labels if needed.</li>
                            <li>Keep labels short — two lines max.</li>
                            <li>Save the setup pack when the buttons are ready.</li>
                            <li>If changes do not appear, clear your cache and try again.</li>
                            <li>Keep the final button for custom requests, such as “Something else”.</li>
                        </ul>
                    </div>
                </div>
            </div>
            <div class="matewa-agency-client-pack-actions">
                <button type="submit" class="button button-primary" name="matewa_agency_client_pack_action" value="<?php echo $matewa_agency_client_is_editing ? esc_attr('save') : esc_attr('create'); ?>"><?php echo $matewa_agency_client_is_editing ? esc_html('Save setup pack') : esc_html('Create setup pack'); ?></button>
                <?php if ($matewa_agency_client_is_editing) : ?>
                    <a class="button button-secondary" href="<?php echo esc_url(add_query_arg(array('page' => '247chatmate', 'matewa_saved_section' => 'agency'), admin_url('admin.php')) . '#matewa-agency-client-packs'); ?>">Cancel edit</a>
                <?php endif; ?>
                <small><?php echo $matewa_agency_client_is_editing ? esc_html('The assigned seat is preserved. The client site will still not receive the agency master LemonSqueezy key.') : esc_html('One available bundle seat will be reserved. The client site will not receive the agency master LemonSqueezy key.'); ?></small>
            </div>
        </div>

        <div class="matewa-agency-client-table-wrap">
            <table class="matewa-agency-client-table">
                <thead>
                    <tr>
                        <th scope="col">Client / domain</th>
                        <th scope="col">Licence</th>
                        <th scope="col">Expires</th>
                        <th scope="col">Pages</th>
                        <th scope="col">Business type</th>
                        <th scope="col">Visitor buttons</th>
                        <th scope="col">Status</th>
                        <th scope="col">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($matewa_agency_client_pack_records)) : ?>
                        <tr>
                            <td data-label="Client / domain">
                                <strong>First client</strong>
                                <span>Waiting for manual client setup pack creation</span>
                            </td>
                            <td data-label="Licence"><span class="matewa-agency-table-pill is-muted">Seat not assigned</span></td>
                            <td data-label="Expires">—</td>
                            <td data-label="Pages">All pages / Homepage / Specific pages</td>
                            <td data-label="Business type">Editable</td>
                            <td data-label="Chips">Defaults or edited</td>
                            <td data-label="Status"><span class="matewa-agency-table-pill is-warning">Create first pack</span></td>
                            <td data-label="Actions">Manual form above</td>
                        </tr>
                    <?php else : ?>
                        <?php foreach ($matewa_agency_client_pack_records as $matewa_client_pack) : ?>
                            <?php
                            $matewa_client_name = isset($matewa_client_pack['client_business']) ? sanitize_text_field((string) $matewa_client_pack['client_business']) : 'Client';
                            $matewa_client_domain = isset($matewa_client_pack['client_domain']) ? sanitize_text_field((string) $matewa_client_pack['client_domain']) : '';
                            $matewa_client_admin_email = isset($matewa_client_pack['client_admin_email']) ? sanitize_email((string) $matewa_client_pack['client_admin_email']) : '';
                            $matewa_client_leads_email = isset($matewa_client_pack['leads_email']) ? sanitize_email((string) $matewa_client_pack['leads_email']) : '';
                            $matewa_client_status = isset($matewa_client_pack['status']) ? sanitize_key((string) $matewa_client_pack['status']) : 'draft';
                            $matewa_client_status_label = 'ready' === $matewa_client_status ? 'Ready' : ('needs_attention' === $matewa_client_status ? 'Needs attention' : 'Draft');
                            $matewa_client_status_class = 'ready' === $matewa_client_status ? 'is-ready' : 'is-warning';
                            $matewa_client_expiry_source = !empty($matewa_client_pack['renews_at']) ? $matewa_client_pack['renews_at'] : ($matewa_client_pack['expires_at'] ?? '');
                            $matewa_client_expiry_label = $matewa_agency_format_date($matewa_client_expiry_source);
                            $matewa_client_page_label = function_exists('matewa_agency_client_pack_page_mode_label') ? matewa_agency_client_pack_page_mode_label($matewa_client_pack['page_mode'] ?? 'all_pages') : 'All pages';
                            $matewa_client_chip_label = function_exists('matewa_agency_client_pack_chip_mode_label') ? matewa_agency_client_pack_chip_mode_label($matewa_client_pack['chip_mode'] ?? 'defaults') : 'Default chips';
                            $matewa_client_visitor_buttons = isset($matewa_client_pack['visitor_buttons']) && is_array($matewa_client_pack['visitor_buttons']) ? array_values($matewa_client_pack['visitor_buttons']) : array();
                            $matewa_client_type = isset($matewa_client_pack['business_type']) ? sanitize_text_field((string) $matewa_client_pack['business_type']) : 'General';
                            $matewa_client_category = isset($matewa_client_pack['business_category']) ? sanitize_text_field((string) $matewa_client_pack['business_category']) : '';
                            $matewa_client_pack_id = isset($matewa_client_pack['setup_pack_id']) ? sanitize_key((string) $matewa_client_pack['setup_pack_id']) : '';
                            $matewa_client_review_flags = '' !== $matewa_client_pack_id && isset($matewa_agency_client_duplicate_flags[$matewa_client_pack_id]) && is_array($matewa_agency_client_duplicate_flags[$matewa_client_pack_id])
                                ? array_values($matewa_agency_client_duplicate_flags[$matewa_client_pack_id])
                                : array();
                            $matewa_client_setup_route_label = 'Manual setup saved';
                            $matewa_client_export_label = 'Export file pending';
                            $matewa_client_pdf_label = 'PDF review later';
                            ?>
                            <tr>
                                <td data-label="Client / domain">
                                    <strong><?php echo esc_html($matewa_client_name); ?></strong>
                                    <span><?php echo esc_html($matewa_client_domain); ?><?php echo '' !== $matewa_client_pack_id ? esc_html(' · ' . $matewa_client_pack_id) : ''; ?></span>
                                    <?php if ('' !== $matewa_client_admin_email || '' !== $matewa_client_leads_email) : ?>
                                        <span><?php echo '' !== $matewa_client_admin_email ? esc_html('Admin: ' . $matewa_client_admin_email) : esc_html('Admin email needed'); ?></span>
                                        <span><?php echo '' !== $matewa_client_leads_email ? esc_html('Leads: ' . $matewa_client_leads_email) : esc_html('Leads email needed'); ?></span>
                                    <?php endif; ?>
                                </td>
                                <td data-label="Licence"><span class="matewa-agency-table-pill is-ready">Seat assigned</span></td>
                                <td data-label="Expires"><?php echo esc_html($matewa_client_expiry_label); ?><br><span>Follows bundle renewal</span></td>
                                <td data-label="Pages"><?php echo esc_html($matewa_client_page_label); ?></td>
                                <td data-label="Business type"><?php echo esc_html($matewa_client_type); ?><?php echo '' !== $matewa_client_category ? '<br><span>' . esc_html($matewa_client_category) . '</span>' : ''; ?></td>
                                <td data-label="Visitor buttons">
                                    <?php if (!empty($matewa_client_visitor_buttons)) : ?>
                                        <div class="matewa-agency-client-chip-summary" aria-label="Saved visitor buttons for <?php echo esc_attr($matewa_client_name); ?>">
                                            <?php foreach (array_slice($matewa_client_visitor_buttons, 0, 6) as $matewa_saved_chip_label) : ?>
                                                <span><?php echo esc_html((string) $matewa_saved_chip_label); ?></span>
                                            <?php endforeach; ?>
                                        </div>
                                    <?php else : ?>
                                        <?php echo esc_html($matewa_client_chip_label); ?>
                                    <?php endif; ?>
                                </td>
                                <td data-label="Status">
                                    <span class="matewa-agency-table-pill <?php echo esc_attr($matewa_client_status_class); ?>"><?php echo esc_html($matewa_client_status_label); ?></span>
                                    <br><span><?php echo esc_html($matewa_client_setup_route_label); ?></span>
                                    <br><span><?php echo esc_html($matewa_client_export_label); ?></span>
                                    <?php if (!empty($matewa_client_review_flags)) : ?>
                                        <?php foreach ($matewa_client_review_flags as $matewa_client_review_flag) : ?>
                                            <br><span class="matewa-agency-client-row-note"><?php echo esc_html((string) $matewa_client_review_flag); ?></span>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </td>
                                <td data-label="Actions">
                                    <div class="matewa-agency-client-row-actions">
                                        <a class="button button-secondary" href="<?php echo esc_url(add_query_arg(array('page' => '247chatmate', 'matewa_saved_section' => 'agency', 'matewa_agency_edit_pack' => $matewa_client_pack_id), admin_url('admin.php')) . '#matewa-agency-client-pack-editor'); ?>">Edit</a>
                                        <button type="submit" class="button button-secondary is-danger" name="matewa_agency_client_pack_delete_id" value="<?php echo esc_attr($matewa_client_pack_id); ?>" onclick="return window.confirm('Delete this client setup pack and release its assigned seat?');">Delete</button>
                                    </div>
                                    <span class="matewa-agency-client-row-note">Export setup file pending</span>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        <div class="matewa-agency-client-table-wrap matewa-agency-performance-table-wrap" aria-label="Agency client performance board">
            <table class="matewa-agency-client-table matewa-agency-performance-table">
                <thead>
                    <tr>
                        <th scope="col">Client</th>
                        <th scope="col">Reporting</th>
                        <th scope="col">Leads</th>
                        <th scope="col">WA handoffs</th>
                        <th scope="col">Incomplete</th>
                        <th scope="col">Setup route</th>
                        <th scope="col">Review</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($matewa_agency_client_pack_records)) : ?>
                        <tr>
                            <td data-label="Client"><strong>No client packs yet</strong></td>
                            <td data-label="Reporting">Create a setup pack first</td>
                            <td data-label="Leads">—</td>
                            <td data-label="WA handoffs">—</td>
                            <td data-label="Incomplete">—</td>
                            <td data-label="Setup route">Manual/PDF later</td>
                            <td data-label="Review">Waiting</td>
                        </tr>
                    <?php else : ?>
                        <?php foreach ($matewa_agency_client_pack_records as $matewa_client_pack) : ?>
                            <?php
                            $matewa_perf_client_name = isset($matewa_client_pack['client_business']) ? sanitize_text_field((string) $matewa_client_pack['client_business']) : 'Client';
                            $matewa_perf_pack_id = isset($matewa_client_pack['setup_pack_id']) ? sanitize_key((string) $matewa_client_pack['setup_pack_id']) : '';
                            $matewa_perf_leads_email = isset($matewa_client_pack['leads_email']) ? sanitize_email((string) $matewa_client_pack['leads_email']) : '';
                            $matewa_perf_flags = '' !== $matewa_perf_pack_id && isset($matewa_agency_client_duplicate_flags[$matewa_perf_pack_id]) && is_array($matewa_agency_client_duplicate_flags[$matewa_perf_pack_id])
                                ? array_values($matewa_agency_client_duplicate_flags[$matewa_perf_pack_id])
                                : array();
                            ?>
                            <tr>
                                <td data-label="Client"><strong><?php echo esc_html($matewa_perf_client_name); ?></strong><?php echo '' !== $matewa_perf_pack_id ? '<br><span>' . esc_html($matewa_perf_pack_id) . '</span>' : ''; ?></td>
                                <td data-label="Reporting"><span class="matewa-agency-table-pill <?php echo is_email($matewa_perf_leads_email) ? esc_attr('is-ready') : esc_attr('is-warning'); ?>"><?php echo is_email($matewa_perf_leads_email) ? esc_html('Client email ready') : esc_html('Needs leads email'); ?></span><br><span>Weekly summary wiring later</span></td>
                                <td data-label="Leads">0<br><span>Client install pending</span></td>
                                <td data-label="WA handoffs">0<br><span>Client install pending</span></td>
                                <td data-label="Incomplete">0<br><span>Client install pending</span></td>
                                <td data-label="Setup route">Manual saved<br><span><?php echo esc_html('Export file pending'); ?></span><br><span><?php echo esc_html('PDF review later'); ?></span></td>
                                <td data-label="Review">
                                    <?php if (!empty($matewa_perf_flags)) : ?>
                                        <span class="matewa-agency-table-pill is-warning"><?php echo esc_html((string) count($matewa_perf_flags)); ?> flag<?php echo 1 === count($matewa_perf_flags) ? '' : 's'; ?></span>
                                    <?php else : ?>
                                        <span class="matewa-agency-table-pill is-ready">No local flags</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        <p class="matewa-agency-client-board-note">Manual setup packs are now saved locally. Export setup file, PDF attachment/review and live client install remain separate locked checkpoints.</p>
    </section>

    <div class="matewa-agency-hub-grid">
        <article class="matewa-agency-hub-card">
            <span class="dashicons dashicons-yes-alt" aria-hidden="true"></span>
            <h4>Agency overview</h4>
            <p><strong><?php echo esc_html($matewa_agency_name); ?></strong></p>
            <p>Own-site access is verified. This free agency key unlocks the agency website only.</p>
            <?php if ('' !== $matewa_agency_id) : ?>
                <small>Agency ID: <?php echo esc_html($matewa_agency_id); ?></small>
            <?php endif; ?>
        </article>

        <article class="matewa-agency-hub-card">
            <span class="dashicons dashicons-admin-network" aria-hidden="true"></span>
            <h4>Client setup packs</h4>
            <p>Manual setup packs are active. Export setup file and PDF attachment/review come in later setup-pack checkpoints.</p>
            <small>Next after bundle seats: client setup pack builder.</small>
        </article>

        <article class="matewa-agency-hub-card">
            <span class="dashicons dashicons-tickets-alt" aria-hidden="true"></span>
            <h4>Licence seats</h4>
            <p>Client seats are separate from this free agency own-site key and come from paid agency bundles.</p>
            <small>Own-site key seats: <?php echo esc_html((string) $matewa_agency_own_site_client_seats); ?> · Bundle seats: <?php echo esc_html((string) $matewa_agency_client_seats); ?></small>
        </article>

        <article class="matewa-agency-hub-card">
            <span class="dashicons dashicons-shield" aria-hidden="true"></span>
            <h4>Verification status</h4>
            <p>Status: <?php echo esc_html($matewa_agency_status_label); ?></p>
            <small>Last checked: <?php echo esc_html($matewa_agency_checked_label); ?></small>
            <?php if ('' !== $matewa_agency_expiry) : ?>
                <small>Access expiry: <?php echo esc_html($matewa_agency_expiry); ?></small>
            <?php endif; ?>
        </article>
    </div>

    <script type="application/json" id="matewa-agency-client-selector-data">
        <?php echo wp_json_encode($matewa_agency_client_selector_categories, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>
    </script>
    <script>
    (function () {
        const root = document.querySelector('[data-matewa-agency-client-selector]');
        const dataEl = document.getElementById('matewa-agency-client-selector-data');
        if (!root || !dataEl) {
            return;
        }

        const categorySelect = root.querySelector('[data-agency-client-category]');
        const businessSelect = root.querySelector('[data-agency-client-business-type]');
        const industryLabel = root.querySelector('[data-agency-client-industry-label]');
        const categoryLabel = root.querySelector('[data-agency-client-category-label]');
        const businessLabel = root.querySelector('[data-agency-client-business-label]');
        const chipTitle = root.querySelector('[data-agency-client-chip-title]');
        const chipGrid = root.querySelector('[data-agency-client-chip-grid]');
        let data = {};

        try {
            data = JSON.parse(dataEl.textContent || '{}');
        } catch (error) {
            data = {};
        }

        function optionLabel(select) {
            if (!select || !select.options || select.selectedIndex < 0) {
                return '';
            }
            return select.options[select.selectedIndex].textContent.trim();
        }

        function getCurrentOption() {
            const categoryKey = categorySelect ? categorySelect.value : '';
            const businessKey = businessSelect ? businessSelect.value : '';
            const category = data[categoryKey] || {};
            const options = category.options || {};
            return options[businessKey] || null;
        }

        function renderBusinessOptions() {
            if (!categorySelect || !businessSelect) {
                return;
            }

            const category = data[categorySelect.value] || {};
            const options = category.options || {};
            const previous = businessSelect.value;
            businessSelect.innerHTML = '';

            Object.keys(options).forEach(function (key) {
                const item = options[key] || {};
                const option = document.createElement('option');
                option.value = key;
                option.textContent = item.display_label || key;
                businessSelect.appendChild(option);
            });

            if (previous && options[previous]) {
                businessSelect.value = previous;
            }
        }

        function normaliseChipLabel(value) {
            return String(value || '').replace(/[\r\n]+/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 34);
        }

        function applyChipVerticalClass(input) {
            if (!input) {
                return;
            }
            const shell = input.closest('.matewa-chip-editor-chip');
            if (!shell) {
                return;
            }
            const label = normaliseChipLabel(input.value);
            shell.classList.toggle('is-single-line', label.length <= 12);
        }

        function bindChipFitInputs() {
            if (!chipGrid) {
                return;
            }
            chipGrid.querySelectorAll('textarea[name="matewa_agency_client_chip_labels[]"]').forEach(function (input) {
                applyChipVerticalClass(input);
                if (input.dataset.matewaAgencyChipBound === '1') {
                    return;
                }
                input.dataset.matewaAgencyChipBound = '1';
                input.addEventListener('input', function () {
                    const clean = normaliseChipLabel(input.value);
                    if (input.value !== clean) {
                        input.value = clean;
                    }
                    applyChipVerticalClass(input);
                });
            });
        }

        function renderChips() {
            if (!chipGrid) {
                return;
            }

            const current = getCurrentOption();
            const labels = current && Array.isArray(current.chips) && current.chips.length ? current.chips.slice(0, 6) : ['Get a quote', 'Pricing', 'Availability', 'Ask a question', 'Book a job', 'Something else'];
            chipGrid.innerHTML = '';

            labels.forEach(function (label) {
                const item = document.createElement('div');
                const shell = document.createElement('div');
                const input = document.createElement('textarea');
                item.className = 'matewa-chip-editor-item';
                shell.className = 'matewa-chip-editor-chip';
                input.name = 'matewa_agency_client_chip_labels[]';
                input.value = normaliseChipLabel(label || '');
                input.maxLength = 34;
                input.rows = 2;
                input.autocomplete = 'off';
                input.setAttribute('aria-label', 'Visitor button label, maximum 34 characters over two visual rows');
                input.addEventListener('input', function () {
                    const clean = normaliseChipLabel(input.value);
                    if (input.value !== clean) {
                        input.value = clean;
                    }
                    applyChipVerticalClass(input);
                });
                shell.appendChild(input);
                applyChipVerticalClass(input);
                item.appendChild(shell);
                chipGrid.appendChild(item);
            });
        }

        function syncHiddenLabels() {
            const categoryText = optionLabel(categorySelect) || 'General';
            const businessText = optionLabel(businessSelect) || 'General';
            if (industryLabel) {
                industryLabel.value = categoryText;
            }
            if (categoryLabel) {
                categoryLabel.value = categoryText;
            }
            if (businessLabel) {
                businessLabel.value = businessText;
            }
            if (chipTitle) {
                chipTitle.textContent = businessText;
            }
        }

        function refreshAll() {
            renderBusinessOptions();
            syncHiddenLabels();
            renderChips();
        }

        if (categorySelect) {
            categorySelect.addEventListener('change', refreshAll);
        }
        if (businessSelect) {
            businessSelect.addEventListener('change', function () {
                syncHiddenLabels();
                renderChips();
            });
        }

        syncHiddenLabels();
        bindChipFitInputs();
    }());
    </script>
</div>
