<?php
if (!function_exists('enrep_itemdetails_decode_json_array')) {
    function enrep_itemdetails_decode_json_array($raw): array
    {
        if (is_array($raw)) {
            return $raw;
        }
        $raw = trim((string)$raw);
        if ($raw === '') {
            return [];
        }
        $decoded = json_decode($raw, true);
        return is_array($decoded) ? $decoded : [];
    }
}

if (!function_exists('enrep_itemdetails_decode_legacy_list')) {
    function enrep_itemdetails_decode_legacy_list($raw): array
    {
        if (is_array($raw)) {
            return $raw;
        }
        $raw = trim((string)$raw);
        if ($raw === '') {
            return [];
        }
        $decoded = @unserialize($raw);
        return is_array($decoded) ? $decoded : [];
    }
}

if (!function_exists('enrep_itemdetails_clean_array')) {
    function enrep_itemdetails_clean_array(array $data): array
    {
        $clean = [];
        foreach ($data as $key => $value) {
            if (is_array($value)) {
                $value = enrep_itemdetails_clean_array($value);
                if ($value !== []) {
                    $clean[$key] = $value;
                }
                continue;
            }
            $value = trim((string)$value);
            if ($value !== '') {
                $clean[$key] = $value;
            }
        }
        return $clean;
    }
}

if (!function_exists('enrep_pressure_yes_no_value')) {
    function enrep_pressure_yes_no_value($value)
    {
        $value = strtolower(trim((string)$value));
        return in_array($value, ['yes', '1', 'true', 'y'], true) ? 'Yes' : 'No';
    }
}

if (!function_exists('enrep_itemdetails_pressure_from_record')) {
    function enrep_itemdetails_pressure_from_record(array $row): array
    {
        return enrep_itemdetails_clean_array(enrep_itemdetails_decode_json_array($row['pressure_data'] ?? ''));
    }
}

if (!function_exists('enrep_itemdetails_lev_from_record')) {
    function enrep_itemdetails_lev_from_record(array $row): array
    {
        $lev = enrep_itemdetails_clean_array(enrep_itemdetails_decode_json_array($row['lev_data'] ?? ''));
        if (!empty($lev['fan_details']) && empty($lev['fan_detail']) && empty($lev['fan_volume']) && empty($lev['fan_direction'])) {
            $fan = explode('|', (string)$lev['fan_details']);
            $lev['fan_detail'] = $fan[0] ?? '';
            $lev['fan_volume'] = $fan[1] ?? '';
            $lev['fan_direction'] = $fan[2] ?? '';
        }
        return enrep_itemdetails_clean_array($lev);
    }
}

if (!function_exists('enrep_itemdetails_json_from_request')) {
    function enrep_itemdetails_json_from_request(array $request, array $record = []): array
    {
        $source = array_merge($record, $request);
        $pressure = enrep_itemdetails_pressure_from_record($source);
        $lev = enrep_itemdetails_lev_from_record($source);

        if (isset($request['pressure']) && is_array($request['pressure'])) {
            $pressure = array_replace_recursive($pressure, enrep_itemdetails_clean_array($request['pressure']));
        }
        if (isset($request['lev']) && is_array($request['lev'])) {
            $lev = array_replace_recursive($lev, enrep_itemdetails_clean_array($request['lev']));
        }
        if (!empty($request['pressure_data'])) {
            $pressure = array_replace_recursive($pressure, enrep_itemdetails_decode_json_array($request['pressure_data']));
        }
        if (!empty($request['lev_data'])) {
            $lev = array_replace_recursive($lev, enrep_itemdetails_decode_json_array($request['lev_data']));
        }

        return [
            'pressure_data' => json_encode(enrep_itemdetails_clean_array($pressure), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
            'lev_data' => json_encode(enrep_itemdetails_clean_array($lev), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
        ];
    }
}

if (!function_exists('enrep_itemdetails_component_rows_from_request')) {
    function enrep_itemdetails_component_rows_from_request(array $request, string $component): array
    {
        $rows = [];
        if (isset($request['pressure'][$component]) && is_array($request['pressure'][$component])) {
            foreach ($request['pressure'][$component] as $row) {
                if (!is_array($row)) {
                    continue;
                }
                $clean = enrep_itemdetails_clean_array([
                    'range' => $row['range'] ?? '',
                    'serial' => $row['serial'] ?? '',
                    'make' => $row['make'] ?? '',
                    'TEP' => $row['TEP'] ?? ($row['tep'] ?? ''),
                    'IEP' => $row['IEP'] ?? ($row['iep'] ?? ''),
                ]);
                if ($clean !== []) {
                    $rows[] = $clean;
                }
            }
            return $rows;
        }

        if (($request[$component] ?? '') !== 'on') {
            return [];
        }

        foreach (range(0, 50) as $index) {
            $rangeKey = $component . 'Range' . $index;
            if (trim((string)($request[$rangeKey] ?? '')) === '') {
                continue;
            }
            $rows[] = enrep_itemdetails_clean_array([
                'range' => $request[$rangeKey] ?? '',
                'serial' => $request[$component . 'Serial' . $index] ?? '',
                'make' => $request[$component . 'Make' . $index] ?? '',
                'TEP' => $request[$component . 'TEP' . $index] ?? '',
                'IEP' => $request[$component . 'IEP' . $index] ?? '',
            ]);
        }

        return $rows;
    }
}

if (!function_exists('enrep_itemdetails_apply_nested_formdata')) {
    function enrep_itemdetails_apply_nested_formdata(array &$request): void
    {
        $pressure = [];
        if (!empty($request['pressure_data'])) {
            $pressure = enrep_itemdetails_decode_json_array($request['pressure_data']);
        }
        if (isset($request['pressure']) && is_array($request['pressure'])) {
            $pressure = array_replace_recursive($pressure, $request['pressure']);
        }

        foreach (['valve', 'gauge', 'burst'] as $component) {
            $rows = enrep_itemdetails_component_rows_from_request($request, $component);
            if ($rows !== []) {
                $pressure[$component] = $rows;
            }
        }
        $request['pressure'] = $pressure;

        $lev = [];
        if (!empty($request['lev_data'])) {
            $lev = enrep_itemdetails_decode_json_array($request['lev_data']);
        }
        if (isset($request['lev']) && is_array($request['lev'])) {
            $lev = array_replace_recursive($lev, $request['lev']);
        }

        $request['lev'] = $lev;
    }
}

if (!function_exists('enrep_itemdetails_try_save_json')) {
    function enrep_itemdetails_try_save_json(mysqli $con, int $itemnumber, string $pressureJson, string $levJson): void
    {
        if ($itemnumber <= 0) {
            return;
        }
        try {
            $stmt = $con->prepare("UPDATE `itemdetails` SET `pressure_data`=?, `lev_data`=? WHERE `itemnumber`=?");
        } catch (Throwable $e) {
            return;
        }
        if (!$stmt) {
            return;
        }
        $stmt->bind_param('ssi', $pressureJson, $levJson, $itemnumber);
        try {
            $stmt->execute();
        } catch (Throwable $e) {
            $stmt->close();
            return;
        }
        $stmt->close();
    }
}
