<?php
/**
 * 247ChatMate — Agency remote setup local test facility
 *
 * Checkpoint: AGENCYLOCALSETUPPUSHTEST1
 *
 * Purpose:
 * - Let an Agency Hub admin test the remote setup import path on the current site.
 * - Use an existing saved setup pack and a temporary local one-time setup key.
 * - Run the same client receive/import/key-consume logic without needing a second fresh WordPress site.
 * - Restore any pre-existing real setup key record after the test, so this support tool does not disrupt a live handover key.
 *
 * Does not:
 * - Use WordPress admin usernames or passwords.
 * - Install plugins remotely.
 * - Activate licences or change agency seat rules.
 * - Touch widget rendering, chips, WhatsApp handoff or lead routing beyond the imported setup values.
 */

defined('ABSPATH') || exit;

if (!class_exists('Matewa_Agency_Remote_Push_Local_Test_Request')) {
    class Matewa_Agency_Remote_Push_Local_Test_Request {
        private $params;
        private $body;
        private $headers;

        public function __construct($params, $body = '', $headers = array()) {
            $this->params = is_array($params) ? $params : array();
            $this->body = is_string($body) ? $body : '';
            $this->headers = is_array($headers) ? $headers : array();
        }

        public function get_json_params() {
            return $this->params;
        }

        public function get_body() {
            return $this->body;
        }

        public function get_header($name) {
            $name = strtolower((string) $name);
            foreach ($this->headers as $key => $value) {
                if (strtolower((string) $key) === $name) {
                    return $value;
                }
            }
            return '';
        }
    }
}

if (!function_exists('matewa_agency_remote_push_test_redirect_url')) {
    function matewa_agency_remote_push_test_redirect_url($notice = '') {
        $args = array(
            'page'                 => '247chatmate',
            'matewa_saved_section' => 'agency',
        );

        if ('' !== (string) $notice) {
            $args['matewa_agency_remote_push_notice'] = sanitize_key((string) $notice);
        }

        return add_query_arg($args, admin_url('admin.php')) . '#matewa-agency-remote-push-test-panel';
    }
}

if (!function_exists('matewa_agency_remote_push_test_redirect')) {
    function matewa_agency_remote_push_test_redirect($notice) {
        wp_safe_redirect(matewa_agency_remote_push_test_redirect_url($notice));
        exit;
    }
}

if (!function_exists('matewa_agency_remote_push_test_response_data')) {
    function matewa_agency_remote_push_test_response_data($response) {
        $status = 200;
        $data = array();

        if (is_object($response) && method_exists($response, 'get_status')) {
            $status = absint($response->get_status());
        }

        if (is_object($response) && method_exists($response, 'get_data')) {
            $data = $response->get_data();
        } elseif (is_array($response)) {
            $data = $response;
        }

        $data = is_array($data) ? $data : array();
        return array('status' => $status, 'data' => $data);
    }
}


if (!function_exists('matewa_agency_remote_push_test_key_snapshot')) {
    function matewa_agency_remote_push_test_key_snapshot() {
        $snapshot = array(
            'has_record'  => false,
            'record'      => array(),
            'has_flash'   => false,
            'flash'       => array(),
            'flash_ttl'   => 10 * MINUTE_IN_SECONDS,
        );

        if (defined('MATEWA_AGENCY_CLIENT_SETUP_KEY_OPTION')) {
            $record = get_option(MATEWA_AGENCY_CLIENT_SETUP_KEY_OPTION, null);
            if (is_array($record) && !empty($record)) {
                $snapshot['has_record'] = true;
                $snapshot['record'] = $record;
            }
        }

        if (function_exists('matewa_agency_client_setup_key_flash_transient_name')) {
            $flash = get_transient(matewa_agency_client_setup_key_flash_transient_name());
            if (is_array($flash) && !empty($flash)) {
                $snapshot['has_flash'] = true;
                $snapshot['flash'] = $flash;
            }
        }

        return $snapshot;
    }
}

if (!function_exists('matewa_agency_remote_push_test_restore_key_snapshot')) {
    function matewa_agency_remote_push_test_restore_key_snapshot($snapshot) {
        $snapshot = is_array($snapshot) ? $snapshot : array();
        $restored_record = false;

        if (defined('MATEWA_AGENCY_CLIENT_SETUP_KEY_OPTION')) {
            if (!empty($snapshot['has_record']) && isset($snapshot['record']) && is_array($snapshot['record'])) {
                update_option(MATEWA_AGENCY_CLIENT_SETUP_KEY_OPTION, $snapshot['record'], false);
                $restored_record = true;
            } else {
                delete_option(MATEWA_AGENCY_CLIENT_SETUP_KEY_OPTION);
            }
        }

        if (function_exists('matewa_agency_client_setup_key_flash_transient_name')) {
            $flash_name = matewa_agency_client_setup_key_flash_transient_name();
            delete_transient($flash_name);
            if (!empty($snapshot['has_flash']) && isset($snapshot['flash']) && is_array($snapshot['flash'])) {
                set_transient($flash_name, $snapshot['flash'], 10 * MINUTE_IN_SECONDS);
            }
        }

        return $restored_record;
    }
}

