<?php

declare(strict_types=1);

namespace PrettyLinks\Pro\Redirect;

// 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.

/**
 * Per-link dynamic redirection mode (v3 drop-in, mutually exclusive).
 *
 * Reads the `prli_dynamic_redirection` link meta; values:
 *   'none'   — no dynamic redirect (static URL only)
 *   'rotate' — URL rotation
 *   'geo'    — country-based targeting
 *   'tech'   — device / browser / OS targeting
 *   'time'   — date/time-based targeting
 *
 * An unset/empty meta is treated like v3's default: if rotations exist,
 * behave like `rotate`; otherwise `none`. This preserves v3's implicit
 * "rotation auto-enables when entries exist" behavior for sites that
 * never explicitly saved a mode.
 */
final class DynamicMode
{
    public const META_KEY = 'prli_dynamic_redirection';

    public const NONE   = 'none';
    public const ROTATE = 'rotate';
    public const GEO    = 'geo';
    public const TECH   = 'tech';
    public const TIME   = 'time';

    /**
     * Resolve the configured dynamic redirect mode for a link.
     *
     * @param integer $linkId The link ID to look up.
     *
     * @return string The dynamic mode constant value.
     */
    public static function forLink(int $linkId): string
    {
        if ($linkId <= 0) {
            return self::NONE;
        }
        global $wpdb;
        $value = $wpdb->get_var(
            $wpdb->prepare(
                "SELECT meta_value FROM {$wpdb->prefix}prli_link_metas
                 WHERE link_id = %d AND meta_key = %s
                 ORDER BY id ASC LIMIT 1",
                $linkId,
                self::META_KEY
            )
        );
        if (is_string($value) && $value !== '') {
            return $value;
        }
        // V3 drop-in: empty meta means "rotate if rotations exist, else none".
        return self::hasRotations($linkId) ? self::ROTATE : self::NONE;
    }

    /**
     * Whether the given mode is the "none" mode.
     *
     * @param string $mode The dynamic mode value.
     *
     * @return boolean True when the mode is none.
     */
    public static function isNone(string $mode): bool
    {
        return $mode === self::NONE;
    }

    /**
     * Whether the given mode supports visitor targeting.
     *
     * @param string $mode The dynamic mode value.
     *
     * @return boolean True when the mode allows targeting.
     */
    public static function allowsTargeting(string $mode): bool
    {
        return $mode === self::GEO
            || $mode === self::TECH
            || $mode === self::TIME;
    }

    /**
     * Whether the given mode supports URL rotation.
     *
     * @param string $mode The dynamic mode value.
     *
     * @return boolean True when the mode allows rotation.
     */
    public static function allowsRotation(string $mode): bool
    {
        return $mode === self::ROTATE;
    }

    /**
     * Whether the link has any configured rotation rows.
     *
     * @param integer $linkId The link ID to check.
     *
     * @return boolean True when rotations exist for the link.
     */
    private static function hasRotations(int $linkId): bool
    {
        global $wpdb;
        return (bool) $wpdb->get_var(
            $wpdb->prepare(
                "SELECT 1 FROM {$wpdb->prefix}prli_link_rotations
                 WHERE link_id = %d LIMIT 1",
                $linkId
            )
        );
    }
}
