<?php
$qahm_brain = new QAHM_Brain();
class QAHM_Brain extends QAHM_File_Data {
    public const NONCE_API  = 'api';
    public function __construct() {
        // Retrieve a list of brains
        //$this->brains = $this->get_brains();
		add_action( 'init', array( $this, 'get_brains' ) );

        // Register AJAX functions
        $this->regist_ajax_func( 'ajax_get_brains' );
        $this->regist_ajax_func( 'ajax_connect_brain' );
    }

    public function ajax_get_brains() {
        if ( ! is_user_logged_in() ) {
            wp_die('you don not have privilege to access this page.');
        }
        // Verify nonce and check maintenance status
        $nonce = $this->wrap_filter_input( INPUT_POST, 'nonce' );
        if ( ! wp_verify_nonce( $nonce, self::NONCE_API ) || $this->is_maintenance() ) {
            http_response_code( 400 );
            die( 'nonce error' );
        }
        // Retrieve the brainSlug from the POST data
        $brain_slug = $this->wrap_filter_input( INPUT_POST, 'brain_slug' );
        $response = $this->get_brains( $brain_slug );
        // Return the JSON response
        wp_send_json_success($response);
    }
    public function get_brains( $brain_slug = null ) {

        $brain_dir = $this->get_data_dir_path( 'brains' );
        $brains = array();

        // Get the list of brain directories
        $dirs = glob( $brain_dir . '*', GLOB_ONLYDIR );

        foreach ( $dirs as $dir ) {
            $slug = basename( $dir );

            // Skip if a specific brain slug is requested and this is not it
            if ( $brain_slug && $slug !== $brain_slug ) {
                continue;
            }

            // Get the config file
            $config_file = $dir . '/config.json';
            if ( ! file_exists( $config_file ) ) {
                continue;
            }

            // Read the config file
            $config = json_decode( file_get_contents( $config_file ), true );
            if ( ! $config ) {
                continue;
            }

            // Create the brain array
            $brain = array(
                'slug'        => $slug,
                'name'        => $config['name'] ?? '',
                'description' => $config['description'] ?? '',
                'author'      => $config['author'] ?? '',
                'version'     => $config['version'] ?? '',
            );


			// translations.jsonの読み込み
			$translations = null;
			$locale = get_locale(); // 例: en_US
			$file_path = $dir . "/translations-{$locale}.json";

			// フォールバック（例: en だけ指定された場合に translations-en.json を見る）
			if ( ! file_exists($file_path) ) {
				$lang = substr($locale, 0, 2);
				$file_path = $dir . "/translations-{$lang}.json";
			}

			// さらにフォールバック（translations.json）
			if ( ! file_exists($file_path) ) {
				$file_path = $dir . "/translations.json";
			}

			// JSON をデコードして連想配列に
			if ( file_exists($file_path) ) {
				$json = file_get_contents( $file_path );
				$translations = json_decode( $json, true );
			}

			// エラー対策
			if ( ! is_array( $translations ) ) {
				$translations = [];
			}

			$brain['name'] = $this->resolve_translation($brain['name'], $translations);
			$brain['description'] = $this->resolve_translation($brain['description'], $translations);

            // Get the character image
            $images = $config['images'] ?? '';
            if ( $images ) {
                $relative_dir = str_replace( WP_CONTENT_DIR, '', $dir );
				foreach ( $images as $key => $image ) {
					$brain['images'][$key] = content_url($relative_dir . '/' . $image );
				}

				// Set brain file from brain_slug directory
				$brain_file = $dir . '/brain.php';
				if ( file_exists( $brain_file ) ) {
					$brain['brain_file'] = $brain_file;
				}
            }

            $brains[ $slug ] = $brain;
        }

        return $brains;
    }

    public function ajax_connect_brain() 	{
        if ( ! is_user_logged_in() ) {
            wp_die('you don not have privilege to access this page.');
        }
        // Verify nonce and check maintenance status
        $nonce = $this->wrap_filter_input( INPUT_POST, 'nonce' );
        if ( ! wp_verify_nonce( $nonce, self::NONCE_API )  ) {
            http_response_code( 401 );
            die( 'nonce error' );
        }
        session_start();

        $brain_slug = $this->wrap_filter_input(INPUT_POST, 'brain_slug');
        $state = $this->wrap_filter_input(INPUT_POST, 'state');
        $free = $this->wrap_filter_input(INPUT_POST, 'free');
        $tracking_id = $this->wrap_filter_input(INPUT_POST, 'tracking_id');

        if ( $state === 'start' ) {
            session_unset();
        }
        if ( !$state ) {
            $state = 'start';
        }

		if ( $free ) {
			$class_name = $this->make_brain_class_name($brain_slug);
			$_SESSION[$class_name]['session_free'] = $free;
		}

        // Return the JSON response
        $response = $this->connect_brain( $brain_slug, $state, $tracking_id );
        if ( ! $response ) {
            http_response_code( 404 );
            die( 'brain not found' );
        }
        wp_send_json_success($response);
    }
    public function connect_brain( $brain_slug, $state, $tracking_id = 'all' ) {
        $brain_config = $this->get_brains( $brain_slug );
        if ( ! isset( $brain_config[$brain_slug]['brain_file'] ) ) {
            return false;
        }
        require_once $brain_config[$brain_slug]['brain_file'];
        $brain_dir_name = dirname( $brain_config[$brain_slug]['brain_file'] );
        $class_name  = $this->make_brain_class_name( $brain_slug );
        if ( isset( $_SESSION[$class_name] )) {
            $brain_class = new $class_name( $tracking_id, $brain_dir_name, $state, $_SESSION[ $class_name ] );
        } else {
            $brain_class = new $class_name( $tracking_id, $brain_dir_name, $state );
        }
        $brain_class->progress_story();

        $response = array(
            'execute' => $brain_class->execute,
        );
        //save variables to session
        foreach ( get_object_vars( $brain_class ) as $key => $value) {
            if ( strpos( $key, 'session_' ) === 0 ) {
                $_SESSION[ $class_name ][ $key ] = $value;
            }
        }
        return $response;
    }
    public function make_brain_class_name ( $brain_slug ) {
        $c_brains_slug = ucfirst( $brain_slug );
        return $c_brains_slug . '_Brain';
    }

	private function resolve_translation($key, $translations) {
		if (strpos($key, '.') !== false) {
			list($section, $subkey) = explode('.', $key, 2);
			if (isset($translations[$section][$subkey])) {
				return $translations[$section][$subkey];
			}
		}
		return $key; // 翻訳が見つからない場合はキーをそのまま返す
	}
}
