<?php

declare(strict_types=1);

namespace PrettyLinks\Pro\Reports;

// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
// phpcs:disable WordPress.DB.PreparedSQL.NotPrepared
// phpcs:disable WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery
// phpcs:disable WordPress.DB.DirectDatabaseQuery.NoCaching
// phpcs:disable WordPress.DB.SlowDBQuery.slow_db_query_meta_key
// phpcs:disable WordPress.DB.SlowDBQuery.slow_db_query_meta_value
// phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter
// Custom plugin tables (prli_*): table names interpolated from $wpdb->prefix (trusted),
// user values bind through $wpdb->prepare(). No caching: these tables are the source
// of truth for click/redirect data and must read-through. "meta_key"/"meta_value" here
// refer to our own prli_link_metas table, not wp_postmeta.

/**
 * Contributes the "split test enabled" WHERE fragment to the shared
 * `prli_links_query_clauses` filter. Activated when the REST caller
 * passes `split_test=1` — backs the "Split tests only" segment in the
 * Lite Links list.
 *
 * The per-link flag lives in `prli_link_metas` under
 * `prli-enable-split-test` with value `'1'` (see LinkPayloadExtension).
 */
class SplitTestLinksFilter
{
    /**
     * Add a split-test filter clause to the link list query.
     *
     * @param  array{0: array<int, string>, 1: array<int, mixed>} $clauses The accumulated WHERE clause parts and params.
     * @param  array<string, mixed>                               $args    The link list query arguments.
     * @return array{0: array<int, string>, 1: array<int, mixed>}
     */
    public function apply(array $clauses, array $args): array
    {
        $flag = (string) ($args['split_test'] ?? '');
        if ($flag !== '1') {
            return $clauses;
        }
        global $wpdb;
        [$where, $params] = $clauses;
        $metas            = $wpdb->prefix . 'prli_link_metas';
        $where[]          = "id IN (
            SELECT link_id FROM {$metas}
            WHERE meta_key = 'prli-enable-split-test' AND meta_value = '1'
        )";
        return [$where, $params];
    }

    /**
     * True when at least one link has split-test enabled. Used to drive
     * the "Split tests only" filter visibility in the admin UI.
     */
    public static function anyEnabled(): bool
    {
        global $wpdb;
        $metas = $wpdb->prefix . 'prli_link_metas';
        $sql   = "SELECT 1 FROM {$metas}
                  WHERE meta_key = 'prli-enable-split-test' AND meta_value = '1'
                  LIMIT 1";
        return (bool) $wpdb->get_var($sql);
    }
}
