<?php
if (!defined('ABSPATH')) exit;
if (!current_user_can('manage_options')) wp_die('Unauthorized');

$live_gateway_scan_limit = 500;

$page_slug = 'afb-live-client-gateways';
$page_url = add_query_arg([
    'page' => $page_slug,
], admin_url('admin.php'));

$settings_page_url = add_query_arg([
    'page' => 'afb-client-gateway-settings',
], admin_url('admin.php'));

$fetch_gateway_rows = static function(int $limit) {
    global $wpdb;

    $option_prefix = '_transient_afb_token_task_';
    $pattern = $wpdb->esc_like($option_prefix) . '%';

    $rows = $wpdb->get_results(
        $wpdb->prepare(
            "SELECT option_name, option_value FROM {$wpdb->options} WHERE option_name LIKE %s ORDER BY option_id DESC LIMIT %d",
            $pattern,
            $limit
        ),
        ARRAY_A
    ) ?: [];

    $parsed = [];

    foreach ($rows as $row) {
        $option_name = (string)($row['option_name'] ?? '');
        if ($option_name === '' || strpos($option_name, $option_prefix) !== 0) {
            continue;
        }

        $token = sanitize_text_field((string) substr($option_name, strlen($option_prefix)));
        if ($token === '') {
            continue;
        }

        $task_gid = preg_replace('/\D+/', '', (string)($row['option_value'] ?? ''));
        if ($task_gid === '') {
            continue;
        }

        $expires_at = (int) get_option('_transient_timeout_afb_token_task_' . $token);

        $gateway_url = add_query_arg(
            ['task_gid' => $task_gid],
            home_url('/task-dashboard/' . $token . '/')
        );

        $task_name = '';
        $project_name = '';

        $cache_path = trailingslashit(AFB_PLUGIN_DIR) . 'cache/tasks-summary-' . $token . '.json';
        if (is_readable($cache_path)) {
            $cache_raw = @file_get_contents($cache_path);
            if ($cache_raw !== false) {
                $cache_data = json_decode($cache_raw, true);
                if (is_array($cache_data)) {
                    $cache_task = $cache_data['parent'] ?? $cache_data['task'] ?? $cache_data;
                    $task_name = sanitize_text_field((string)($cache_task['name'] ?? ''));
                    $project_name = sanitize_text_field((string)($cache_task['projects'][0]['name'] ?? ''));
                }
            }
        }

        $parsed[] = [
            'token' => $token,
            'task_gid' => $task_gid,
            'task_name' => $task_name,
            'project_name' => $project_name,
            'url' => esc_url_raw($gateway_url),
            'expires_at' => $expires_at,
            'expires_label' => $expires_at > 0
                ? wp_date('Y-m-d H:i', $expires_at)
                : 'No expiry found',
        ];
    }

    return $parsed;
};

$expire_token_locally = static function(string $token): bool {
    $token = sanitize_text_field($token);
    if ($token === '') {
        return false;
    }

    if (function_exists('afb_expire_gateway_token_local')) {
        afb_expire_gateway_token_local($token, 'admin_purged');
        return true;
    }

    set_transient('afb_token_reason_' . $token, 'admin_purged', DAY_IN_SECONDS);
    delete_transient('afb_token_task_' . $token);
    delete_transient('afb_token_pin_hash_' . $token);

    $cache_file = trailingslashit(AFB_PLUGIN_DIR) . 'cache/tasks-summary-' . $token . '.json';
    if (file_exists($cache_file)) {
        @unlink($cache_file);
    }

    $settings_file = trailingslashit(AFB_PLUGIN_DIR) . 'cache/gateway-settings-' . sanitize_file_name($token) . '.json';
    if (file_exists($settings_file)) {
        @unlink($settings_file);
    }

    return true;
};

