<?php
/**
 * Agency Connection transparency page (LolaHub child side).
 *
 * @package LolaCore
 * @license GPL-2.0-or-later
 */

declare(strict_types=1);

if (!defined('ABSPATH')) {
    exit;
}

/** @var array{status: string, master_label: string, connected_at: string} $connection */
/** @var bool $connected */
/** @var array{entries: array<int, array<string, mixed>>, total: int} $log */
/** @var array{synced_at: string, fact_count: int, master_label: string}|null $reconcile */
/** @var array<string, string> $domains */
/** @var string[] $denied */
/** @var string $search */
/** @var int $page */
/** @var string $notice */
/** @var LolaCore\Hub\HubScope $scope */
/** @var string[] $allowedLabels */

$lolacore_total_pages = max(1, (int) ceil($log['total'] / 20));

$lolacore_notices = [
    'scope_saved'       => __('Access updated. The next remote action will use these limits.', 'lolacore'),
    'disconnected'      => __('Agency connection removed. Remote access from that LolaHub is off.', 'lolacore'),
    'memory_forgotten'  => __('Operator memory removed from this site. Your own memory is unchanged.', 'lolacore'),
];
?>
<div class="wrap lolacore-admin-wrap" id="lolacore-hub-transparency">
    <h1><?php echo esc_html__('Agency Connection', 'lolacore'); ?></h1>

    <?php if ($notice !== '' && isset($lolacore_notices[$notice])) : ?>
        <div class="notice notice-success is-dismissible"><p><?php echo esc_html($lolacore_notices[$notice]); ?></p></div>
    <?php endif; ?>

    <p class="description">
        <?php echo esc_html__(
            'See who can manage this site through LolaHub, what they may do, what they have done, and change or end the connection at any time.',
            'lolacore'
        ); ?>
    </p>

    <div class="lolacore-tab-content" style="max-width: 960px;">

        <section class="lc-card" style="margin-bottom: 24px; padding: 20px;">
            <h2><?php echo esc_html__('Connection', 'lolacore'); ?></h2>
            <?php if (!$connected) : ?>
                <p><?php echo esc_html__('No agency LolaHub is connected to this site right now.', 'lolacore'); ?></p>
            <?php else : ?>
                <p>
                    <?php
                    printf(
                        /* translators: 1: agency label, 2: connection date */
                        esc_html__('Connected to %1$s since %2$s.', 'lolacore'),
                        '<strong>' . esc_html($connection['master_label'] !== '' ? $connection['master_label'] : __('your agency', 'lolacore')) . '</strong>',
                        esc_html($connection['connected_at'])
                    );
                    ?>
                </p>
            <?php endif; ?>
        </section>

        <?php if ($connected) : ?>

        <section class="lc-card" style="margin-bottom: 24px; padding: 20px;">
            <h2><?php echo esc_html__('What they can do', 'lolacore'); ?></h2>
            <p><?php echo esc_html__('Uncheck an area to narrow what the agency may do on the next remote action.', 'lolacore'); ?></p>
            <?php if ($allowedLabels !== []) : ?>
                <p><em><?php echo esc_html(implode(', ', $allowedLabels)); ?></em></p>
            <?php endif; ?>

            <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                <?php wp_nonce_field('lolacore_hub_save_scope'); ?>
                <input type="hidden" name="action" value="lolacore_hub_save_scope" />
                <fieldset>
                    <legend class="screen-reader-text"><?php echo esc_html__('Allowed areas', 'lolacore'); ?></legend>
                    <?php foreach ($domains as $lolacore_domain_slug => $lolacore_domain_label) : ?>
                        <label style="display:block;margin:8px 0;">
                            <input type="checkbox" name="hub_allowed_domains[]" value="<?php echo esc_attr($lolacore_domain_slug); ?>"
                                <?php checked(!in_array($lolacore_domain_slug, $denied, true)); ?> />
                            <?php echo esc_html($lolacore_domain_label); ?>
                        </label>
                    <?php endforeach; ?>
                </fieldset>
                <?php submit_button(__('Save access limits', 'lolacore'), 'secondary', 'submit', false); ?>
            </form>
        </section>

        <section class="lc-card" style="margin-bottom: 24px; padding: 20px;">
            <h2><?php echo esc_html__('What they have done', 'lolacore'); ?></h2>
            <form method="get" style="margin-bottom: 12px;">
                <input type="hidden" name="page" value="<?php echo esc_attr(LolaCore\Hub\HubTransparencyPage::MENU_SLUG); ?>" />
                <input type="search" name="hub_log_search" value="<?php echo esc_attr($search); ?>"
                    placeholder="<?php echo esc_attr__('Search actions…', 'lolacore'); ?>" />
                <?php submit_button(__('Search', 'lolacore'), 'secondary', '', false); ?>
            </form>

            <?php if ($log['entries'] === []) : ?>
                <p><?php echo esc_html__('No remote actions recorded yet.', 'lolacore'); ?></p>
            <?php else : ?>
                <table class="widefat striped">
                    <thead>
                        <tr>
                            <th><?php echo esc_html__('When', 'lolacore'); ?></th>
                            <th><?php echo esc_html__('Action', 'lolacore'); ?></th>
                            <th><?php echo esc_html__('By', 'lolacore'); ?></th>
                            <th><?php echo esc_html__('Status', 'lolacore'); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($log['entries'] as $lolacore_log_entry) : ?>
                            <tr>
                                <td><?php echo esc_html((string) ($lolacore_log_entry['executed_at'] ?? '')); ?></td>
                                <td><?php echo esc_html((string) ($lolacore_log_entry['description'] ?? $lolacore_log_entry['action_type'] ?? '')); ?></td>
                                <td><?php echo esc_html((string) ($lolacore_log_entry['source'] ?? '')); ?></td>
                                <td><?php echo esc_html((string) ($lolacore_log_entry['status'] ?? '')); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                <?php if ($lolacore_total_pages > 1) : ?>
                    <p class="tablenav">
                        <?php
                        for ($lolacore_page_i = 1; $lolacore_page_i <= $lolacore_total_pages; $lolacore_page_i++) {
                            $lolacore_page_url = add_query_arg(
                                [
                                    'page'           => LolaCore\Hub\HubTransparencyPage::MENU_SLUG,
                                    'hub_log_page'   => $lolacore_page_i,
                                    'hub_log_search' => $search,
                                ],
                                admin_url('admin.php')
                            );
                            if ($lolacore_page_i === $page) {
                                echo '<strong> ' . esc_html((string) $lolacore_page_i) . ' </strong>';
                            } else {
                                echo '<a href="' . esc_url($lolacore_page_url) . '">' . esc_html((string) $lolacore_page_i) . '</a> ';
                            }
                        }
                        ?>
                    </p>
                <?php endif; ?>
            <?php endif; ?>
        </section>

        <section class="lc-card" style="margin-bottom: 24px; padding: 20px;">
            <h2><?php echo esc_html__('Operator memory', 'lolacore'); ?></h2>
            <?php if ($reconcile === null) : ?>
                <p><?php echo esc_html__('No memory sync from the agency has been recorded on this site yet.', 'lolacore'); ?></p>
            <?php else : ?>
                <p>
                    <?php
                    printf(
                        /* translators: 1: date/time, 2: number of facts */
                        esc_html__('Last sync: %1$s (%2$d facts from the agency).', 'lolacore'),
                        esc_html($reconcile['synced_at']),
                        (int) $reconcile['fact_count']
                    );
                    ?>
                </p>
            <?php endif; ?>
            <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>"
                onsubmit="return confirm('<?php echo esc_js(__('Remove operator memory from this site? Your own memory stays.', 'lolacore')); ?>');">
                <?php wp_nonce_field('lolacore_hub_forget_memory'); ?>
                <input type="hidden" name="action" value="lolacore_hub_forget_memory" />
                <?php submit_button(__('Forget operator memory', 'lolacore'), 'secondary', 'submit', false); ?>
            </form>
        </section>

        <section class="lc-card" style="margin-bottom: 24px; padding: 20px; border-left: 4px solid #d63638;">
            <h2><?php echo esc_html__('Disconnect', 'lolacore'); ?></h2>
            <p><?php echo esc_html__('Stop remote access from this agency immediately. You can pair again later from their LolaHub.', 'lolacore'); ?></p>
            <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>"
                onsubmit="return confirm('<?php echo esc_js(__('Disconnect this agency from your site?', 'lolacore')); ?>');">
                <?php wp_nonce_field('lolacore_hub_disconnect'); ?>
                <input type="hidden" name="action" value="lolacore_hub_disconnect" />
                <?php submit_button(__('Disconnect agency', 'lolacore'), 'delete', 'submit', false); ?>
            </form>
        </section>

        <?php endif; ?>
    </div>
</div>
