<?php

if ( !defined( 'ABSPATH' ) ) {
    exit;
}
class BSPP_Settings_Repository {
    private $table;

    /**
     * Free-tier defaults always present.
     *
     * @var array
     */
    private const FREE_DEFAULTS = [
        'enable_subscription'          => 1,
        'subscription_price_monthly'   => 9.99,
        'subscription_price_annual'    => 99,
        'posts_become_paid_after_days' => 7,
        'bspp_onboarding_completed'    => 0,
        'bspp_paywall_launched'        => 0,
    ];

    public function __construct() {
        global $wpdb;
        $this->table = $wpdb->prefix . 'bobasoftware_pp_settings';
    }

    /**
     * All settings defaults (free + Pro when premium package present).
     *
     * @return array
     */
    public static function defaults() {
        $defaults = self::FREE_DEFAULTS;
        return $defaults;
    }

    public function get( $key, $default = null ) {
        global $wpdb;
        $value = $wpdb->get_var( $wpdb->prepare( "SELECT setting_value FROM {$this->table} WHERE setting_key = %s", $key ) );
        if ( $value !== null ) {
            return maybe_unserialize( $value );
        }
        $defaults = self::defaults();
        if ( array_key_exists( $key, $defaults ) ) {
            return $defaults[$key];
        }
        return $default;
    }

    public function set( $key, $value ) {
        global $wpdb;
        $exists = $wpdb->get_var( $wpdb->prepare( "SELECT setting_key FROM {$this->table} WHERE setting_key = %s LIMIT 1", $key ) );
        if ( $exists !== null ) {
            return $wpdb->update( $this->table, [
                'setting_value' => maybe_serialize( $value ),
            ], [
                'setting_key' => $key,
            ] );
        }
        return $wpdb->insert( $this->table, [
            'setting_key'   => $key,
            'setting_value' => maybe_serialize( $value ),
        ] );
    }

    public function seed_defaults_if_missing() {
        global $wpdb;
        foreach ( self::defaults() as $key => $value ) {
            $exists = $wpdb->get_var( $wpdb->prepare( "SELECT setting_key FROM {$this->table} WHERE setting_key = %s LIMIT 1", $key ) );
            if ( $exists !== null ) {
                continue;
            }
            $wpdb->insert( $this->table, [
                'setting_key'   => $key,
                'setting_value' => maybe_serialize( $value ),
            ] );
        }
    }

}