$build_redirect = static function(array $args = []) use ($page_url): string {
    if (empty($args)) {
        return $page_url;
    }

    return add_query_arg($args, $page_url);
};

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['afb_gateway_action'])) {
    check_admin_referer('afb_live_gateway_actions');

    $action = sanitize_key((string) wp_unslash($_POST['afb_gateway_action']));

    if ($action === 'delete_one') {
        $token = sanitize_text_field((string) wp_unslash($_POST['gateway_token'] ?? ''));
        if ($token === '') {
            wp_safe_redirect($build_redirect([
                'notice' => 'error',
                'message' => 'Missing gateway token.',
            ]));
            exit;
        }

        $deleted = $expire_token_locally($token);

        wp_safe_redirect($build_redirect($deleted
            ? [
                'notice' => 'deleted',
                'token' => $token,
            ]
            : [
                'notice' => 'error',
                'message' => 'Could not delete that gateway.',
            ]
        ));
        exit;
    }

    if ($action === 'purge_before_date') {
        $cutoff_date = sanitize_text_field((string) wp_unslash($_POST['purge_before_date'] ?? ''));
        if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $cutoff_date)) {
            wp_safe_redirect($build_redirect([
                'notice' => 'error',
                'message' => 'Please provide a valid purge date.',
            ]));
            exit;
        }

        $cutoff_dt = DateTimeImmutable::createFromFormat('!Y-m-d H:i:s', $cutoff_date . ' 23:59:59', wp_timezone());
        if (!$cutoff_dt) {
            wp_safe_redirect($build_redirect([
                'notice' => 'error',
                'message' => 'Could not parse the purge date.',
            ]));
            exit;
        }

        $cutoff_ts = (int) $cutoff_dt->getTimestamp();
        $all_gateways = $fetch_gateway_rows($live_gateway_scan_limit);

        $purged_count = 0;
        foreach ($all_gateways as $gateway) {
            $expires_at = (int) ($gateway['expires_at'] ?? 0);
            if ($expires_at <= 0 || $expires_at > $cutoff_ts) {
                continue;
            }

            if ($expire_token_locally((string) $gateway['token'])) {
                $purged_count++;
            }
        }

        wp_safe_redirect($build_redirect([
            'notice' => 'purged',
            'count' => $purged_count,
            'date' => $cutoff_date,
        ]));
        exit;
    }
}

$notice = sanitize_key((string)($_GET['notice'] ?? ''));
$notice_message = '';
$notice_class = 'notice-info';

if ($notice === 'deleted') {
    $notice_class = 'notice-success';
    $deleted_token = sanitize_text_field((string)($_GET['token'] ?? ''));
    $notice_message = $deleted_token !== ''
        ? ('Gateway deleted: ' . $deleted_token)
        : 'Gateway deleted.';
} elseif ($notice === 'purged') {
    $notice_class = 'notice-success';
    $purged_count = max(0, (int)($_GET['count'] ?? 0));
    $purged_date = sanitize_text_field((string)($_GET['date'] ?? ''));
    $notice_message = sprintf(
        'Purged %d gateway%s with expiry on or before %s.',
        $purged_count,
        $purged_count === 1 ? '' : 's',
        $purged_date !== '' ? $purged_date : 'the selected date'
    );
} elseif ($notice === 'error') {
    $notice_class = 'notice-error';
    $notice_message = sanitize_text_field((string)($_GET['message'] ?? 'Action failed.'));
}

$today_local = wp_date('Y-m-d');
$default_purge_date = sanitize_text_field((string)($_GET['date'] ?? $today_local));
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $default_purge_date)) {
    $default_purge_date = $today_local;
}

$all_gateways = $fetch_gateway_rows($live_gateway_scan_limit);
$now = time();

$live_gateways = [];
foreach ($all_gateways as $gateway) {
    $expires_at = (int)($gateway['expires_at'] ?? 0);
    if ($expires_at > 0 && $expires_at <= $now) {
        continue;
    }
    $live_gateways[] = $gateway;
}

?>