if (!function_exists('matewa_agency_remote_push_test_handle_local')) {
    function matewa_agency_remote_push_test_handle_local() {
        if (!is_admin() || !current_user_can('manage_options')) {
            wp_die(esc_html__('You do not have permission to test setup pushes.', '247chatmate'));
        }

        check_admin_referer('matewa_agency_remote_push_local_test', 'matewa_agency_remote_push_test_nonce');

        $attempted_at = function_exists('matewa_agency_remote_push_now') ? matewa_agency_remote_push_now() : time();
        $request_id = function_exists('matewa_agency_remote_push_request_id') ? matewa_agency_remote_push_request_id() : ('test_' . time());
        $pack_id = isset($_POST['matewa_agency_remote_push_test_pack_id']) ? sanitize_key((string) wp_unslash($_POST['matewa_agency_remote_push_test_pack_id'])) : '';
        $client_site_url = esc_url_raw(home_url('/'));

        $last_base = array(
            'checkpoint'      => 'AGENCYLOCALSETUPPUSHTEST1',
            'attempted_at'    => $attempted_at,
            'request_id'      => $request_id,
            'pack_id'         => $pack_id,
            'client_site_url' => $client_site_url,
            'endpoint_url'    => 'local_loopback',
            'ok'              => false,
            'test_mode'       => true,
            'transport'       => 'local_loopback',
        );

        if ('' === $pack_id) {
            if (function_exists('matewa_agency_remote_push_store_last')) {
                matewa_agency_remote_push_store_last(array_merge($last_base, array('notice' => 'remote_push_test_missing_pack')));
            }
            matewa_agency_remote_push_test_redirect('remote_push_test_missing_pack');
        }

        if (!function_exists('matewa_agency_hub_is_active') || !matewa_agency_hub_is_active()) {
            if (function_exists('matewa_agency_remote_push_store_last')) {
                matewa_agency_remote_push_store_last(array_merge($last_base, array('notice' => 'remote_push_agency_required')));
            }
            matewa_agency_remote_push_test_redirect('remote_push_agency_required');
        }

        if (!function_exists('matewa_agency_client_pack_get_record_by_id') || !function_exists('matewa_agency_client_pack_build_export_payload')) {
            if (function_exists('matewa_agency_remote_push_store_last')) {
                matewa_agency_remote_push_store_last(array_merge($last_base, array('notice' => 'remote_push_payload_failed')));
            }
            matewa_agency_remote_push_test_redirect('remote_push_payload_failed');
        }

        if (!function_exists('matewa_agency_client_setup_key_create') || !function_exists('matewa_agency_remote_push_build_request_body') || !function_exists('matewa_agency_remote_push_rest_receive')) {
            if (function_exists('matewa_agency_remote_push_store_last')) {
                matewa_agency_remote_push_store_last(array_merge($last_base, array(
                    'notice'  => 'remote_push_test_failed',
                    'message' => 'Local test handlers are unavailable.',
                )));
            }
            matewa_agency_remote_push_test_redirect('remote_push_test_failed');
        }

        $record = matewa_agency_client_pack_get_record_by_id($pack_id);
        if (empty($record) || !is_array($record)) {
            if (function_exists('matewa_agency_remote_push_store_last')) {
                matewa_agency_remote_push_store_last(array_merge($last_base, array('notice' => 'remote_push_pack_not_found')));
            }
            matewa_agency_remote_push_test_redirect('remote_push_pack_not_found');
        }

        $payload = matewa_agency_client_pack_build_export_payload($record);
        $json = wp_json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        if (!is_array($payload) || !is_string($json) || '' === $json) {
            if (function_exists('matewa_agency_remote_push_store_last')) {
                matewa_agency_remote_push_store_last(array_merge($last_base, array('notice' => 'remote_push_payload_failed')));
            }
            matewa_agency_remote_push_test_redirect('remote_push_payload_failed');
        }

        $payload_hash = function_exists('matewa_agency_client_import_payload_hash')
            ? matewa_agency_client_import_payload_hash($payload)
            : hash('sha256', $json);

        $key_snapshot = function_exists('matewa_agency_remote_push_test_key_snapshot')
            ? matewa_agency_remote_push_test_key_snapshot()
            : array('has_record' => false, 'record' => array(), 'has_flash' => false, 'flash' => array());
        $restored_existing_key = false;

        $key_result = matewa_agency_client_setup_key_create();
        $setup_key = isset($key_result['plain_key']) ? (string) $key_result['plain_key'] : '';
        if ('' === $setup_key) {
            if (function_exists('matewa_agency_remote_push_test_restore_key_snapshot')) {
                $restored_existing_key = matewa_agency_remote_push_test_restore_key_snapshot($key_snapshot);
            }
            if (function_exists('matewa_agency_remote_push_store_last')) {
                matewa_agency_remote_push_store_last(array_merge($last_base, array(
                    'notice'              => 'remote_push_test_failed',
                    'message'             => 'Temporary local setup key could not be created.',
                    'payload_hash'        => $payload_hash,
                    'setup_key_restored'  => $restored_existing_key,
                    'plain_key_stored'    => false,
                )));
            }
            matewa_agency_remote_push_test_redirect('remote_push_test_failed');
        }

        $body = matewa_agency_remote_push_build_request_body($setup_key, $payload, $pack_id, $client_site_url, $request_id);
        $body['checkpoint'] = 'AGENCYLOCALSETUPPUSHTEST1';
        $body['test_facility'] = array(
            'mode'       => 'local_loopback',
            'created_at' => gmdate('c'),
        );

        $body_json = wp_json_encode($body, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        if (!is_string($body_json) || '' === $body_json) {
            if (function_exists('matewa_agency_client_setup_key_revoke')) {
                matewa_agency_client_setup_key_revoke();
            }
            if (function_exists('matewa_agency_remote_push_test_restore_key_snapshot')) {
                $restored_existing_key = matewa_agency_remote_push_test_restore_key_snapshot($key_snapshot);
            }
            if (function_exists('matewa_agency_remote_push_store_last')) {
                matewa_agency_remote_push_store_last(array_merge($last_base, array(
                    'notice'              => 'remote_push_payload_failed',
                    'payload_hash'        => $payload_hash,
                    'setup_key_restored'  => $restored_existing_key,
                    'plain_key_stored'    => false,
                )));
            }
            matewa_agency_remote_push_test_redirect('remote_push_payload_failed');
        }

        $request = new Matewa_Agency_Remote_Push_Local_Test_Request(
            $body,
            $body_json,
            array('x-247chatmate-setup-key' => $setup_key)
        );

        $response = matewa_agency_remote_push_rest_receive($request);
        $normalised = matewa_agency_remote_push_test_response_data($response);
        $response_code = absint($normalised['status']);
        $data = is_array($normalised['data']) ? $normalised['data'] : array();
        $ok = !empty($data['ok']);
        $message = isset($data['message']) ? sanitize_text_field((string) $data['message']) : ($ok ? 'Local loopback test imported the setup.' : 'Local loopback test failed.');

        $temporary_key_id = isset($key_result['record']['key_id']) ? sanitize_key((string) $key_result['record']['key_id']) : '';
        $temporary_key_consumed = false;
        $temporary_key_record = function_exists('matewa_agency_client_setup_key_get_record') ? matewa_agency_client_setup_key_get_record() : array();
        if (is_array($temporary_key_record) && '' !== $temporary_key_id && $temporary_key_id === sanitize_key((string) ($temporary_key_record['key_id'] ?? ''))) {
            $temporary_key_consumed = !empty($temporary_key_record['used_at']);
        }

        if (!$ok && function_exists('matewa_agency_client_setup_key_revoke')) {
            matewa_agency_client_setup_key_revoke();
        }

        if (function_exists('matewa_agency_remote_push_test_restore_key_snapshot')) {
            $restored_existing_key = matewa_agency_remote_push_test_restore_key_snapshot($key_snapshot);
        }

        if (function_exists('matewa_agency_remote_push_store_last')) {
            matewa_agency_remote_push_store_last(array_merge($last_base, array(
                'ok'                         => $ok,
                'notice'                     => $ok ? 'remote_push_test_ok' : 'remote_push_test_failed',
                'message'                    => $message,
                'response_code'              => $response_code,
                'payload_hash'               => isset($data['payload_hash']) ? sanitize_text_field((string) $data['payload_hash']) : $payload_hash,
                'setup_pack_id'              => isset($data['setup_pack_id']) ? sanitize_key((string) $data['setup_pack_id']) : $pack_id,
                'temporary_key_id'           => $temporary_key_id,
                'temporary_key_consumed'     => $temporary_key_consumed,
                'setup_key_restored'         => $restored_existing_key,
                'plain_key_stored'           => false,
            )));
        }

        matewa_agency_remote_push_test_redirect($ok ? 'remote_push_test_ok' : 'remote_push_test_failed');
    }
}
add_action('admin_post_matewa_agency_remote_push_local_test', 'matewa_agency_remote_push_test_handle_local');

if (!function_exists('matewa_agency_remote_push_test_render_action_form')) {
    function matewa_agency_remote_push_test_render_action_form() {
        ?>
        <form id="matewa-agency-remote-push-local-test-form" class="matewa-admin-hidden-action-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" aria-hidden="true">
            <input type="hidden" name="action" value="matewa_agency_remote_push_local_test">
            <?php wp_nonce_field('matewa_agency_remote_push_local_test', 'matewa_agency_remote_push_test_nonce'); ?>
        </form>
        <?php
    }
}
