/**
 * Storm Cloud Jumpers — inquiry form handler (Google Apps Script)
 * ------------------------------------------------------------------
 * This sends inquiry-form submissions to the shop's Gmail using the
 * shop's OWN Google account — no third-party form service, no cost.
 *
 * ONE-TIME SETUP (about 5 minutes):
 *  1. Sign in to the Gmail account that should RECEIVE inquiries
 *     (stormcloudjumpers@gmail.com).
 *  2. Go to https://script.google.com  →  New project.
 *  3. Delete the sample code, paste THIS whole file in, and Save.
 *  4. Click "Deploy" → "New deployment".
 *       - Type: Web app
 *       - Description: SCJ inquiry form
 *       - Execute as: Me
 *       - Who has access: Anyone
 *     Click Deploy and authorize when prompted.
 *  5. Copy the Web app URL (ends in /exec).
 *  6. Open scj/script.js and paste that URL into FORM_ENDPOINT.
 *
 * That's it — the website form will then email submissions straight
 * to the inbox. (Until FORM_ENDPOINT is set, the form falls back to
 * opening the visitor's own email app, which also works fine.)
 */

// Where inquiries are delivered:
var TO_ADDRESS = 'stormcloudjumpers@gmail.com';

function doPost(e) {
  try {
    var p = (e && e.parameter) ? e.parameter : {};
    var name    = (p.name    || 'Someone').toString().slice(0, 200);
    var email   = (p.email   || '(no email)').toString().slice(0, 200);
    var spider  = (p.spider  || '(not specified)').toString().slice(0, 200);
    var message = (p.message || '(no message)').toString().slice(0, 5000);

    var subject = 'Spider Inquiry — ' + spider + ' (' + name + ')';
    var body =
      'New inquiry from the Storm Cloud Jumpers website:\n\n' +
      'Name:              ' + name + '\n' +
      'Email:             ' + email + '\n' +
      'Spider of interest: ' + spider + '\n\n' +
      'Message:\n' + message + '\n\n' +
      '— Reply directly to this email to reach the buyer.';

    GmailApp.sendEmail(TO_ADDRESS, subject, body, { replyTo: email, name: 'SCJ Website' });

    return ContentService
      .createTextOutput(JSON.stringify({ ok: true }))
      .setMimeType(ContentService.MimeType.JSON);
  } catch (err) {
    return ContentService
      .createTextOutput(JSON.stringify({ ok: false, error: String(err) }))
      .setMimeType(ContentService.MimeType.JSON);
  }
}

// Simple health check when the URL is opened in a browser.
function doGet() {
  return ContentService.createTextOutput('Storm Cloud Jumpers form handler is running.');
}
