<?php
declare(strict_types=1);
defined('ABSPATH') || exit;

class DSProofwp_Form_Settings_Repository
{
    private wpdb $wpdb;
    private string $table;
    private DSProofwp_Recaptcha_Service $recaptcha_service;

    public function __construct(wpdb $wpdb, DSProofwp_Recaptcha_Service $recaptcha_service)
    {
        $this->wpdb              = $wpdb;
        $this->table             = $wpdb->prefix . 'dsproofwp_form_settings';
        $this->recaptcha_service = $recaptcha_service;
    }

    public function get(): ?array
    {
        $query = "SELECT id, form_settings, created_at, updated_at
            FROM {$this->table}
            WHERE id = 1
            LIMIT 1";

        // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Static query with no user input; table name is derived from $wpdb->prefix.
        $row = $this->wpdb->get_row($query, ARRAY_A);

        if (! $row) {
            return null;
        }

        $mapped = $this->map_row($row);

        // Inject a safe boolean flag — never expose the secret key to the frontend
        $mapped['recaptcha_secret_key_set'] = $this->recaptcha_service->has_secret_key();

        // Ensure the actual secret key is never returned to the frontend
        unset($mapped['recaptcha_secret_key']);

        return $mapped;
    }

    public function update(array $data): ?array
    {
        // Extract and encrypt the secret key before persisting anything else.
        // It must never be stored in the form_settings JSON column.
        if (array_key_exists('recaptcha_secret_key', $data)) {
            $raw_secret = trim((string) $data['recaptcha_secret_key']);
            $this->recaptcha_service->save_secret_key($raw_secret);
            unset($data['recaptcha_secret_key']);
        }

        // Strip metadata fields that are not part of settings
        unset($data['id'], $data['created_at'], $data['updated_at'], $data['recaptcha_secret_key_set']);

        $this->wpdb->update(
            $this->table,
            ['form_settings' => wp_json_encode($data)],
            ['id' => 1],
            ['%s'],
            ['%d']
        );

        return $this->get();
    }

    private function map_row(array $row): array
    {
        $settings = json_decode((string) $row['form_settings'], true);
        if (! is_array($settings)) {
            $settings = [];
        }

        return array_merge($settings, [
            'id'         => (int) $row['id'],
            'created_at' => (string) $row['created_at'],
            'updated_at' => (string) $row['updated_at'],
        ]);
    }
}
