<?php
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Templates use local variables supplied by the render context.
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

$connection = isset( $connection ) && is_array( $connection ) ? $connection : array();

$store_url       = isset( $connection['store_url'] ) ? (string) $connection['store_url'] : '';
$settings_url    = isset( $connection['settings_url'] ) ? (string) $connection['settings_url'] : '';
$preferences_url = isset( $connection['preferences_url'] ) ? (string) $connection['preferences_url'] : '';
$ping_url        = isset( $connection['ping_url'] ) ? (string) $connection['ping_url'] : '';
$import_url      = isset( $connection['import_url'] ) ? (string) $connection['import_url'] : '';
$site_url        = isset( $connection['site_url'] ) ? (string) $connection['site_url'] : '';
$enabled         = ! empty( $connection['enabled'] );
$configured      = ! empty( $connection['configured'] );
$has_app_pass    = ! empty( $connection['app_pass'] );
$app_pass        = isset( $connection['app_pass'] ) ? (string) $connection['app_pass'] : '';
$regenerate_url  = isset( $connection['regenerate_action'] ) && (string) $connection['regenerate_action'] !== '' ? (string) $connection['regenerate_action'] : admin_url( 'admin-post.php' );
$nonce_name      = isset( $connection['regenerate_nonce_name'] ) && (string) $connection['regenerate_nonce_name'] !== '' ? (string) $connection['regenerate_nonce_name'] : '_wpnonce';
$nonce           = isset( $connection['regenerate_nonce'] ) ? (string) $connection['regenerate_nonce'] : '';
$regenerate_id   = isset( $connection['regenerate_form_id'] ) && (string) $connection['regenerate_form_id'] !== '' ? (string) $connection['regenerate_form_id'] : 'nexdirectory-regenerate-extension-app-pass';
$return_url      = isset( $connection['return_url'] ) ? (string) $connection['return_url'] : '';

$format_timestamp = static function ( $value ) {
    if ( is_numeric( $value ) ) {
        $timestamp = (int) $value;
    } elseif ( is_string( $value ) && $value !== '' ) {
        $timestamp = strtotime( $value );
    } else {
        $timestamp = false;
    }

    if ( ! $timestamp ) {
        return __( 'Not yet recorded', 'nexdirectory' );
    }

    return wp_date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), $timestamp, wp_timezone() );
};

$handshake_at = $format_timestamp( isset( $connection['last_handshake_at'] ) ? $connection['last_handshake_at'] : '' );
$import_at    = $format_timestamp( isset( $connection['last_import_at'] ) ? $connection['last_import_at'] : '' );
$route_at     = $format_timestamp( isset( $connection['last_route_at'] ) ? $connection['last_route_at'] : '' );
$import_state = isset( $connection['last_import_status'] ) ? sanitize_text_field( (string) $connection['last_import_status'] ) : '';
$last_route   = isset( $connection['last_route'] ) ? sanitize_text_field( (string) $connection['last_route'] ) : '';
$connection_values = array(
    'site-url'             => array(
        'label' => __( 'Site URL', 'nexdirectory' ),
        'value' => $site_url,
    ),
    'ping-endpoint'        => array(
        'label' => __( 'Handshake endpoint', 'nexdirectory' ),
        'value' => $ping_url,
    ),
    'import-endpoint'      => array(
        'label' => __( 'Listing import endpoint', 'nexdirectory' ),
        'value' => $import_url,
    ),
    'preferences-endpoint' => array(
        'label' => __( 'Policy sync endpoint', 'nexdirectory' ),
        'value' => $preferences_url,
    ),
);
$connection_values = array_filter(
    $connection_values,
    static function ( $row ) {
        return is_array( $row ) && ! empty( $row['value'] );
    }
);

