<?php

header('Content-Type: application/x-javascript; charset=utf-8');
header('Cache-Control: max-age=600');

// wp関連ファイルの読み込み
if ( ! defined( 'SHORTINIT' ) ) {
	define('SHORTINIT', true);
}
require_once '../../../wp-load.php' ;
require_once '../../../wp-settings.php' ;
require_once ABSPATH . WPINC . '/l10n.php';

wp_plugin_directory_constants();

$GLOBALS['wp_plugin_paths'] = array();
require_once ABSPATH . WPINC . '/link-template.php';

// qa-configの読み込み
(function() {
    foreach (array(
        WP_CONTENT_DIR . '/qa-zero-data/qa-config.php',
        WP_CONTENT_DIR . '/qa-heatmap-analytics-data/qa-config.php'
    ) as $config_path) {
        if (file_exists($config_path)) {
            require_once $config_path;
            return;
        }
    }
})();

// qa関連ファイルの読み込み
require_once 'qahm-const.php';
require_once 'class-qahm-base.php';
$qahm_base = new QAHM_Base;
$qahm_base->init_wp_filesystem(); //<-Needed!
require_once 'class-qahm-time.php';
require_once 'class-qahm-log.php';
require_once 'class-qahm-file-base.php'; 

$qahm_file   = new QAHM_File_Base();

$tracking_id = $_GET['tracking_id'];
//$file_name   = './js/'.$tracking_id.'/qtag.js';

// PHPの定数や変数をJavaScriptに渡す
$debug_mode = false;
if ( QAHM_DEBUG >= QAHM_DEBUG_LEVEL['debug'] ) {
	$debug_mode = true;
}
$debug_mode = json_encode($debug_mode);

$send_interval = QAHM_CONFIG_BEHAVIORAL_SEND_INTERVAL;

// QA Advisorの場合は直接qtag.jsの内容を返す
if (QAHM_TYPE === QAHM_TYPE_WP) {
    $qahm_file = new QAHM_File_Base();
    $qtag_js_path = $qahm_file->create_qtag($tracking_id, false);
    
    if ($qtag_js_path && file_exists($qtag_js_path)) {
        echo file_get_contents($qtag_js_path);
    }
} else {
    // JavaScriptコードを動的に生成
    $js_code = <<<JS
var qahmz  = qahmz || {};
qahmz.debug = {$debug_mode};
qahmz.tracking_id = "{$tracking_id}";
qahmz.send_interval = {$send_interval};

JS;

    echo $js_code;
    echo file_get_contents($qahm_file->create_qtag($tracking_id, false));
}

exit;

?>