<?php

namespace Clonable\Helpers;

class Session {
    const CLONABLE_VALIDATION_KEY = "clonable-validation-data";
    const EXPIRATION = 3600;

    private static function get_validation_data_key(): string {
        $sId = wp_get_session_token();
        return self::CLONABLE_VALIDATION_KEY . ':' . $sId;
    }

    private static function get_validation_data(): array {
        $trKey = self::get_validation_data_key();
        $tr = get_transient($trKey);
        if (is_array($tr)) {
            return $tr;
        } else {
            return [];
        }
    }

    /**
     * Saves the provided validation data or deletes it on null.
     *
     * @param $data ?array array of data to save, or null to delete all validation data
     * @return void
     */
    private static function save_validation_data(?array $data) {
        $trKey = self::get_validation_data_key();
        if ($data == null) {
            delete_transient($trKey);
        } else {
            set_transient($trKey, $data, self::EXPIRATION);
        }
    }

    public static function old($option_name, $default_value = false) {
        $validationData = self::get_validation_data();
        if (isset($validationData[$option_name])) {
            return $validationData[$option_name];
        }
        return get_option($option_name, $default_value);
    }

    public static function put_validation_data($key, $data) {
        $validationData = self::get_validation_data();
        $data = Json::handle_output(Json::handle_output($data));
        $validationData[$key] = $data;
        self::save_validation_data($validationData);
    }

    public static function clear_validation_data() {
        self::save_validation_data(null);
    }
}