<div class="wrap">
    <h1>Live Client Gateways</h1>
    <p class="description" style="max-width:980px; margin-top: 6px;">
        This page lists active Client Gateway links currently stored in WordPress transient mappings.
    </p>

    <p class="description" style="max-width:980px; margin-top: 2px;">
        Expires comes from the WordPress transient timeout option for each token: <code>_transient_timeout_afb_token_task_{token}</code>.
    </p>

    <p class="description" style="max-width:980px; margin-top: 2px;">
        Showing <?= esc_html((string)count($live_gateways)) ?> live gateway<?= count($live_gateways) === 1 ? '' : 's' ?> (scan limit: <?= esc_html((string)$live_gateway_scan_limit) ?>).
    </p>

    <?php if ($notice_message !== ''): ?>
        <div class="notice <?= esc_attr($notice_class) ?> is-dismissible" style="max-width:980px; margin-top: 12px;">
            <p><?= esc_html($notice_message) ?></p>
        </div>
    <?php endif; ?>

    <form method="post" style="margin-top: 12px; display:flex; flex-wrap:wrap; align-items:flex-end; gap:12px; max-width:980px;">
        <?php wp_nonce_field('afb_live_gateway_actions'); ?>
        <input type="hidden" name="afb_gateway_action" value="purge_before_date" />

        <p style="margin:0;">
            <label for="afb-purge-before-date"><strong>Purge gateways with expiry on or before</strong></label><br>
            <input
                type="date"
                id="afb-purge-before-date"
                name="purge_before_date"
                value="<?= esc_attr($default_purge_date) ?>"
                required
            />
        </p>

        <p style="margin:0;">
            <button
                type="submit"
                class="button button-secondary"
                onclick="return confirm('Purge all gateways on or before this date? This expires each selected link immediately.');"
            >
                Purge By Date
            </button>
        </p>
    </form>

    <p style="margin-top: 12px;">
        <a class="button button-secondary" href="<?= esc_url($settings_page_url) ?>">Back to Client Gateway Settings</a>
    </p>

    <?php if (empty($live_gateways)): ?>
        <div class="notice notice-info" style="max-width:980px; margin-top: 12px;">
            <p>No live Client Gateway links are currently active.</p>
        </div>
    <?php else: ?>
        <table class="widefat striped" style="max-width:1280px; margin-top: 14px;">
            <thead>
                <tr>
                    <th>Gateway URL</th>
                    <th style="width:190px;">Task GID</th>
                    <th style="width:310px;">Task Name</th>
                    <th style="width:220px;">Project</th>
                    <th style="width:180px;">Expires</th>
                    <th style="width:220px;">Token</th>
                    <th style="width:160px;">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($live_gateways as $live_gateway): ?>
                    <tr>
                        <td>
                            <a href="<?= esc_url($live_gateway['url']) ?>" target="_blank" rel="noopener noreferrer">
                                <?= esc_html($live_gateway['url']) ?>
                            </a>
                        </td>
                        <td><code><?= esc_html($live_gateway['task_gid']) ?></code></td>
                        <td><?= esc_html($live_gateway['task_name'] !== '' ? $live_gateway['task_name'] : 'Unknown task') ?></td>
                        <td><?= esc_html($live_gateway['project_name'] !== '' ? $live_gateway['project_name'] : 'Unknown project') ?></td>
                        <td><?= esc_html($live_gateway['expires_label']) ?></td>
                        <td><code><?= esc_html($live_gateway['token']) ?></code></td>
                        <td>
                            <form method="post" style="margin:0;">
                                <?php wp_nonce_field('afb_live_gateway_actions'); ?>
                                <input type="hidden" name="afb_gateway_action" value="delete_one" />
                                <input type="hidden" name="gateway_token" value="<?= esc_attr($live_gateway['token']) ?>" />
                                <button
                                    type="submit"
                                    class="button button-link-delete"
                                    onclick="return confirm('Delete this gateway link now? This cannot be undone.');"
                                >
                                    Delete
                                </button>
                            </form>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>
</div>
