<?php
require_once __DIR__ . '/../security.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, 'Tenant config not found');
}

require_once(ROOT_URL . '/includes/master/form_functions.php');
enrep_require_user();

if ((int)($_SESSION['access'] ?? 0) !== 999) {
    enrep_fail(403, 'Admin access required');
}

$tables = ['reportitems', 'reportitems_temp', 'archiveitems'];
$reportFields = enrepReportDataFields();
$fixedFields = array_flip(enrepReportFixedFields());
$summary = [];

foreach ($tables as $table) {
    $summary[$table] = ['scanned' => 0, 'converted' => 0, 'skipped' => 0, 'errors' => []];

    $sql = "SELECT * FROM `$table` WHERE `reportdata` IS NULL OR `reportdata`=''";
    $res = mysqli_query($GLOBALS['con'], $sql);
    if (!$res) {
        $summary[$table]['errors'][] = mysqli_error($GLOBALS['con']);
        continue;
    }

    $stmt = $GLOBALS['con']->prepare("UPDATE `$table` SET `reportdata`=? WHERE `repitem`=?");
    if (!$stmt) {
        $summary[$table]['errors'][] = mysqli_error($GLOBALS['con']);
        continue;
    }

    while ($row = mysqli_fetch_assoc($res)) {
        $summary[$table]['scanned']++;
        $reportData = [];

        foreach ($reportFields as $field) {
            if (!array_key_exists($field, $row) || array_key_exists($field, $fixedFields)) {
                continue;
            }

            $value = $row[$field];
            if ($field === 'process_conditions') {
                $decoded = enrepDecodeJsonArray($value);
                if (!empty($decoded)) {
                    foreach ($decoded as $decodedKey => $decodedValue) {
                        $reportData[(string)$decodedKey] = $decodedValue;
                    }
                    continue;
                }
            }

            if ($value !== null && $value !== '') {
                $reportData[$field] = $value;
            }
        }

        if (empty($reportData)) {
            $summary[$table]['skipped']++;
            continue;
        }

        $json = enrepReportDataJson($reportData);
        $repitem = (int)($row['repitem'] ?? 0);
        $stmt->bind_param('si', $json, $repitem);
        if (!$stmt->execute()) {
            $summary[$table]['errors'][] = 'repitem ' . $repitem . ': ' . $stmt->error;
            continue;
        }

        $summary[$table]['converted']++;
    }

    $stmt->close();
}

header('Content-Type: application/json');
echo json_encode(['ok' => true, 'summary' => $summary], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
