<?php

namespace WPSN\Modules\BulkTable\Admin;

use WPSN\Core\Container;

defined('ABSPATH') || exit;

/**
 * JSON export for SEO overrides.
 *
 * Designed for agency workflows and staging → production transfers.
 * Exports only override fields (no resolved/template values) and includes
 * permalink + slug so imports can map rows even when IDs differ.
 */
final class BulkTableJsonExporter
{
    private Container $container;

    public function __construct(Container $container)
    {
        $this->container = $container;
    }

    /**
     * @param array{pt:string,status:string,filter:string,s:string} $filters
     */
    public function buildJson(array $filters, int $maxRows = 5000, bool $includeEmptyFields = false): string
    {
        $query = new BulkTableQuery($this->container);
        [$items] = $query->fetch($filters, $maxRows, 0);

        $payload = [
            'schema' => 'wpsn-overrides-v1',
            'generated_at' => gmdate('c'),
            'source' => [
                'site_url' => home_url('/'),
                'plugin_version' => defined('WPSN_VERSION') ? WPSN_VERSION : '',
            ],
            'filters' => $filters,
            'items' => [],
        ];

        foreach ($items as $row) {
            $id = (int) ($row['ID'] ?? 0);
            if ($id <= 0) {
                continue;
            }

            $permalink = get_permalink($id);
            $permalink = is_string($permalink) ? $permalink : '';

            $overrides = [
                'seo_title' => (string) ($row['seo_title'] ?? ''),
                'meta_description' => (string) ($row['meta_description'] ?? ''),
                'canonical' => (string) ($row['canonical'] ?? ''),
                'robots_index' => (string) ($row['robots_index'] ?? ''),
                'robots_follow' => (string) ($row['robots_follow'] ?? ''),
                'og_title' => (string) ($row['og_title'] ?? ''),
                'og_description' => (string) ($row['og_description'] ?? ''),
                'og_image' => (string) ($row['og_image'] ?? ''),
                'twitter_title' => (string) ($row['twitter_title'] ?? ''),
                'twitter_description' => (string) ($row['twitter_description'] ?? ''),
                'twitter_image' => (string) ($row['twitter_image'] ?? ''),
            ];

            if (!$includeEmptyFields) {
                // Export only non-empty override values (safer for staging → production).
                $overrides = array_filter(
                    $overrides,
                    static fn($v): bool => is_string($v) && trim($v) !== ''
                );

                if (empty($overrides)) {
                    continue;
                }
            }

            $payload['items'][] = [
                'type' => 'post',
                'id' => $id,
                'post_type' => (string) ($row['post_type'] ?? ''),
                'post_status' => (string) ($row['post_status'] ?? ''),
                'slug' => (string) get_post_field('post_name', $id),
                'permalink' => $permalink,
                'overrides' => $overrides,
            ];
        }

        $json = wp_json_encode($payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        return is_string($json) ? $json : '';
    }
}
