<?php
// Stands in for GIFOCUS's /gifocus/mg03/mg03d01/create_csv.
// By default: Returns pure genuine CSV with Content-Disposition.
// When simulate_icap=1: Dynamically reads the real Menlo template from
// /home/vagrant/git/menlo-icap/templates/file-download-frame.html (NO hardcoding).

$now = microtime(true);
$usec = sprintf("%06d", ($now - floor($now)) * 1000000);
$table = isset($_POST['main_form-combo_user_table']) ? $_POST['main_form-combo_user_table'] : 'u_com01_00100';
$filename = "IT-116_" . date("YmdH", (int)$now) . "_" . date("i", (int)$now) . "_" . date("s", (int)$now) . $usec . ".csv";

// Check if Menlo ICAP interception is requested
$simulate_icap = isset($_REQUEST['simulate_icap']) && $_REQUEST['simulate_icap'] == '1';

if ($simulate_icap) {
    // -------------------------------------------------------------
    // DYNAMIC MENLO TEMPLATE LOADER (Zero hardcoded HTML strings)
    // Reads directly from Menlo ICAP git repository or package
    // -------------------------------------------------------------
    $templatePath = '/home/vagrant/git/menlo-icap/templates/file-download-frame.html';
    if (!file_exists($templatePath)) {
        $templatePath = '/usr/local/menlo-icap/app/templates/file-download-frame.html';
    }

    $html = file_get_contents($templatePath);
    if ($html === false) {
        http_response_code(500);
        echo "Error: Could not read template from " . htmlspecialchars($templatePath);
        exit;
    }

    // Dynamic values matching Tornado context in file_icap_filter.py
    $iframeUrl = "gifocus_dl_status_mock.php?filename=" . urlencode($filename);
    $clusterHost = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '10.51.9.170';
    $cssAsset = '<link href="https://' . $clusterHost . '/safeview-static/css/file-download.css" rel="stylesheet" type="text/css">';
    $jsAsset  = '<script src="https://' . $clusterHost . '/safeview-static/scripts/file-download.js" type="text/javascript"></script>';

    // Replace Tornado template variables
    $replacements = [
        '{{ iframe_origin }}' => '',
        '{{ docview_modal }}' => 'true',
        '{{ file_name }}' => $filename,
        '{{ iframe_url }}' => $iframeUrl,
        "{{ _('ID_DL_PAGE_TITLE') }}" => 'ファイルのダウンロード',
        "{{ _('ID_DL_PAGE_CONTACTING') }}" => 'サーバーに接続しています...',
        "{{ _('ID_DL_PAGE_TRANSFER') }}" => 'ダウンロードしています...',
        "{{ _('ID_DL_BLOCKED_ERROR_1') }}" => 'エラーが発生しました',
        "{{ _('ID_DL_BLOCKED_ERROR_2') }}" => 'ファイルのダウンロード中にエラーが発生しました。',
        "{{ _('ID_DL_GENERAL_NAME') }}" => 'ファイル名:',
        "{{ _('ID_DL_BLOCKED_RETRY_TIME') }}" => '後でもう一度やり直してください。',
        "{{ _('ID_DL_PAGE_REQUIRES_IFRAMES') }}" => 'この機能を使用するには、インラインフレームをサポートするブラウザが必要です。',
    ];
    $html = str_replace(array_keys($replacements), array_values($replacements), $html);

    // Handle Tornado {% raw include_assets(...) %}
    $html = preg_replace('/\{%\s*raw\s+include_assets\([^)]*\)\s*%\}/s', $cssAsset . "\n" . $jsAsset, $html);

    // Handle Tornado {% if is_newtab_required %}...{% else %}...{% end %}
    $html = preg_replace('/\{%\s*if\s+is_newtab_required\s*%\}.*?\{%\s*else\s*%\}(.*?)\{%\s*end\s*%\}/s', '$1', $html);

    // Strip any remaining Tornado comment tags if any
    $html = preg_replace('/\{#.*?#\}/s', '', $html);

    // Send headers matching menlo-icap (NO Content-Disposition!)
    header("HTTP/1.1 200 OK");
    header("Content-Type: text/html; charset=UTF-8");
    header("Cache-Control: no-cache, no-store, must-revalidate");
    header("Pragma: no-cache");
    header("Expires: 0");

    echo $html;
    exit;
}

// -------------------------------------------------------------
// NORMAL FLOW: Returns real CSV with Content-Disposition
// -------------------------------------------------------------
$body = "\xEF\xBB\xBF"; // UTF-8 BOM
$body .= "ID,Name,Address,Latitude,Longitude,UpdatedAt\n";
for ($i = 1; $i <= 8; $i++) {
   $body .= sprintf("%s-%04d,Hub%d,Tokyo Minato-ku %d-chome,35.%04d,139.%04d,2026/05/07 16:45:%02d\n",
                    $table, $i, $i, $i, 6500 + $i, 7400 + $i, $i);
}

header("HTTP/1.1 200 OK");
header("Content-Type: text/csv; charset=UTF-8");
header("Content-Disposition: attachment; filename=\"" . $filename . "\"");
header("Content-Length: " . strlen($body));
header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Expires: 0");

echo $body;
exit;
