<?php
$origPath = 'c:/Users/HP/Downloads/climate-system/temp_extract/climate-system/index.php';
$destPath = 'c:/Users/HP/Downloads/climate-system/climate-system/index.php';

if (!file_exists($origPath)) {
    die("Original index.php not found at $origPath\n");
}

$content = file_get_contents($origPath);

// Define diff blocks (Target => Replacement)
$replacements = [
    // 1. Baseline anomaly check
    'if (stripos($variable_sanitized, \'precip\') !== false || stripos($variable_sanitized, \'hujan\') !== false) {
        $base = 2300; // default baseline (curah hujan)' 
    => 
    'if (stripos($variable_sanitized, \'anomaly\') !== false || stripos($variable_sanitized, \'anomali\') !== false) {
        $base = 0.5; // default baseline (anomali suhu)
    } else if (stripos($variable_sanitized, \'precip\') !== false || stripos($variable_sanitized, \'hujan\') !== false) {
        $base = 2300; // default baseline (curah hujan)',

    // 2. cols_to_add DB schema migration columns
    '\'graph_ssp3_slope\' => \'REAL DEFAULT NULL\',
        \'graph_ssp5_slope\' => \'REAL DEFAULT NULL\',
        \'csv_data\' => \'TEXT DEFAULT NULL\',
        \'image_climate_map_url_2\' => "TEXT DEFAULT \'\'"
    ];'
    =>
    '\'graph_ssp3_slope\' => \'REAL DEFAULT NULL\',
        \'graph_ssp5_slope\' => \'REAL DEFAULT NULL\',
        \'csv_data\' => \'TEXT DEFAULT NULL\',
        \'image_climate_map_url_2\' => "TEXT DEFAULT \'\'",
        \'image_stripe_ssp126_url\' => "TEXT DEFAULT \'\'",
        \'image_stripe_ssp245_url\' => "TEXT DEFAULT \'\'",
        \'image_stripe_ssp370_url\' => "TEXT DEFAULT \'\'",
        \'image_stripe_ssp585_url\' => "TEXT DEFAULT \'\'"
    ];',

    // 3. CREATE TABLE future_climate columns
    'image_climate_map_url_2 TEXT DEFAULT \'\',
                image_time_series_url TEXT DEFAULT \'\',
                image_climate_stripe_url TEXT DEFAULT \'\',
                csv_data TEXT DEFAULT NULL,'
    =>
    'image_climate_map_url_2 TEXT DEFAULT \'\',
                image_time_series_url TEXT DEFAULT \'\',
                image_climate_stripe_url TEXT DEFAULT \'\',
                image_stripe_ssp126_url TEXT DEFAULT \'\',
                image_stripe_ssp245_url TEXT DEFAULT \'\',
                image_stripe_ssp370_url TEXT DEFAULT \'\',
                image_stripe_ssp585_url TEXT DEFAULT \'\',
                csv_data TEXT DEFAULT NULL,',

    // 4. get_future_csv folder mapping
    '// Sanitasi input untuk mencegah Directory Traversal
            $location_sanitized = str_replace(array(\'..\', \'/\', \'\\\\\'), \'\', $location);
            $variable_sanitized = str_replace(array(\'..\', \'/\', \'\\\\\'), \'\', $variable);
 
            // Auto-generate sample CSV jika belum ada demi pengalaman tanpa hambatan
            ensure_sample_csv_exists_ipcc($location_sanitized, $variable_sanitized);'
    =>
    '// Tentukan folder variabel (misal: memetakan Suhu Udara Minimum ke Temperature Anomaly)
            $variable_folder = $variable;
            if ($variable === \'Suhu Udara Minimum\' || stripos($variable, \'minimum\') !== false) {
                $variable_folder = \'Temperature Anomaly\';
            }

            // Sanitasi input untuk mencegah Directory Traversal
            $location_sanitized = str_replace(array(\'..\', \'/\', \'\\\\\'), \'\', $location);
            $variable_folder_sanitized = str_replace(array(\'..\', \'/\', \'\\\\\'), \'\', $variable_folder);
 
            // Auto-generate sample CSV jika belum ada demi pengalaman tanpa hambatan
            ensure_sample_csv_exists_ipcc($location_sanitized, $variable_folder_sanitized);',

    // 5. get_future_csv dir lookup folder
    '$stat_lower = strtolower($statistic);
            $main_filename = isset($stat_map[$stat_lower]) ? $stat_map[$stat_lower] : \'areal_averaged_ensmean.csv\';
 
            $variable_folder = $variable_sanitized;
            if ($variable_sanitized === \'Suhu Udara Minimum\' || stripos($variable_sanitized, \'minimum\') !== false) {
                $variable_folder = \'Temperature Anomaly\';
            }
            $dir = __DIR__ . "/data/{$location_sanitized}/{$variable_folder}";'
    =>
    '$stat_lower = strtolower($statistic);
            $main_filename = isset($stat_map[$stat_lower]) ? $stat_map[$stat_lower] : \'areal_averaged_ensmean.csv\';
 
            $dir = __DIR__ . "/data/{$location_sanitized}/{$variable_folder_sanitized}";',

    // 6. get_future return array columns mapping
    '\'imageClimateMap2\' => $periodData ? $periodData[\'image_climate_map_url_2\'] : \'\',
                        \'imageTimeSeries\' => ($periodData && !empty($periodData[\'image_time_series_url\'])) ? $periodData[\'image_time_series_url\'] : ($globalData ? $globalData[\'image_time_series_url\'] : \'\'),
                        \'imageClimateStripe\' => ($periodData && !empty($periodData[\'image_climate_stripe_url\'])) ? $periodData[\'image_climate_stripe_url\'] : ($globalData ? $globalData[\'image_climate_stripe_url\'] : \'\'),
                        \'graphBaseValue\' => ($periodData && $periodData[\'graph_base_value\'] !== null) ? $periodData[\'graph_base_value\'] : ($globalData ? $globalData[\'graph_base_value\'] : null),'
    =>
    '\'imageClimateMap2\' => $periodData ? $periodData[\'image_climate_map_url_2\'] : \'\',
                        \'imageTimeSeries\' => ($periodData && !empty($periodData[\'image_time_series_url\'])) ? $periodData[\'image_time_series_url\'] : ($globalData ? $globalData[\'image_time_series_url\'] : \'\'),
                        \'imageClimateStripe\' => ($periodData && !empty($periodData[\'image_climate_stripe_url\'])) ? $periodData[\'image_climate_stripe_url\'] : ($globalData ? $globalData[\'image_climate_stripe_url\'] : \'\'),
                        \'imageStripeSSP126\' => ($periodData && !empty($periodData[\'image_stripe_ssp126_url\'])) ? $periodData[\'image_stripe_ssp126_url\'] : ($globalData ? $globalData[\'image_stripe_ssp126_url\'] : \'\'),
                        \'imageStripeSSP245\' => ($periodData && !empty($periodData[\'image_stripe_ssp245_url\'])) ? $periodData[\'image_stripe_ssp245_url\'] : ($globalData ? $globalData[\'image_stripe_ssp245_url\'] : \'\'),
                        \'imageStripeSSP370\' => ($periodData && !empty($periodData[\'image_stripe_ssp370_url\'])) ? $periodData[\'image_stripe_ssp370_url\'] : ($globalData ? $globalData[\'image_stripe_ssp370_url\'] : \'\'),
                        \'imageStripeSSP585\' => ($periodData && !empty($periodData[\'image_stripe_ssp585_url\'])) ? $periodData[\'image_stripe_ssp585_url\'] : ($globalData ? $globalData[\'image_stripe_ssp585_url\'] : \'\'),
                        \'graphBaseValue\' => ($periodData && $periodData[\'graph_base_value\'] !== null) ? $periodData[\'graph_base_value\'] : ($globalData ? $globalData[\'graph_base_value\'] : null),',

    // 7. save_future updates block updates list
    'if (isset($input[\'imageClimateMap\'])) { $updates[] = "image_climate_map_url = :image_map"; $params[\':image_map\'] = trim($input[\'imageClimateMap\']); }
                if (isset($input[\'imageClimateMap2\'])) { $updates[] = "image_climate_map_url_2 = :image_map_2"; $params[\':image_map_2\'] = trim($input[\'imageClimateMap2\']); }
                if (isset($input[\'imageClimateStripe\'])) { $updates[] = "image_climate_stripe_url = :image_stripe"; $params[\':image_stripe\'] = trim($input[\'imageClimateStripe\']); }
                if (isset($input[\'imageTimeSeries\'])) { $updates[] = "image_time_series_url = :image_ts"; $params[\':image_ts\'] = trim($input[\'imageTimeSeries\']); }'
    =>
    'if (isset($input[\'imageClimateMap\'])) { $updates[] = "image_climate_map_url = :image_map"; $params[\':image_map\'] = trim($input[\'imageClimateMap\']); }
                if (isset($input[\'imageClimateMap2\'])) { $updates[] = "image_climate_map_url_2 = :image_map_2"; $params[\':image_map_2\'] = trim($input[\'imageClimateMap2\']); }
                if (isset($input[\'imageClimateStripe\'])) { $updates[] = "image_climate_stripe_url = :image_stripe"; $params[\':image_stripe\'] = trim($input[\'imageClimateStripe\']); }
                if (isset($input[\'imageStripeSSP126\'])) { $updates[] = "image_stripe_ssp126_url = :stripe_ssp126"; $params[\':stripe_ssp126\'] = trim($input[\'imageStripeSSP126\']); }
                if (isset($input[\'imageStripeSSP245\'])) { $updates[] = "image_stripe_ssp245_url = :stripe_ssp245"; $params[\':stripe_ssp245\'] = trim($input[\'imageStripeSSP245\']); }
                if (isset($input[\'imageStripeSSP370\'])) { $updates[] = "image_stripe_ssp370_url = :stripe_ssp370"; $params[\':stripe_ssp370\'] = trim($input[\'imageStripeSSP370\']); }
                if (isset($input[\'imageStripeSSP585\'])) { $updates[] = "image_stripe_ssp585_url = :stripe_ssp585"; $params[\':stripe_ssp585\'] = trim($input[\'imageStripeSSP585\']); }
                if (isset($input[\'imageTimeSeries\'])) { $updates[] = "image_time_series_url = :image_ts"; $params[\':image_ts\'] = trim($input[\'imageTimeSeries\']); }',

    // 8. save_future insertions variables list
    '$imgMap = isset($input[\'imageClimateMap\']) ? trim($input[\'imageClimateMap\']) : \'\';
                $imgMap2 = isset($input[\'imageClimateMap2\']) ? trim($input[\'imageClimateMap2\']) : \'\';
                $imgStripe = isset($input[\'imageClimateStripe\']) ? trim($input[\'imageClimateStripe\']) : \'\';
                $imgTS = isset($input[\'imageTimeSeries\']) ? trim($input[\'imageTimeSeries\']) : \'\';'
    =>
    '$imgMap = isset($input[\'imageClimateMap\']) ? trim($input[\'imageClimateMap\']) : \'\';
                $imgMap2 = isset($input[\'imageClimateMap2\']) ? trim($input[\'imageClimateMap2\']) : \'\';
                $imgStripe = isset($input[\'imageClimateStripe\']) ? trim($input[\'imageClimateStripe\']) : \'\';
                $imgStripeSSP126 = isset($input[\'imageStripeSSP126\']) ? trim($input[\'imageStripeSSP126\']) : \'\';
                $imgStripeSSP245 = isset($input[\'imageStripeSSP245\']) ? trim($input[\'imageStripeSSP245\']) : \'\';
                $imgStripeSSP370 = isset($input[\'imageStripeSSP370\']) ? trim($input[\'imageStripeSSP370\']) : \'\';
                $imgStripeSSP585 = isset($input[\'imageStripeSSP585\']) ? trim($input[\'imageStripeSSP585\']) : \'\';
                $imgTS = isset($input[\'imageTimeSeries\']) ? trim($input[\'imageTimeSeries\']) : \'\';',

    // 9. save_future INSERT INTO list
    'INSERT INTO future_climate (
                        location_id, variable_id, period_id, description, 
                        image_climate_map_url, image_climate_map_url_2, image_time_series_url, image_climate_stripe_url,
                        graph_base_value, graph_uncertainty, graph_ssp1_slope, graph_ssp2_slope, graph_ssp3_slope, graph_ssp5_slope,
                        csv_data,
                        updated_at'
    =>
    'INSERT INTO future_climate (
                        location_id, variable_id, period_id, description, 
                        image_climate_map_url, image_climate_map_url_2, image_time_series_url, image_climate_stripe_url,
                        image_stripe_ssp126_url, image_stripe_ssp245_url, image_stripe_ssp370_url, image_stripe_ssp585_url,
                        graph_base_value, graph_uncertainty, graph_ssp1_slope, graph_ssp2_slope, graph_ssp3_slope, graph_ssp5_slope,
                        csv_data,
                        updated_at',

    // 10. save_future VALUES list
    'VALUES (
                    :location_id, :variable_id, :period_id, :description, 
                    :image_climate_map, :image_climate_map_2, :image_time_series, :image_climate_stripe,
                    :graph_base_value, :graph_uncertainty, :graph_ssp1_slope, :graph_ssp2_slope, :graph_ssp3_slope, :graph_ssp5_slope,
                    :csv_data,
                    CURRENT_TIMESTAMP
                )'
    =>
    'VALUES (
                    :location_id, :variable_id, :period_id, :description, 
                    :image_climate_map, :image_climate_map_2, :image_time_series, :image_climate_stripe,
                    :stripe_ssp126, :stripe_ssp245, :stripe_ssp370, :stripe_ssp585,
                    :graph_base_value, :graph_uncertainty, :graph_ssp1_slope, :graph_ssp2_slope, :graph_ssp3_slope, :graph_ssp5_slope,
                    :csv_data,
                    CURRENT_TIMESTAMP
                )',

    // 11. save_future VALUES binding array keys
    '":img_map_2" => $imgMap2,
                ":img_ts" => $imgTS,
                ":img_stripe" => $imgStripe,
                ":graph_base_value" => $graphBaseValue,'
    =>
    '":img_map_2" => $imgMap2,
                ":img_ts" => $imgTS,
                ":img_stripe" => $imgStripe,
                ":stripe_ssp126" => $imgStripeSSP126,
                ":stripe_ssp245" => $imgStripeSSP245,
                ":stripe_ssp370" => $imgStripeSSP370,
                ":stripe_ssp585" => $imgStripeSSP585,
                ":graph_base_value" => $graphBaseValue,',

    // 12. Form 1B settings markup insertion
    '      <button class="save-btn" onclick="saveFutureMapSettings()">Simpan Gambar & Deskripsi</button>
    </div>

    <!-- Form 2: Pengaturan Grafik Interaktif Proyeksi'
    =>
    '      <button class="save-btn" onclick="saveFutureMapSettings()">Simpan Gambar & Deskripsi</button>
    </div>

    <!-- Form 1B: Pengaturan Climate Stripe Proyeksi (Per Skenario) -->
    <div class="form-section" style="margin-top:30px;">
      <h3 style="margin-bottom:20px;">Tambah / Edit Climate Stripe Proyeksi (Per Skenario)</h3>
      <div class="form-grid">
        <div class="form-box">
          <label>Lokasi</label>
          <select id="futureSetStripeLocation" onchange="loadFutureStripeSettingsData()">
            <!-- Diisi secara dinamis -->
          </select>
        </div>
        <div class="form-box">
          <label>Variable</label>
          <select id="futureSetStripeVariable" onchange="loadFutureStripeSettingsData()">
            <!-- Diisi secara dinamis -->
          </select>
        </div>
        <div class="form-box">
          <label>Periode</label>
          <select id="futureSetStripePeriod" onchange="loadFutureStripeSettingsData()">
            <!-- Diisi secara dinamis -->
          </select>
        </div>
        <div class="form-box" style="grid-column: 1 / -1; border-top: 1px dashed #cbd5e1; padding-top: 15px; margin-top: 15px;">
          <h4 style="margin-bottom: 12px; color: #2563eb;">Masukkan URL Gambar Climate Stripe untuk Masing-Masing Skenario</h4>
          <div class="form-grid" style="grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));">
            <div class="form-box">
              <label>SSP1-2.6</label>
              <input id="futureSetStripeSSP126" placeholder="Masukkan URL gambar SSP1-2.6" type="text" />
            </div>
            <div class="form-box">
              <label>SSP2-4.5</label>
              <input id="futureSetStripeSSP245" placeholder="Masukkan URL gambar SSP2-4.5" type="text" />
            </div>
            <div class="form-box">
              <label>SSP3-7.0</label>
              <input id="futureSetStripeSSP370" placeholder="Masukkan URL gambar SSP3-7.0" type="text" />
            </div>
            <div class="form-box">
              <label>SSP5-8.5</label>
              <input id="futureSetStripeSSP585" placeholder="Masukkan URL gambar SSP5-8.5" type="text" />
            </div>
          </div>
        </div>
      </div>
      <button class="save-btn" onclick="saveFutureStripeSettings()">Simpan Climate Stripe</button>
    </div>

    <!-- Form 2: Pengaturan Grafik Interaktif Proyeksi',

    // 13. JS populate stripe location dropdown
    '          populateDropdown(\'historicalSetLocation\', data.locations);
          populateDropdown(\'futureSetLocationMap\', data.locations);
          populateDropdown(\'futureSetLocationGraph\', data.locations);

          // Variables'
    =>
    '          populateDropdown(\'historicalSetLocation\', data.locations);
          populateDropdown(\'futureSetLocationMap\', data.locations);
          populateDropdown(\'futureSetLocationGraph\', data.locations);
          populateDropdown(\'futureSetStripeLocation\', data.locations);

          // Variables',

    // 14. JS populate stripe variable dropdown
    '          populateDropdown(\'futureSetVariableMap\', data.variables);
          populateDropdown(\'futureSetVariableGraph\', data.variables);
          populateDropdown(\'futureStripeVariable\', data.variables);

          // Periods'
    =>
    '          populateDropdown(\'futureSetVariableMap\', data.variables);
          populateDropdown(\'futureSetVariableGraph\', data.variables);
          populateDropdown(\'futureStripeVariable\', data.variables);
          populateDropdown(\'futureSetStripeVariable\', data.variables);

          // Periods',

    // 15. JS populate stripe period dropdown
    '          populateDropdown(\'futurePeriodMap\', data.periods);
        }
      } catch (err) {'
    =>
    '          populateDropdown(\'futurePeriodMap\', data.periods);
          populateDropdown(\'futureSetStripePeriod\', data.periods);
        }
      } catch (err) {',

    // 16. Chart drawing isTempAnomaly min check
    '        if (vNorm.includes(\'anomaly\') || vNorm.includes(\'anomali\') || vNorm.includes(\'minimum\') || vNorm.includes(\'min\')) {
          unit = \'°C\';
          yLabel = \'Temperature Anomaly\';
        } else {'
    =>
    '        if (vNorm.includes(\'anomaly\') || vNorm.includes(\'anomali\')) {
          unit = \'°C\';
          yLabel = \'Temperature Anomaly\';
        } else {',

    // 17. Chart isTempAnomaly variable check
    '      if (vLower.includes(\'anomaly\') || vLower.includes(\'anomali\') || vLower.includes(\'minimum\') || vLower.includes(\'min\')) {
        isTempAnomaly = true;
      } else if (vLower.includes(\'suhu\') || vLower.includes(\'temp\') || vLower.includes(\'temperature\')) {'
    =>
    '      if (vLower.includes(\'anomaly\') || vLower.includes(\'anomali\')) {
        isTempAnomaly = true;
      } else if (vLower.includes(\'suhu\') || vLower.includes(\'temp\') || vLower.includes(\'temperature\')) {',

    // 18. Chart isTempAnomaly threshold fallback
    '        if (maxVal < 12) {
          isTempAnomaly = true;
        }'
    =>
    '        if (maxVal < 12) {
          isTempAnomaly = true;
          yLabel = \'Temperature Anomaly\';
        }',

    // 19. Chart options accessibility config disable
    '        title: {
          text: null
        },
        credits: {'
    =>
    '        title: {
          text: null
        },
        accessibility: {
          enabled: false
        },
        credits: {',

    // 20. Main page filter load scenario specific stripe mapping
    '          // Future Climate Stripe
          document.getElementById(\'futureImageClimateStripe\').src = savedData.imageClimateStripe ? normalizeImageUrl(savedData.imageClimateStripe) : PLACEHOLDER_IMG;
          document.getElementById(\'futureCategoryTitleStripe\').innerText = "Future Climate Stripe";
          document.getElementById(\'futureVariableTextStripe\').innerText = "Variabel: " + variable;
          document.getElementById(\'futurePeriodTextStripe\').innerText = "Periode: " + period;
        } else {
          document.getElementById(\'futureDescription\').innerText = \'Data climate belum tersedia di database untuk filter ini, namun visualisasi telah diperbarui.\';
          // Reset gambar ke placeholder
          document.getElementById(\'futureImageClimateMap\').src = PLACEHOLDER_IMG;
          document.getElementById(\'futureImageClimateMap2\').src = PLACEHOLDER_IMG;
          switchClimateMap(1); // Reset slider to show Map 1 first
          document.getElementById(\'futureImageClimateStripe\').src = PLACEHOLDER_IMG;
          
          document.getElementById(\'futureVariableText\').innerText = "Variabel: " + variable;
          document.getElementById(\'futurePeriodText\').innerText = "Periode: " + period;
          document.getElementById(\'futureVariableTextStripe\').innerText = "Variabel: " + variable;
          document.getElementById(\'futurePeriodTextStripe\').innerText = "Periode: " + period;'
    =>
    '          // Future Climate Stripe
          const scenario = document.getElementById(\'futureStripeScenario\').value;
          let stripeUrl = PLACEHOLDER_IMG;
          let stripeLabel = "Skenario: " + scenario;
          if (scenario === \'SSP1-2.6\' && savedData.imageStripeSSP126) stripeUrl = normalizeImageUrl(savedData.imageStripeSSP126);
          else if (scenario === \'SSP2-4.5\' && savedData.imageStripeSSP245) stripeUrl = normalizeImageUrl(savedData.imageStripeSSP245);
          else if (scenario === \'SSP3-7.0\' && savedData.imageStripeSSP370) stripeUrl = normalizeImageUrl(savedData.imageStripeSSP370);
          else if (scenario === \'SSP5-8.5\' && savedData.imageStripeSSP585) stripeUrl = normalizeImageUrl(savedData.imageStripeSSP585);
          else if (savedData.imageClimateStripe) stripeUrl = normalizeImageUrl(savedData.imageClimateStripe);
          else stripeLabel = "Skenario: " + scenario + " (Data tidak ditemukan)";

          document.getElementById(\'futureImageClimateStripe\').src = stripeUrl;
          document.getElementById(\'futureCategoryTitleStripe\').innerText = "Future Climate Stripe";
          document.getElementById(\'futureVariableTextStripe\').innerText = "Variabel: " + variable;
          document.getElementById(\'futurePeriodTextStripe\').innerText = stripeLabel;
        } else {
          document.getElementById(\'futureDescription\').innerText = \'Data climate belum tersedia di database untuk filter ini, namun visualisasi telah diperbarui.\';
          // Reset gambar ke placeholder
          document.getElementById(\'futureImageClimateMap\').src = PLACEHOLDER_IMG;
          document.getElementById(\'futureImageClimateMap2\').src = PLACEHOLDER_IMG;
          switchClimateMap(1); // Reset slider to show Map 1 first
          document.getElementById(\'futureImageClimateStripe\').src = PLACEHOLDER_IMG;
          
          const scenario = document.getElementById(\'futureStripeScenario\').value;
          document.getElementById(\'futureVariableText\').innerText = "Variabel: " + variable;
          document.getElementById(\'futurePeriodText\').innerText = "Periode: " + period;
          document.getElementById(\'futureVariableTextStripe\').innerText = "Variabel: " + variable;
          document.getElementById(\'futurePeriodTextStripe\').innerText = "Skenario: " + scenario + " (Data tidak ditemukan)";',

    // 21. Main page apply stripe filters load method
    '      const lokasi = document.getElementById(\'futureLocationMap\').value || \'Indonesia\';
      const variable = document.getElementById(\'futureStripeVariable\').value;
      const scenario = document.getElementById(\'futureStripeScenario\').value;

      if (!variable || !scenario) {
        alert(\'Silakan pilih variabel dan skenario terlebih dahulu.\');
        return;
      }

      // Map scenario to period:
      // SSP1-2.6 -> 2021-2050
      // SSP2-4.5 -> 2031-2060
      // SSP3-7.0 -> 2041-2070
      // SSP5-8.5 -> 2051-2080
      let period = \'2021-2050\';
      if (scenario === \'SSP2-4.5\') period = \'2031-2060\';
      else if (scenario === \'SSP3-7.0\') period = \'2041-2070\';
      else if (scenario === \'SSP5-8.5\') period = \'2051-2080\';

      try {
        const res = await fetch(`?action=get_future&location=${encodeURIComponent(lokasi)}&variable=${encodeURIComponent(variable)}&period=${encodeURIComponent(period)}`);
        const result = await res.json();

        if (result.success && result.data && result.data.imageClimateStripe && result.data.imageClimateStripe !== \'\') {
          const savedData = result.data;
          document.getElementById(\'futureImageClimateStripe\').src = normalizeImageUrl(savedData.imageClimateStripe);
          document.getElementById(\'futureVariableTextStripe\').innerText = "Variabel: " + variable;
          document.getElementById(\'futurePeriodTextStripe\').innerText = "Skenario: " + scenario;
        } else {
          document.getElementById(\'futureImageClimateStripe\').src = PLACEHOLDER_IMG;
          document.getElementById(\'futureVariableTextStripe\').innerText = "Variabel: " + variable;
          document.getElementById(\'futurePeriodTextStripe\').innerText = "Skenario: " + scenario + " (Data tidak ditemukan)";
        }
      } catch (err) {'
    =>
    '      const lokasi = document.getElementById(\'futureLocationMap\').value || \'Indonesia\';
      const variable = document.getElementById(\'futureStripeVariable\').value;
      const scenario = document.getElementById(\'futureStripeScenario\').value;
      const period = document.getElementById(\'futurePeriodMap\').value || \'2021-2050\';

      if (!variable || !scenario) {
        alert(\'Silakan pilih variabel dan skenario terlebih dahulu.\');
        return;
      }

      try {
        const res = await fetch(`?action=get_future&location=${encodeURIComponent(lokasi)}&variable=${encodeURIComponent(variable)}&period=${encodeURIComponent(period)}`);
        const result = await res.json();

        let stripeUrl = PLACEHOLDER_IMG;
        let found = false;
        if (result.success && result.data) {
          const savedData = result.data;
          if (scenario === \'SSP1-2.6\' && savedData.imageStripeSSP126) { stripeUrl = normalizeImageUrl(savedData.imageStripeSSP126); found = true; }
          else if (scenario === \'SSP2-4.5\' && savedData.imageStripeSSP245) { stripeUrl = normalizeImageUrl(savedData.imageStripeSSP245); found = true; }
          else if (scenario === \'SSP3-7.0\' && savedData.imageStripeSSP370) { stripeUrl = normalizeImageUrl(savedData.imageStripeSSP370); found = true; }
          else if (scenario === \'SSP5-8.5\' && savedData.imageStripeSSP585) { stripeUrl = normalizeImageUrl(savedData.imageStripeSSP585); found = true; }
          
          if (!found && savedData.imageClimateStripe) {
            stripeUrl = normalizeImageUrl(savedData.imageClimateStripe);
            found = true;
          }
        }

        document.getElementById(\'futureImageClimateStripe\').src = stripeUrl;
        document.getElementById(\'futureVariableTextStripe\').innerText = "Variabel: " + variable;
        document.getElementById(\'futurePeriodTextStripe\').innerText = "Skenario: " + scenario + (found ? "" : " (Data tidak ditemukan)");
      } catch (err) {',

    // 22. JS settings load & save stripe settings functions
    '    async function loadFutureGraphSettingsData() {'
    =>
    '    async function loadFutureStripeSettingsData() {
      const lokasiSelect = document.getElementById(\'futureSetStripeLocation\');
      const variableSelect = document.getElementById(\'futureSetStripeVariable\');
      const periodSelect = document.getElementById(\'futureSetStripePeriod\');

      if (!lokasiSelect || !variableSelect || !periodSelect) return;

      const lokasi = lokasiSelect.value.trim();
      const variable = variableSelect.value.trim();
      const period = periodSelect.value.trim();

      if (!lokasi || !variable || !period) return;

      try {
        const res = await fetch(`?action=get_future&location=${encodeURIComponent(lokasi)}&variable=${encodeURIComponent(variable)}&period=${encodeURIComponent(period)}`);
        const result = await res.json();

        if (result.success && result.data) {
          const d = result.data;
          document.getElementById(\'futureSetStripeSSP126\').value = d.imageStripeSSP126 || \'\';
          document.getElementById(\'futureSetStripeSSP245\').value = d.imageStripeSSP245 || \'\';
          document.getElementById(\'futureSetStripeSSP370\').value = d.imageStripeSSP370 || \'\';
          document.getElementById(\'futureSetStripeSSP585\').value = d.imageStripeSSP585 || \'\';
        } else {
          document.getElementById(\'futureSetStripeSSP126\').value = \'\';
          document.getElementById(\'futureSetStripeSSP245\').value = \'\';
          document.getElementById(\'futureSetStripeSSP370\').value = \'\';
          document.getElementById(\'futureSetStripeSSP585\').value = \'\';
        }
      } catch (err) {
        console.error(err);
      }
    }

    async function saveFutureStripeSettings() {
      const lokasi = document.getElementById(\'futureSetStripeLocation\').value.trim();
      const variable = document.getElementById(\'futureSetStripeVariable\').value.trim();
      const period = document.getElementById(\'futureSetStripePeriod\').value.trim();

      const stripeSSP126 = normalizeImageUrl(document.getElementById(\'futureSetStripeSSP126\').value.trim());
      const stripeSSP245 = normalizeImageUrl(document.getElementById(\'futureSetStripeSSP245\').value.trim());
      const stripeSSP370 = normalizeImageUrl(document.getElementById(\'futureSetStripeSSP370\').value.trim());
      const stripeSSP585 = normalizeImageUrl(document.getElementById(\'futureSetStripeSSP585\').value.trim());

      if (!lokasi || !variable || !period) {
        alert(\'Lokasi, Variable, dan Periode wajib diisi!\');
        return;
      }

      const data = {
        location: lokasi,
        variable: variable,
        period: period,
        imageStripeSSP126: stripeSSP126,
        imageStripeSSP245: stripeSSP245,
        imageStripeSSP370: stripeSSP370,
        imageStripeSSP585: stripeSSP585
      };

      try {
        const res = await fetch(\'?action=save_future\', {
          method: \'POST\',
          headers: {
            \'Content-Type\': \'application/json\'
          },
          body: JSON.stringify(data)
        });
        const result = await res.json();

        if (result.success) {
          alert(\'Data Climate Stripe berhasil disimpan ke database SQLite!\');
          await loadFilters();
        } else {
          alert(\'Gagal menyimpan: \' + (result.error || result.message));
        }
      } catch (err) {
        console.error(err);
        alert(\'Gagal mengirim data penyimpanan ke server.\');
      }
    }

    async function loadFutureGraphSettingsData() {',

    // 23. JS settings init stripe call on load
    '      // Load initial settings data (which also triggers updateSettingsChartPreview)
      await loadHistoricalSettingsData();
      await loadFutureMapSettingsData();
      await loadFutureGraphSettingsData();'
    =>
    '      // Load initial settings data (which also triggers updateSettingsChartPreview)
      await loadHistoricalSettingsData();
      await loadFutureMapSettingsData();
      await loadFutureStripeSettingsData();
      await loadFutureGraphSettingsData();',
];

$successCount = 0;
foreach ($replacements as $target => $replacement) {
    // Normalize target line endings
    $target_norm = str_replace("\r\n", "\n", $target);
    $content_norm = str_replace("\r\n", "\n", $content);
    
    $pos = strpos($content_norm, $target_norm);
    if ($pos !== false) {
        // Replace target with replacement in normalized form to avoid mismatch
        $content = str_replace($target_norm, $replacement, $content_norm);
        $successCount++;
    } else {
        echo "WARNING: target block not found:\n" . substr($target, 0, 100) . "...\n\n";
    }
}

echo "Successfully applied $successCount / " . count($replacements) . " edits.\n";

// Write back to index.php
file_put_contents($destPath, $content);
echo "Written restored stripes content to $destPath\n";
