<?php
/**
 * 247ChatMate — Agency Hub overview and bundle licence intake
 * Checkpoint: AGENCYKEYAGENCYMOVECOLLAPSE1
 *
 * Purpose:
 * - Prepare Agency Hub variables and include smaller display-only Agency Hub partials.
 * - Keep agency bundle, setup pack, page scan and remote push rendering separated for maintenance.
 * - Preserve existing agency setup pack, remote push, manual JSON fallback and client-site import behaviour.
 *
 * Does not:
 * - Change frontend widget, saved Visitor Buttons settings, chips, WhatsApp handoff, lead emails or weekly summary.
 * - Change agency bundle licence logic, remote push logic, manual JSON fallback, import mapping or seat logic.
 */

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_email_profile = function_exists('matewa_email_profile_get') ? matewa_email_profile_get('agency') : array();
$matewa_agency_email_profile = is_array($matewa_agency_email_profile) ? $matewa_agency_email_profile : array();
$matewa_agency_email_profile_status = function_exists('matewa_email_profile_status_label') ? matewa_email_profile_status_label($matewa_agency_email_profile) : '247ChatMate fallback active';
$matewa_agency_email_profile_note = function_exists('matewa_email_profile_effective_sender_note') ? matewa_email_profile_effective_sender_note('agency') : 'Emails send from the verified 247ChatMate/default route. Replies route using Reply-To.';
$matewa_email_profile_provider_options = function_exists('matewa_email_profile_provider_options') ? matewa_email_profile_provider_options() : array('fallback_247chatmate' => '247ChatMate fallback sender');

$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', 'client_pack_pages_scanned'], true) ? 'success' : 'warning';

$matewa_agency_remote_push_notice_code = isset($_GET['matewa_agency_remote_push_notice']) && is_scalar($_GET['matewa_agency_remote_push_notice'])
    ? sanitize_key(wp_unslash($_GET['matewa_agency_remote_push_notice']))
    : '';
$matewa_agency_remote_push_notice_message = '';
if ('' !== $matewa_agency_remote_push_notice_code) {
    $matewa_agency_remote_push_notice_message = function_exists('matewa_agency_remote_push_notice_message')
        ? matewa_agency_remote_push_notice_message($matewa_agency_remote_push_notice_code)
        : str_replace('_', ' ', $matewa_agency_remote_push_notice_code);
}
$matewa_agency_remote_push_success_codes = function_exists('matewa_agency_remote_push_success_codes') ? matewa_agency_remote_push_success_codes() : array('remote_push_ok');
$matewa_agency_remote_push_notice_type = in_array($matewa_agency_remote_push_notice_code, $matewa_agency_remote_push_success_codes, true) ? 'success' : 'warning';
$matewa_agency_remote_push_last = function_exists('matewa_agency_remote_push_get_last') ? matewa_agency_remote_push_get_last() : array();
$matewa_agency_remote_push_last = is_array($matewa_agency_remote_push_last) ? $matewa_agency_remote_push_last : array();

$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_routing_cleared'      => 'Last routing test result cleared.',
    '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', 'agency_routing_cleared');
$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_last_routing_send = get_option('matewa_agency_last_routing_send', array());
$matewa_agency_last_routing_send = is_array($matewa_agency_last_routing_send) ? $matewa_agency_last_routing_send : array();
$matewa_agency_last_routing_time = isset($matewa_agency_last_routing_send['time']) ? absint($matewa_agency_last_routing_send['time']) : 0;
$matewa_agency_last_routing_results = isset($matewa_agency_last_routing_send['results']) && is_array($matewa_agency_last_routing_send['results']) ? $matewa_agency_last_routing_send['results'] : array();
$matewa_agency_last_routing_test_id = isset($matewa_agency_last_routing_send['test_id']) ? sanitize_text_field((string) $matewa_agency_last_routing_send['test_id']) : '';

$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',
);
$matewa_agency_client_detected_pages = $matewa_agency_client_is_editing && isset($matewa_agency_client_edit_pack['detected_pages']) && is_array($matewa_agency_client_edit_pack['detected_pages'])
    ? array_values($matewa_agency_client_edit_pack['detected_pages'])
    : array();
