<?php
if (!defined('ABSPATH')) {
    exit;
}

function ai_content_wizard_get_setting($key, $default = false) {
    global $wpdb;
    $table_name = $wpdb->prefix . 'ai_content_wizard_settings';
    $result = $wpdb->get_var($wpdb->prepare("SELECT setting_value FROM $table_name WHERE setting_key = %s", $key));

    if ($result !== null) {
        return maybe_unserialize($result);
    }

    $legacy_value = get_option($key, null);
    if ($legacy_value !== null) {
        return $legacy_value;
    }

    return $default;
}

function ai_content_wizard_update_setting($key, $value) {
    global $wpdb;
    $table_name = $wpdb->prefix . 'ai_content_wizard_settings';

    $result = $wpdb->replace($table_name, [
        'setting_key' => $key,
        'setting_value' => maybe_serialize($value)
    ]);

    if ($result === false || !empty($wpdb->last_error)) {
        update_option($key, $value);
    }
}

function ai_content_wizard_get_category_setting($category_id, $setting_key, $default = false) {
    global $wpdb;
    $table_name = $wpdb->prefix . 'ai_content_wizard_settings';
    $key = $category_id . '_' . $setting_key;
    $result = $wpdb->get_var($wpdb->prepare("SELECT setting_value FROM $table_name WHERE setting_key = %s", $key));

    if ($result !== null) {
        return maybe_unserialize($result);
    }

    $legacy_value = get_option($key, null);
    if ($legacy_value !== null) {
        return $legacy_value;
    }

    return $default;
}

function ai_content_wizard_update_category_setting($category_id, $setting_key, $value) {
    global $wpdb;
    $table_name = $wpdb->prefix . 'ai_content_wizard_settings';
    $key = $category_id . '_' . $setting_key;

    $result = $wpdb->replace($table_name, [
        'setting_key' => $key,
        'setting_value' => maybe_serialize($value)
    ]);

    if ($result === false || !empty($wpdb->last_error)) {
        update_option($key, $value);
    }
}
