<?php 
header('Content-Type: application/json');

$tenant = trim((string)($_REQUEST['tenant'] ?? ''), "/\\");


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

if (file_exists('/config.php')) {
    require_once('/config.php');
}

function reptypesResponse(string $status, string $message): void
{
    echo json_encode([
        'status' => $status,
        'message' => $message
    ]);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    reptypesResponse('error', 'Invalid request method');
}

if (!isset($GLOBALS['con']) || !($GLOBALS['con'] instanceof mysqli)) {
    http_response_code(500);
    reptypesResponse('error', 'Database connection is not available');
}

$GLOBALS['con']->set_charset('utf8mb4');

$function = (string)($_REQUEST['FUNCTION'] ?? '');

switch ($function) {
    case 'updateReportType':
        $formnumber = (int)($_REQUEST['formnumber'] ?? 0);
        $formtype = trim((string)($_REQUEST['formtype'] ?? ''));
        $description = trim((string)($_REQUEST['description'] ?? ''));
        $regs = trim((string)($_REQUEST['regs'] ?? ''));

        if ($formnumber < 1) {
            reptypesResponse('error', 'A valid form number is required');
        }

        if ($formtype === '') {
            reptypesResponse('error', 'Report Type is required');
        }

        if (strlen($formtype) > 80) {
            reptypesResponse('error', 'Report Type must be 80 characters or fewer');
        }

        if ($description === '') {
            reptypesResponse('error', 'Description is required');
        }

        if (strlen($description) > 50) {
            reptypesResponse('error', 'Description must be 50 characters or fewer');
        }

        $stmt = $GLOBALS['con']->prepare("
            UPDATE `dd_formtypes`
            SET `formtype` = ?, `description` = ?, `regs` = ?
            WHERE `formnumber` = ?
            LIMIT 1
        ");

        if (!$stmt) {
            http_response_code(500);
            reptypesResponse('error', 'Unable to prepare the update');
        }

        $stmt->bind_param('sssi', $formtype, $description, $regs, $formnumber);
        $ok = $stmt->execute();
        $affected = $stmt->affected_rows;
        $stmt->close();

        if (!$ok) {
            http_response_code(500);
            reptypesResponse('error', 'Unable to update the report type');
        }

        if ($affected < 1) {
            reptypesResponse('success', 'No changes were needed for this report type');
        }

        reptypesResponse('success', 'Report type updated');

    default:
        http_response_code(400);
        reptypesResponse('error', 'Unknown request');
}