if ( $import_state === '' ) {
    $import_state = __( 'No import recorded yet', 'nexdirectory' );
} else {
    $import_state = ucwords( str_replace( array( '-', '_' ), ' ', $import_state ) );
}
?>
<div class="wrap nexdirectory-admin-premium nexdirectory-operations-chrome-extension">
    <?php $this->render_admin_premium_shell_styles(); ?>

    <section class="nexdirectory-admin-hero" aria-labelledby="nexdirectory-extension-operations-title">
        <span class="nexdirectory-admin-hero-kicker"><?php esc_html_e( 'Directory Operations', 'nexdirectory' ); ?></span>
        <h1 id="nexdirectory-extension-operations-title"><?php esc_html_e( 'Chrome Extension Connector', 'nexdirectory' ); ?></h1>
        <p><?php esc_html_e( 'Review the connection that receives structured listing drafts from the Nex Directory Chrome Extension.', 'nexdirectory' ); ?></p>
    </section>

    <section class="nexdirectory-admin-panel" aria-labelledby="nexdirectory-extension-overview-title">
        <h2 id="nexdirectory-extension-overview-title"><span class="dashicons dashicons-admin-generic" aria-hidden="true"></span><?php esc_html_e( 'Connection overview', 'nexdirectory' ); ?></h2>
        <div class="nexdirectory-admin-grid">
            <div class="nexdirectory-admin-stat-card">
                <p class="nexdirectory-admin-stat-label"><?php esc_html_e( 'Connector', 'nexdirectory' ); ?></p>
                <p class="nexdirectory-admin-stat-value"><?php echo esc_html( $enabled ? __( 'Enabled', 'nexdirectory' ) : __( 'Disabled', 'nexdirectory' ) ); ?></p>
            </div>
            <div class="nexdirectory-admin-stat-card">
                <p class="nexdirectory-admin-stat-label"><?php esc_html_e( 'Configuration', 'nexdirectory' ); ?></p>
                <p class="nexdirectory-admin-stat-value"><?php echo esc_html( $configured ? __( 'Ready', 'nexdirectory' ) : __( 'Needs setup', 'nexdirectory' ) ); ?></p>
            </div>
            <div class="nexdirectory-admin-stat-card">
                <p class="nexdirectory-admin-stat-label"><?php esc_html_e( 'Last handshake', 'nexdirectory' ); ?></p>
                <p class="nexdirectory-admin-stat-value"><?php echo esc_html( $handshake_at ); ?></p>
            </div>
        </div>
    </section>

    <section class="nexdirectory-admin-panel" aria-labelledby="nexdirectory-extension-install-title">
        <h2 id="nexdirectory-extension-install-title"><span class="dashicons dashicons-admin-plugins" aria-hidden="true"></span><?php esc_html_e( 'Install the extension', 'nexdirectory' ); ?></h2>
        <p><?php esc_html_e( 'Install the official extension in Chrome, then return here to confirm its connection and import activity.', 'nexdirectory' ); ?></p>
        <?php if ( $store_url !== '' ) : ?>
            <p>
                <a class="button button-primary" href="<?php echo esc_url( $store_url ); ?>" target="_blank" rel="noopener noreferrer external" aria-label="<?php esc_attr_e( 'Install the Nex Directory Chrome Extension from the Chrome Web Store (opens in a new tab)', 'nexdirectory' ); ?>">
                    <span class="dashicons dashicons-external" aria-hidden="true"></span>
                    <?php esc_html_e( 'Install from Chrome Web Store', 'nexdirectory' ); ?>
                </a>
            </p>
            <p class="description"><?php esc_html_e( 'Opens the official Chrome Web Store listing.', 'nexdirectory' ); ?></p>
        <?php else : ?>
            <p class="description"><?php esc_html_e( 'The Chrome Web Store link is not available right now.', 'nexdirectory' ); ?></p>
        <?php endif; ?>
    </section>

    <section class="nexdirectory-admin-panel" aria-labelledby="nexdirectory-extension-activity-title">
        <h2 id="nexdirectory-extension-activity-title"><span class="dashicons dashicons-chart-line" aria-hidden="true"></span><?php esc_html_e( 'Recent activity', 'nexdirectory' ); ?></h2>
        <div class="nexdirectory-admin-table-wrap">
            <table class="widefat striped">
                <tbody>
                    <tr>
                        <th scope="row"><?php esc_html_e( 'Last import', 'nexdirectory' ); ?></th>
                        <td><?php echo esc_html( $import_at ); ?></td>
                    </tr>
                    <tr>
                        <th scope="row"><?php esc_html_e( 'Last import status', 'nexdirectory' ); ?></th>
                        <td><?php echo esc_html( $import_state ); ?></td>
                    </tr>
                    <tr>
                        <th scope="row"><?php esc_html_e( 'Last route activity', 'nexdirectory' ); ?></th>
                        <td>
                            <?php echo esc_html( $route_at ); ?>
                            <?php if ( $last_route !== '' ) : ?>
                                <span class="description">&mdash; <?php echo esc_html( $last_route ); ?></span>
                            <?php endif; ?>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </section>

    <?php if ( ! empty( $connection_values ) ) : ?>
        <section class="nexdirectory-admin-panel" aria-labelledby="nexdirectory-extension-details-title">
            <h2 id="nexdirectory-extension-details-title"><span class="dashicons dashicons-admin-links" aria-hidden="true"></span><?php esc_html_e( 'Extension connection details', 'nexdirectory' ); ?></h2>
            <p><?php esc_html_e( 'Copy these values into the matching fields in the Chrome extension. The endpoints accept authenticated extension requests only.', 'nexdirectory' ); ?></p>
            <div class="nexdirectory-admin-table-wrap">
                <table class="widefat striped">
                    <tbody>
                        <?php foreach ( $connection_values as $copy_key => $connection_value ) : ?>
                            <?php
                            $input_id = 'nexdirectory-extension-' . sanitize_html_class( (string) $copy_key );
                            /* translators: %s: Connection field label. */
                            $copy_label = sprintf( __( 'Copy %s', 'nexdirectory' ), (string) $connection_value['label'] );
                            ?>
                            <tr>
                                <th scope="row"><label for="<?php echo esc_attr( $input_id ); ?>"><?php echo esc_html( (string) $connection_value['label'] ); ?></label></th>
                                <td>
                                    <div class="nexdirectory-admin-toolbar">
                                        <input id="<?php echo esc_attr( $input_id ); ?>" type="text" class="large-text code" value="<?php echo esc_attr( (string) $connection_value['value'] ); ?>" readonly autocomplete="off" spellcheck="false" data-nexdirectory-copy-source="<?php echo esc_attr( (string) $copy_key ); ?>">
                                        <button type="button" class="button button-secondary" data-nexdirectory-copy-button="<?php echo esc_attr( (string) $copy_key ); ?>" aria-live="polite" aria-label="<?php echo esc_attr( $copy_label ); ?>"><?php esc_html_e( 'Copy', 'nexdirectory' ); ?></button>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </section>
    <?php endif; ?>

    <section class="nexdirectory-admin-panel" aria-labelledby="nexdirectory-extension-app-pass-title">
        <h2 id="nexdirectory-extension-app-pass-title"><span class="dashicons dashicons-admin-network" aria-hidden="true"></span><?php esc_html_e( 'Extension App Pass', 'nexdirectory' ); ?></h2>
        <p><?php esc_html_e( 'Use this App Pass only in the Nex Directory Chrome Extension. Treat it like a password and do not share it in screenshots or messages.', 'nexdirectory' ); ?></p>
        <div class="nexdirectory-admin-toolbar">
            <label for="nexdirectory-extension-app-pass-value"><strong><?php esc_html_e( 'App Pass', 'nexdirectory' ); ?></strong></label>
            <input id="nexdirectory-extension-app-pass-value" type="text" class="regular-text code" value="<?php echo esc_attr( $app_pass ); ?>" readonly autocomplete="off" spellcheck="false" data-nexdirectory-copy-source="extension-app-pass" aria-describedby="nexdirectory-extension-app-pass-help" placeholder="<?php esc_attr_e( 'Generate an App Pass to connect the extension.', 'nexdirectory' ); ?>">
            <?php if ( $has_app_pass ) : ?>
                <button type="button" class="button button-secondary" data-nexdirectory-copy-button="extension-app-pass" aria-live="polite" aria-label="<?php esc_attr_e( 'Copy the Extension App Pass', 'nexdirectory' ); ?>"><?php esc_html_e( 'Copy App Pass', 'nexdirectory' ); ?></button>
            <?php endif; ?>
        </div>
        <p id="nexdirectory-extension-app-pass-help" class="description">
            <?php
            if ( $has_app_pass ) {
                esc_html_e( 'Copy this one-time value now. For security, it is hidden again after one hour.', 'nexdirectory' );
            } elseif ( $configured ) {
                esc_html_e( 'The App Pass is stored securely and cannot be revealed. Regenerate it to create a one-time replacement.', 'nexdirectory' );
            } else {
                esc_html_e( 'No App Pass has been generated yet.', 'nexdirectory' );
            }
            ?>
        </p>

        <form id="<?php echo esc_attr( $regenerate_id ); ?>" method="post" action="<?php echo esc_url( $regenerate_url ); ?>" class="nexdirectory-admin-toolbar">
            <input type="hidden" name="action" value="nexdirectory_regenerate_extension_app_pass">
            <input type="hidden" name="<?php echo esc_attr( $nonce_name ); ?>" value="<?php echo esc_attr( $nonce ); ?>">
            <?php if ( $return_url !== '' ) : ?>
                <input type="hidden" name="nexdirectory_redirect_to" value="<?php echo esc_url( $return_url ); ?>">
            <?php endif; ?>
            <?php if ( $configured ) : ?>
                <button type="button" class="button button-secondary" data-nexdirectory-pass-rotate-trigger aria-controls="nexdirectory-extension-pass-rotate-confirmation" aria-expanded="false">
                    <span class="dashicons dashicons-update" aria-hidden="true"></span>
                    <?php esc_html_e( 'Regenerate', 'nexdirectory' ); ?>
                </button>
                <div id="nexdirectory-extension-pass-rotate-confirmation" class="notice notice-warning inline" data-nexdirectory-pass-rotate-confirmation hidden>
                    <p><strong><?php esc_html_e( 'Disconnect the current extension?', 'nexdirectory' ); ?></strong></p>
                    <p><?php esc_html_e( 'The existing App Pass will stop working immediately. You will need to copy the replacement into every connected browser.', 'nexdirectory' ); ?></p>
                    <p>
                        <button type="submit" class="button button-secondary"><?php esc_html_e( 'Yes, regenerate App Pass', 'nexdirectory' ); ?></button>
                        <button type="button" class="button button-link" data-nexdirectory-pass-rotate-cancel><?php esc_html_e( 'Cancel', 'nexdirectory' ); ?></button>
                    </p>
                </div>
            <?php else : ?>
                <button type="submit" class="button button-secondary">
                    <span class="dashicons dashicons-update" aria-hidden="true"></span>
                    <?php esc_html_e( 'Generate', 'nexdirectory' ); ?>
                </button>
            <?php endif; ?>
            <span class="description"><?php esc_html_e( 'Generating a new App Pass immediately disconnects any extension still using the previous value.', 'nexdirectory' ); ?></span>
        </form>
    </section>

    <?php if ( $settings_url !== '' || $site_url !== '' ) : ?>
        <section class="nexdirectory-admin-panel" aria-labelledby="nexdirectory-extension-links-title">
            <h2 id="nexdirectory-extension-links-title"><span class="dashicons dashicons-admin-links" aria-hidden="true"></span><?php esc_html_e( 'Manage connection', 'nexdirectory' ); ?></h2>
            <div class="nexdirectory-admin-toolbar">
                <?php if ( $settings_url !== '' ) : ?>
                    <a class="button button-secondary" href="<?php echo esc_url( $settings_url ); ?>"><?php esc_html_e( 'Connector settings', 'nexdirectory' ); ?></a>
                <?php endif; ?>
                <?php if ( $site_url !== '' ) : ?>
                    <a class="button button-secondary" href="<?php echo esc_url( $site_url ); ?>" target="_blank" rel="noopener noreferrer"><?php esc_html_e( 'Open site', 'nexdirectory' ); ?></a>
                <?php endif; ?>
            </div>
        </section>
    <?php endif; ?>
</div>
