#!/usr/bin/python3
"""Apply the appliance setup changes to a supported upstream wizard."""
import pathlib
import sys

path = pathlib.Path(sys.argv[1])
source = path.read_text()
changes = [
    ("""    $store_owner = zen_output_string_protected($_POST['store_owner']);""",
     """    $sql = "UPDATE " . TABLE_CONFIGURATION . "
            SET configuration_value = :configValue:
            WHERE configuration_key = 'MODULE_PAYMENT_MONEYORDER_PAYTO'
              AND configuration_value = 'the Store Owner/Website Name'";
    $sql = $db->bindVars($sql, ':configValue:', $_POST['store_owner'], 'string');
    $db->Execute($sql);
    $store_owner = zen_output_string_protected($_POST['store_owner']);"""),
    ("""  $store_address = STORE_NAME_ADDRESS;""",
     """  $store_address = str_replace("\\r\\n", "\\n", STORE_NAME_ADDRESS) === "Store Name\\nAddress\\nCountry\\nPhone" ? '' : STORE_NAME_ADDRESS;"""),
    ("""'id="store_name" class="form-control" autofocus="autofocus"'""",
     """'id="store_name" class="form-control" autofocus="autofocus" required'"""),
    ("""'id="store_owner" class="form-control"'""",
     """'id="store_owner" class="form-control" required'"""),
    ("""'id="store_owner_email" class="form-control"'""",
     """'id="store_owner_email" class="form-control" required'"""),
    ("""  if (isset($_POST['store_address']) && $_POST['store_address'] != '') {""",
     """  if (trim($_POST['store_address'] ?? '') === '') {
    $_POST['store_address'] = $_POST['store_name'];
    $db->Execute("UPDATE " . TABLE_CONFIGURATION . " SET configuration_value = 'False'
                  WHERE configuration_key = 'MODULE_PAYMENT_MONEYORDER_STATUS'");
    $messageStack->add_session('Check and money order payments are disabled. Configure a payment method before accepting orders.', 'caution');
  }
  if (isset($_POST['store_address']) && $_POST['store_address'] != '') {"""),
    ("""<?php echo zen_draw_textarea_field('store_address', 'soft', '50', '5', $store_address, 'id="store_address" class="form-control"'); ?>""",
     """<?php echo zen_draw_textarea_field('store_address', 'soft', '50', '5', $store_address, 'id="store_address" class="form-control"'); ?>
            <p class="help-block">Enter a postal address to accept check and money order payments. If left blank, configure another payment method before accepting orders.</p>"""),
]
for old, new in changes:
    if source.count(old) != 1:
        raise SystemExit("Zen Cart setup wizard no longer matches the expected source")
    source = source.replace(old, new)
path.write_text(source)
