<?php
require_once __DIR__ . '/../../functions/security.php';
require_once __DIR__ . '/../../functions/logging.php';

$tenant = enrep_tenant_segment();
if ($tenant !== '' && file_exists('../../../' . $tenant . '/config.php')) {
    require_once('../../../' . $tenant . '/config.php');
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}

if (!isset($GLOBALS['con']) || !($GLOBALS['con'] instanceof mysqli)) {
    enrep_fail(400, 'Database connection not available');
}

enrep_require_user();

$rawFormNumber = enrep_request_string('formNumber', '', 20);
$formNumber = preg_replace('/\D+/', '', $rawFormNumber);

if ($formNumber === '') {
    enrep_fail(400, 'Invalid form number');
}

$fieldNames = json_decode(enrep_request_string('default_text_fields', '[]', 20000), true);
if (!is_array($fieldNames)) {
    $fieldNames = [];
}

$cleanFieldNames = [];
foreach ($fieldNames as $fieldName) {
    $fieldName = (string)$fieldName;
    if (preg_match('/^[A-Za-z0-9_\-]+$/', $fieldName) && !in_array($fieldName, $cleanFieldNames, true)) {
        $cleanFieldNames[] = $fieldName;
    }
}

$reservedFields = ['formNumber', 'default_text_fields', 'tenant'];
if (empty($cleanFieldNames)) {
    foreach ($_REQUEST as $fieldName => $value) {
        if (in_array($fieldName, $reservedFields, true)) {
            continue;
        }

        if (preg_match('/^[A-Za-z0-9_\-]+$/', (string)$fieldName) && !in_array($fieldName, $cleanFieldNames, true)) {
            $cleanFieldNames[] = (string)$fieldName;
        }
    }
}

$data = [];
foreach ($cleanFieldNames as $fieldName) {
    $data[$fieldName] = (string)($_REQUEST[$fieldName] ?? '');
}
$data['formNumber'] = 'F' . $formNumber;

$jsonOptions = JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES;
if (defined('JSON_INVALID_UTF8_SUBSTITUTE')) {
    $jsonOptions |= JSON_INVALID_UTF8_SUBSTITUTE;
}

$json = json_encode($data, $jsonOptions);
if (!is_string($json)) {
    enrep_fail(400, 'Unable to encode default text');
}

$stmt = $GLOBALS['con']->prepare("SELECT `id` FROM `default_text` WHERE `formNumber` = ? LIMIT 1");
if (!$stmt) {
    enrep_fail(500, 'Unable to save default text');
}

$stmt->bind_param('s', $formNumber);
$stmt->execute();
$res = $stmt->get_result();
$stmt->close();
$existing = mysqli_fetch_assoc($res);
$logAction = (is_array($existing) && !empty($existing['id'])) ? 'updated' : 'created';

if (is_array($existing) && !empty($existing['id'])) {
    $id = (int)$existing['id'];
    $stmt = $GLOBALS['con']->prepare("UPDATE `default_text` SET `data` = ? WHERE `id` = ?");
    if (!$stmt) {
        enrep_fail(500, 'Unable to save default text');
    }

    $stmt->bind_param('si', $json, $id);
} else {
    $stmt = $GLOBALS['con']->prepare("INSERT INTO `default_text` (`formNumber`, `data`) VALUES (?, ?)");
    if (!$stmt) {
        enrep_fail(500, 'Unable to save default text');
    }

    $stmt->bind_param('ss', $formNumber, $json);
}

$stmt->execute();
if ($stmt->error) {
    $stmt->close();
    enrep_fail(500, 'Unable to save default text');
}

$stmt->close();
enrep_log('default_text', $logAction, ucfirst($logAction) . ' default text for form F' . $formNumber, [
    'entity_type' => 'default_text',
    'entity_id' => $formNumber,
    'subject' => 'F' . $formNumber,
    'field_count' => count($cleanFieldNames),
]);
echo 'success';
