<?php

/**
 * Class Setting
 *
 *
 * @package LinkFiliate\Models
 * @since 1.0.0
 */

namespace LinkFiliate\App\Models;

if (! defined('ABSPATH')) {
    exit;
}

class Setting
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table;

    /**
     * Constructor for $wpdb and table name
     */
    public function __construct()
    {
        global $wpdb;
        $this->table = $wpdb->prefix . LINKFILIATE_DB_BASE . '_settings';
    }

    /**
     * Get general setting.
     *
     * @return array|null
     */
    public function get_general()
    {
        global $wpdb;

        $general_settings = $wpdb->get_var(
            $wpdb->prepare(
                "SELECT option_value FROM %i WHERE option_key = %s LIMIT 1",
                $this->table,
                'general'
            )
        );

        // Decode JSON if it exists
        return $general_settings ? json_decode($general_settings, true) : null;
    }

    /**
     * Update general setting.
     *
     * @param array $data Key-value pairs to update
     * @return bool True on success, false on failure
     */
    public function update_general($data = [])
    {
        global $wpdb;

        if (empty($data)) {
            return false;
        }

        $settings_json  = wp_json_encode($data);

        // Check if settings already exist
        $existing = $wpdb->get_var(
            $wpdb->prepare("SELECT id FROM %i WHERE option_key = %s", $this->table, 'general')
        );

        if ($existing) {
            // Update existing settings
            $updated = $wpdb->update(
                $this->table,
                array(
                    'option_value' => $settings_json,
                    'updated_at'   => gmdate('Y-m-d H:i:s')
                ),
                array('option_key' => 'general'),
                array('%s', '%s'),
                array('%s')
            );

            if ($updated === false) {
                return new \WP_REST_Response([
                    'status'  => 'error',
                    'message' => 'Failed to update general settings'
                ], 500);
            }
        } else {
            // Insert new settings
            $inserted = $wpdb->insert(
                $this->table,
                array(
                    'option_key'   => 'general',
                    'option_value' => $settings_json,
                    'created_at'   => gmdate('Y-m-d H:i:s'),
                    'updated_at'   => gmdate('Y-m-d H:i:s')
                ),
                array('%s', '%s', '%s', '%s')
            );

            if ($inserted === false) {
                return new \WP_REST_Response([
                    'status'  => 'error',
                    'message' => 'Failed to insert general settings'
                ], 500);
            }
        }

        return true; // success
    }
}