$matewa_agency_client_selected_pages = $matewa_agency_client_is_editing && isset($matewa_agency_client_edit_pack['selected_pages']) && is_array($matewa_agency_client_edit_pack['selected_pages'])
    ? array_values($matewa_agency_client_edit_pack['selected_pages'])
    : array();
$matewa_agency_client_selected_page_urls = function_exists('matewa_agency_client_pack_page_urls')
    ? matewa_agency_client_pack_page_urls($matewa_agency_client_selected_pages)
    : array();
$matewa_agency_client_last_page_scan = $matewa_agency_client_is_editing && isset($matewa_agency_client_edit_pack['page_scan']) && is_array($matewa_agency_client_edit_pack['page_scan'])
    ? $matewa_agency_client_edit_pack['page_scan']
    : array();
?>

<?php
$matewa_agency_section_foundation_open = ('' !== $matewa_agency_setup_request_notice_message || '' !== $matewa_agency_routing_notice_message);
$matewa_agency_section_bundles_open = ('' !== $matewa_agency_bundle_notice_message || empty($matewa_agency_bundle_records));
$matewa_agency_client_import_has_notice = isset($_GET['matewa_agency_import_notice']) && is_scalar($_GET['matewa_agency_import_notice']);
$matewa_agency_client_import_has_pending = function_exists('matewa_agency_client_import_get_pending') && !empty(matewa_agency_client_import_get_pending());
$matewa_agency_client_import_open = $matewa_agency_client_import_has_notice || $matewa_agency_client_import_has_pending;
$matewa_agency_client_pdf_has_notice = isset($_GET['matewa_agency_client_pdf_notice']) && is_scalar($_GET['matewa_agency_client_pdf_notice']);

$matewa_agency_section_clients_open = (
    '' !== $matewa_agency_client_pack_notice_message
    || '' !== $matewa_agency_remote_push_notice_message
    || $matewa_agency_client_is_editing
    || $matewa_agency_client_import_open
    || $matewa_agency_client_pdf_has_notice
    || (isset($_GET['matewa_setup_key_notice']) && is_scalar($_GET['matewa_setup_key_notice']))
);
?>
<div class="matewa-agency-hub-shell" aria-label="Agency Hub overview">
    <?php require __DIR__ . '/agency-hub/overview.php'; ?>

    <div class="matewa-agency-hub-accordion" aria-label="Agency Hub sections">
        <details class="matewa-agency-hub-section-detail" <?php echo $matewa_agency_section_foundation_open ? 'open' : ''; ?>>
            <summary>
                <span>Agency foundation and emails</span>
                <small>Set the agency contact route, setup request email and support summary.</small>
            </summary>
            <div class="matewa-agency-hub-section-body">
                <?php require __DIR__ . '/agency-hub/foundation-controls.php'; ?>
            </div>
        </details>

        <details class="matewa-agency-hub-section-detail" <?php echo $matewa_agency_section_bundles_open ? 'open' : ''; ?>>
            <summary>
                <span>Agency bundle licences and seats</span>
                <small>Add/recheck bundles, manage seats and keep client licences separate from the free agency key.</small>
            </summary>
            <div class="matewa-agency-hub-section-body">
                <?php require __DIR__ . '/agency-hub/bundle-licences.php'; ?>
            </div>
        </details>

        <details class="matewa-agency-hub-section-detail" <?php echo $matewa_agency_section_clients_open ? 'open' : ''; ?>>
            <summary>
                <span>Client setup packs and remote setup</span>
                <small>Create packs, generate or paste setup keys, push setup, scan pages and export JSON fallback.</small>
            </summary>
            <div class="matewa-agency-hub-section-body">
                <?php require __DIR__ . '/agency-hub/client-setup-packs.php'; ?>
            </div>
        </details>

        <details class="matewa-agency-hub-section-detail matewa-agency-hub-section-detail--summary">
            <summary>
                <span>Agency support and parked roadmap notes</span>
                <small>Open if support asks for the future-safe summary cards.</small>
            </summary>
            <div class="matewa-agency-hub-section-body">
                <?php require __DIR__ . '/agency-hub/summary-cards.php'; ?>
            </div>
        </details>
    </div>

    <?php require __DIR__ . '/agency-hub/client-selector-script.php'; ?>
</div>
