<?php
/**
 * The Google Apps Script the user pastes into their own sheet.
 *
 * @package Ordsync
 */

defined( 'ABSPATH' ) || exit;

/**
 * Build the script with the store's secret already filled in.
 *
 * Kept deliberately short and boring — the user has to read it and
 * trust it before pasting it into their own Google account.
 *
 * Held as an array of lines rather than a heredoc: WordPress.org's
 * Plugin Check rejects heredoc syntax outright, and concatenating one
 * long string would make the JavaScript unreadable in review.
 *
 * @param string $secret Shared secret.
 * @return string
 */
function ordsync_apps_script( $secret ) {

	$secret = preg_replace( '/[^A-Za-z0-9]/', '', (string) $secret );

	$lines = array(
		'/**',
		' * OrderCarry - Google Sheets receiver',
		' *',
		' * Deploy > New deployment > Web app',
		' *   Execute as:      Me',
		' *   Who has access:  Anyone',
		' * Then copy the /exec URL back into the plugin.',
		' */',
		'',
		'const SECRET     = \'' . $secret . '\';',
		'const SHEET_NAME = \'Orders\';',
		'',
		'/**',
		' * Column order. New columns are appended at the END on purpose: inserting',
		' * one in the middle would shift every existing row\'s data sideways.',
		' */',
		'const HEADERS = [',
		'  \'Date\', \'Order\', \'Status\', \'Customer\', \'Email\', \'Phone\', \'Country\',',
		'  \'Items\', \'Total\', \'Currency\', \'Coupons\', \'Shipping\'',
		'];',
		'',
		'// Leave this empty if you opened this editor from inside your sheet',
		'// (Extensions > Apps Script). Only fill it in if you created the script',
		'// on its own - paste the long ID from your sheet\'s address bar:',
		'// docs.google.com/spreadsheets/d/THIS_PART_HERE/edit',
		'const SHEET_ID = \'\';',
		'',
		'function getSpreadsheet() {',
		'  if (SHEET_ID) {',
		'    return SpreadsheetApp.openById(SHEET_ID);',
		'  }',
		'  const active = SpreadsheetApp.getActiveSpreadsheet();',
		'  if (!active) {',
		'    throw new Error(',
		'      \'This script is not attached to a spreadsheet. Either open it from \' +',
		'      \'your sheet via Extensions > Apps Script, or set SHEET_ID at the top.\'',
		'    );',
		'  }',
		'  return active;',
		'}',
		'',
		'function doPost(e) {',
		'  try {',
		'    const data = JSON.parse(e.postData.contents);',
		'',
		'    // Only your store knows this secret.',
		'    if (data.secret !== SECRET) {',
		'      return reply({ ok: false, error: \'Wrong secret\' });',
		'    }',
		'',
		'    const ss = getSpreadsheet();',
		'    const sheet = ss.getSheetByName(SHEET_NAME) || ss.insertSheet(SHEET_NAME);',
		'',
		'    // First run: write the header row.',
		'    ensureHeaders(sheet);',
		'',
		'    const items = (data.items || []).map(function (i) {',
		'      return i.quantity + \'x \' + i.name;',
		'    }).join(\', \');',
		'',
		'    const c = data.customer || {};',
		'',
		'    sheet.appendRow([',
		'      safe(data.date),',
		'      safe(data.order_number),',
		'      safe(data.status),',
		'      safe(((c.first_name || \'\') + \' \' + (c.last_name || \'\')).trim()),',
		'      safe(c.email),',
		'      safe(c.phone),',
		'      safe(c.country),',
		'      safe(items),',
		'      safe(data.total),',
		'      safe(data.currency),',
		'      safe(data.coupons_text),',
		'      safe(data.shipping_method)',
		'    ]);',
		'',
		'    return reply({ ok: true });',
		'',
		'  } catch (err) {',
		'    return reply({ ok: false, error: String(err) });',
		'  }',
		'}',
		'',
		'/**',
		' * Write the header row, or widen an older one.',
		' *',
		' * Sheets created by an earlier version have fewer columns. Rewriting just',
		' * the header row adds the new titles without touching any existing data,',
		' * because new columns are only ever appended on the right.',
		' */',
		'function ensureHeaders(sheet) {',
		'  if (sheet.getLastRow() === 0) {',
		'    sheet.appendRow(HEADERS);',
		'    sheet.setFrozenRows(1);',
		'    sheet.getRange(1, 1, 1, HEADERS.length).setFontWeight(\'bold\');',
		'    return;',
		'  }',
		'',
		'  if (sheet.getLastColumn() < HEADERS.length) {',
		'    sheet.getRange(1, 1, 1, HEADERS.length).setValues([HEADERS]);',
		'    sheet.getRange(1, 1, 1, HEADERS.length).setFontWeight(\'bold\');',
		'  }',
		'}',
		'',
		'/**',
		' * Google Sheets runs any cell starting with = + - or @ as a formula.',
		' *',
		' * That breaks every international phone number (+49...), and it lets a',
		' * customer put a real formula in their own name or address and have it',
		' * execute inside your spreadsheet. A leading apostrophe forces plain text.',
		' * Genuine numbers are still written as numbers so totals stay sortable.',
		' */',
		'function safe(v) {',
		'  if (v === null || v === undefined) return \'\';',
		'  var s = String(v);',
		'  if (s === \'\') return \'\';',
		'  if (s.trim() !== \'\' && !isNaN(s)) return Number(s);',
		'  if (/^[=+\\-@]/.test(s)) return "\'" + s;',
		'  return s;',
		'}',
		'',
		'function reply(obj) {',
		'  return ContentService',
		'    .createTextOutput(JSON.stringify(obj))',
		'    .setMimeType(ContentService.MimeType.JSON);',
		'}',
	);

	return implode( "\n", $lines );
}
