<?php

namespace Formatrica\Integrations;

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

/**
 * Counts which forms have a given integration enabled — the data source for
 * the Free one-form-per-install webhook limit (P-WH1). Counts ALL forms
 * regardless of active state (an inactive form still holds the slot; deleting
 * or disabling the integration frees it).
 */
final class Integration_Usage_Snapshot
{
    /**
     * Forms (id + title) that have $integration_id enabled, excluding one form.
     *
     * @return list<array{id:int,title:string}>
     */
    public function forms_using(string $integration_id, int $exclude_form_id = 0): array
    {
        global $wpdb;

        $table = $wpdb->prefix . 'formatrica_forms';
        // The forms table stores options JSON in the `settings` column. LIKE
        // prefilter narrows the scan; the JSON decode below is the
        // authoritative check (a title mentioning "zapier" can't
        // false-positive the decode step).
        $like = '%' . $wpdb->esc_like('"' . $integration_id . '"') . '%';
        // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter -- table name from $wpdb->prefix; one-off admin-screen scan, no cache value
        $rows = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT id, title, settings FROM {$table} WHERE settings LIKE %s",
                $like
            ),
            ARRAY_A
        );
        // phpcs:enable

        $out = [];
        foreach ((array) $rows as $row) {
            $form_id = (int) ($row['id'] ?? 0);
            if ($form_id === 0 || $form_id === $exclude_form_id) {
                continue;
            }
            $options = json_decode((string) ($row['settings'] ?? ''), true);
            if (!is_array($options)) {
                continue;
            }
            if (!empty($options['integrations'][$integration_id]['enabled'])) {
                $out[] = ['id' => $form_id, 'title' => (string) ($row['title'] ?? '')];
            }
        }

        return $out;
    }

    /**
     * The first OTHER form using the integration, or null when the slot is free.
     *
     * @return array{id:int,title:string}|null
     */
    public function first_other_form_using(string $integration_id, int $exclude_form_id): ?array
    {
        $forms = $this->forms_using($integration_id, $exclude_form_id);
        return $forms[0] ?? null;
    }
}
