<?php
$html = file_get_contents('site/tools/merchant-feed-generator.html');

$html = str_replace('Google Merchant feed generator', 'Facebook product feed generator', $html);
$html = str_replace('Free Google Merchant Feed Generator', 'Free Facebook Product Feed Generator', $html);
$html = str_replace('merchant-feed-generator', 'facebook-product-feed-generator', $html);
$html = str_replace('Google Merchant Center-ready XML feed', 'Facebook/Instagram Commerce Manager-ready CSV feed', $html);
$html = str_replace('Google Merchant Center', 'Facebook Catalog', $html);
$html = str_replace('Merchant feed XML', 'Facebook feed CSV', $html);
$html = str_replace('merchant-feed.xml', 'facebook-feed.csv', $html);
$html = str_replace('application/xml', 'text/csv', $html);
$html = str_replace('xml', 'csv', $html);
$html = str_replace('XML', 'CSV', $html);

$csvBuildFeed = <<<'EOD'
  function buildFeed(items){
    var header = 'id,title,description,availability,condition,price,link,image_link,brand';
    var rows = items.map(function(p){
      var v = [p.id, p.title, p.description, p.availability || 'in_stock', p.condition || 'new', p.price, p.link, p.image_link, p.brand];
      return v.map(function(val){
        var str = String(val == null ? "" : val);
        if (/[",\n]/.test(str)) return '"' + str.replace(/"/g, '""') + '"';
        return str;
      }).join(',');
    });
    $('output').textContent = [header].concat(rows).join('\n');
    $('feed-output-section').classList.remove('hidden');
  }
EOD;

$html = preg_replace('/  function buildFeed\(items\)\{.*?  \}/s', $csvBuildFeed, $html);

file_put_contents('site/tools/facebook-product-feed-generator.html', $html);
echo "Done\n";
