<?php

namespace GriffinForms\Includes\Integrations\Mailchimp;

use GriffinForms\Config;

class SyncStateStore
{
    public function getState(int $submission_id): array
    {
        $meta = $this->getSubmissionMeta($submission_id);
        $state = $meta[Contract::SUBMISSION_META_KEY] ?? [];

        return is_array($state) ? $state : [];
    }

    public function saveState(int $submission_id, array $state): bool
    {
        if ($submission_id <= 0) {
            return false;
        }

        $meta = $this->getSubmissionMeta($submission_id);
        $state['updated_at'] = gmdate('c');
        $meta[Contract::SUBMISSION_META_KEY] = $state;

        return $this->updateSubmissionMeta($submission_id, $meta);
    }

    public function mergeState(int $submission_id, array $changes): bool
    {
        if ($submission_id <= 0) {
            return false;
        }

        $state = $this->getState($submission_id);
        $state = array_replace($state, $changes);
        $state['updated_at'] = gmdate('c');

        return $this->saveState($submission_id, $state);
    }

    private function getSubmissionMeta(int $submission_id): array
    {
        if ($submission_id <= 0) {
            return [];
        }

        global $wpdb;
        $table = Config::getInstance()->getTable('submission');
        $raw_meta = $wpdb->get_var(
            $wpdb->prepare(
                "SELECT submission_meta FROM %i WHERE id = %d",
                $table,
                $submission_id
            )
        );

        if (!is_string($raw_meta) || $raw_meta === '') {
            return [];
        }

        $decoded = json_decode($raw_meta, true);
        return is_array($decoded) ? $decoded : [];
    }

    private function updateSubmissionMeta(int $submission_id, array $meta): bool
    {
        global $wpdb;
        $table = Config::getInstance()->getTable('submission');
        $updated = $wpdb->update(
            $table,
            ['submission_meta' => wp_json_encode($meta)],
            ['id' => $submission_id],
            ['%s'],
            ['%d']
        );

        return $updated !== false;
    }
}
