<?php
/**
 * JSON file-based storage replacing RedBeanPHP/MySQL
 * Stores mamont_status data as JSON files in /tmp/mamont/
 */

class MamontStorage {
    private static $dir = null;

    private static function getDir() {
        if (self::$dir === null) {
            self::$dir = sys_get_temp_dir() . '/mamont_data';
            if (!is_dir(self::$dir)) {
                mkdir(self::$dir, 0777, true);
            }
        }
        return self::$dir;
    }

    private static function getFile($mamontId) {
        return self::getDir() . '/' . preg_replace('/[^0-9]/', '', $mamontId) . '.json';
    }

    public static function create($mamontId) {
        $file = self::getFile($mamontId);
        if (!file_exists($file)) {
            $data = [
                'mamont_id' => $mamontId,
                'action_otp' => null,
                'action_push' => null,
                'action_balance' => null,
                'action_custom' => null,
                'action_failed' => null,
                'action_success' => null,
                'action_newcard' => null,
                'action_errcard' => null,
                'action_checksumm' => null,
                'action_support' => null,
                'action_error_otp' => null,
                'action_error_push' => null,
                'action_error_balance' => null,
                'action_error_custom' => null,
                'action_error_checksumm' => null,
                'mamont_custom' => null,
            ];
            file_put_contents($file, json_encode($data), LOCK_EX);
        }
    }

    public static function get($mamontId) {
        $file = self::getFile($mamontId);
        if (!file_exists($file)) {
            self::create($mamontId);
        }
        $content = file_get_contents($file);
        return json_decode($content, true) ?: [];
    }

    public static function setField($mamontId, $field, $value) {
        $data = self::get($mamontId);
        $data[$field] = $value;
        file_put_contents(self::getFile($mamontId), json_encode($data), LOCK_EX);
    }

    public static function clearField($mamontId, $field) {
        self::setField($mamontId, $field, null);
    }
}
