<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(E_ALL);

if (file_exists('../../../'.$_REQUEST['tenant'].'/config.php')) { require_once('../../../'.$_REQUEST['tenant'].'/config.php'); }
if (file_exists('/config.php')) { require_once('/config.php'); }

header('Content-Type: text/plain');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); echo 'Invalid method'; exit; }
if (!isset($GLOBALS['con']) || !($GLOBALS['con'] instanceof mysqli)) { http_response_code(500); echo 'DB missing'; exit; }

mysqli_begin_transaction($GLOBALS['con']);
try {
    // 1) Clear all previous selections
    if (!mysqli_query($GLOBALS['con'], "DELETE FROM master_formtypes")) {
        throw new Exception(mysqli_error($GLOBALS['con']));
    }

    // 2) Insert current selections (if any)
    if (!empty($_POST['formtypes']) && is_array($_POST['formtypes'])) {
        $stmt = $GLOBALS['con']->prepare("INSERT INTO master_formtypes (formnumber, toggle) VALUES (?, 1)");
        if (!$stmt) { throw new Exception(mysqli_error($GLOBALS['con'])); }

        foreach ($_POST['formtypes'] as $formnumber => $v) {
            if (ctype_digit((string)$formnumber)) {
                $fn = (int)$formnumber;
                $stmt->bind_param('i', $fn);
            } else {
                $fn = (string)$formnumber;
                $stmt->bind_param('s', $fn);
            }
            if (!$stmt->execute()) { throw new Exception($stmt->error); }
        }
        $stmt->close();
    }

    mysqli_commit($GLOBALS['con']);
    echo 's';
} catch (Throwable $e) {
    mysqli_rollback($GLOBALS['con']);
    http_response_code(500);
    echo 'e: '.$e->getMessage();
}
