<?php
if (!isset($id_item) || intval($id_item) <= 0) {
    echo "<div class=\"bordered\"><span class=\"testo_err\">Survey non valida.</span></div>";
    return;
}

$id_item = intval($id_item);

$sql = "SELECT si.id, si.id_survey, si.id_utente, si.data_ins, si.data_elab,
               s.descrizione, tu.nome, tu.cognome, tu.email
        FROM survey_items si
        LEFT JOIN surveys s ON s.id = si.id_survey
        LEFT JOIN t_utenti tu ON tu.id_utenti = si.id_utente
        WHERE si.id = $id_item";
$mydb->DoSelect($sql);
$info = $mydb->GetRow();

if (!$info) {
    echo "<div class=\"bordered\"><span class=\"testo_err\">Survey non trovata.</span></div>";
    return;
}

$id_survey = intval($info['id_survey']);
$utente_nome = trim(mydecodeTxt($info['nome']) . " " . mydecodeTxt($info['cognome']));
$utente_email = mydecodeTxt($info['email']);
$descrizione = mydecodeTxt($info['descrizione']);
$data_ins = Date_fromdbX($info['data_ins']);
$data_elab_raw = $info['data_elab'];
$stato = ($data_elab_raw == "0000-00-00 00:00:00" || $data_elab_raw == "") ? "In corso" : "Completato";
$data_elab = ($data_elab_raw == "0000-00-00 00:00:00" || $data_elab_raw == "") ? "-" : Date_fromdbX($data_elab_raw);

// Helper per formattare i valori
if (!function_exists('bc_admin_format_value')) {
    function bc_admin_format_value($raw)
    {
        $raw = mydecodeTxt($raw);
        $decoded = json_decode($raw, true);
        if (json_last_error() === JSON_ERROR_NONE && (is_array($decoded) || is_object($decoded))) {
            if (is_array($decoded)) {
                return implode(", ", array_map('strval', $decoded));
            }
            return json_encode($decoded);
        }
        return $raw;
    }
}

// Helper per mappare id -> testo dal template
if (!function_exists('bc_admin_build_label_map')) {
    function bc_admin_build_label_map($templateFile)
    {
        $labels = [];
        $order = [];

        if (!is_file($templateFile)) {
            return [$labels, $order];
        }

        $json = json_decode(file_get_contents($templateFile), true);
        if (!is_array($json) || !isset($json['sezioni']) || !is_array($json['sezioni'])) {
            return [$labels, $order];
        }

        foreach ($json['sezioni'] as $sezione) {
            if (!isset($sezione['domande']) || !is_array($sezione['domande'])) {
                continue;
            }
            foreach ($sezione['domande'] as $domanda) {
                $tipo = $domanda['tipo'] ?? '';
                if ($tipo === 'nota') {
                    continue;
                }
                if ($tipo === 'group' && isset($domanda['campi']) && is_array($domanda['campi'])) {
                    foreach ($domanda['campi'] as $campo) {
                        $cid = $campo['id'] ?? '';
                        if ($cid === '') {
                            continue;
                        }
                        if (!isset($labels[$cid])) {
                            $labels[$cid] = $campo['testo'] ?? $cid;
                            $order[] = $cid;
                        }
                    }
                    continue;
                }

                $id = $domanda['id'] ?? '';
                if ($id === '') {
                    continue;
                }
                if (!isset($labels[$id])) {
                    $labels[$id] = $domanda['testo'] ?? $id;
                    $order[] = $id;
                }
            }
        }

        return [$labels, $order];
    }
}

?>

<div class="box boxw bordered" style="text-align:left">
    <div class="titolo_big">Survey #<?=$id_item?></div>
    <div class="spessore"></div>
    <div class="testo"><strong>Template:</strong> <?=$descrizione?></div>
    <div class="testo"><strong>Utente:</strong> <?=$utente_nome?> (<?=$utente_email?>)</div>
    <div class="testo"><strong>Data creazione:</strong> <?=$data_ins?></div>
    <div class="testo"><strong>Stato:</strong> <?=$stato?></div>
    <div class="testo"><strong>Data elaborazione:</strong> <?=$data_elab?></div>
</div>

<div class="spessore"></div>

<?php
// Riutilizza la stessa struttura di elabora_business_case (tabelle + analisi IA)
$bc_admin_readonly = true;
include "elabora_business_case.php";
?>

<div class="spessore"></div>

<?php
// Riepilogo dati inseriti dall'utente
$templateFile = dirname(dirname(__DIR__)) . "/userdata/survey_template_" . $id_survey . ".json";
list($labelMap, $labelOrder) = bc_admin_build_label_map($templateFile);

$sql = "SELECT id, field_name, field_value
        FROM survey_items_data
        WHERE id_survey_item='$id_item'
        ORDER BY id ASC";
$aData = $mydb->DoSelect($sql);

$dataByName = [];
if (is_array($aData)) {
    foreach ($aData as $row) {
        $fname = mydecodeTxt($row['field_name']);
        $fval = $row['field_value'];
        $dataByName[$fname] = $fval;
    }
}

$used = [];
?>

<div class="box boxw bordered" style="text-align:left">
    <div class="titolo_big">Riepilogo Dati Inseriti</div>
    <div class="spessore"></div>
    <table class="tablegrid tablegrid3">
        <tr>
            <th>Campo</th>
            <th>Valore</th>
        </tr>
        <?php
        $hasRows = false;

        foreach ($labelOrder as $key) {
            $name = "srv_" . $key;
            if (!array_key_exists($name, $dataByName)) {
                continue;
            }
            $label = $labelMap[$key] ?? $key;
            $value = bc_admin_format_value($dataByName[$name]);
            $value = nl2br(htmlspecialchars($value, ENT_QUOTES, 'UTF-8'));
            $label = htmlspecialchars($label, ENT_QUOTES, 'UTF-8');
            echo "<tr><td>$label</td><td>$value</td></tr>";
            $used[$name] = true;
            $hasRows = true;

            // Gestione eventuale campo choice
            $choiceName = $name . "_choice";
            if (array_key_exists($choiceName, $dataByName)) {
                $choiceVal = bc_admin_format_value($dataByName[$choiceName]);
                $choiceVal = nl2br(htmlspecialchars($choiceVal, ENT_QUOTES, 'UTF-8'));
                echo "<tr><td>$label (scelta)</td><td>$choiceVal</td></tr>";
                $used[$choiceName] = true;
            }
        }

        foreach ($dataByName as $name => $rawVal) {
            if (isset($used[$name])) {
                continue;
            }
            $base = $name;
            if (strpos($base, 'srv_') === 0) {
                $base = substr($base, 4);
            }
            $label = $labelMap[$base] ?? $base;
            $value = bc_admin_format_value($rawVal);
            $value = nl2br(htmlspecialchars($value, ENT_QUOTES, 'UTF-8'));
            $label = htmlspecialchars($label, ENT_QUOTES, 'UTF-8');
            echo "<tr><td>$label</td><td>$value</td></tr>";
            $hasRows = true;
        }

        if (!$hasRows) {
            echo "<tr><td colspan=\"2\">Nessun dato salvato.</td></tr>";
        }
        ?>
    </table>
</div>
