<?php

$id_utente = (int)$_idutente;

$sql1 = "SELECT * FROM t_utenti WHERE id_utenti = $id_utente";
$mydb->DoSelect($sql1);
$ru = $mydb->GetRow();

$nomeUtente = mydecodeTxt($ru['nome']);
$cognomeUtente = mydecodeTxt($ru['cognome']);
$nominativo = trim($nomeUtente . " " . $cognomeUtente);
$nominativoSafe = htmlspecialchars($nominativo, ENT_QUOTES, 'UTF-8');

$oggi = Date("Y-m-d");
$dt1access = "n.d.";

if ($login == '1') {
    $sql2 = "SELECT * FROM t_accessi WHERE id_utente=$id_utente AND data_login < '$oggi' ORDER BY id DESC LIMIT 0,1";
    $mydb->DoSelect($sql2);
    if (($ra = $mydb->GetRow())) {
        $dt1access = Date_fromdbX($ra['data_login']);
    }
}

$msg = "";
$aSurveysUsers = array();
$surveyTotali = 0;
$surveyCompletate = 0;
$surveyInCorso = 0;
$ultimaSurvey = "Nessuna survey compilata";
$surveyNuoveOggi = 0;
$isUserDashboard = ($_level <= $MAXUSERSLEVEL);
$heroText = "Da questa dashboard puoi avviare una nuova survey, riprendere quelle in corso e consultare i business case gia elaborati.";
$heroBadgeLabel = "Survey totali";
$heroBadgeValue = 0;
$heroBadgeNote = "";

if ($isUserDashboard) {
    $sql = "SELECT si.id, si.id_survey, si.data_ins, si.data_elab, s.descrizione
            FROM survey_items si
            LEFT JOIN surveys s ON s.id = si.id_survey
            WHERE si.id_utente=$id_utente
            ORDER BY si.data_ins DESC";
    $aSurveysUsers = $mydb->DoSelect($sql);

    if (is_array($aSurveysUsers)) {
        $surveyTotali = count($aSurveysUsers);

        foreach ($aSurveysUsers as $r) {
            $isCompletata = !($r['data_elab'] == "0000-00-00 00:00:00" || $r['data_elab'] == "");
            if ($isCompletata) {
                $surveyCompletate++;
            } else {
                $surveyInCorso++;
            }
        }

        if ($surveyTotali > 0) {
            $ultimaSurvey = Date_fromdbX($aSurveysUsers[0]['data_ins']);
        }
    }
    
    $heroBadgeValue = $surveyTotali;
} else {
    $heroText = "Panoramica generale delle survey inserite dagli utenti e stato corrente delle elaborazioni.";

    $sql = "SELECT COUNT(*) AS n FROM survey_items";
    $mydb->DoSelect($sql);
    if (($rCount = $mydb->GetRow())) {
        $surveyTotali = (int)$rCount['n'];
    }

    $sql = "SELECT COUNT(*) AS n FROM survey_items WHERE DATE(data_ins) = '$oggi'";
    $mydb->DoSelect($sql);
    if (($rCount = $mydb->GetRow())) {
        $surveyNuoveOggi = (int)$rCount['n'];
    }

    $sql = "SELECT COUNT(*) AS n FROM survey_items WHERE data_elab IS NULL OR data_elab = '' OR data_elab = '0000-00-00 00:00:00'";
    $mydb->DoSelect($sql);
    if (($rCount = $mydb->GetRow())) {
        $surveyInCorso = (int)$rCount['n'];
    }

    $sql = "SELECT COUNT(*) AS n FROM survey_items WHERE data_elab IS NOT NULL AND data_elab <> '' AND data_elab <> '0000-00-00 00:00:00'";
    $mydb->DoSelect($sql);
    if (($rCount = $mydb->GetRow())) {
        $surveyCompletate = (int)$rCount['n'];
    }

    $heroBadgeLabel = "Nuove Survey Oggi";
    $heroBadgeValue = $surveyNuoveOggi;
}

$notaAccesso = ($login == '1')
    ? "Ultimo accesso registrato il $dt1access"
    : "Area personale disponibile dopo l'accesso";

$heroBadgeNote = $isUserDashboard
    ? $notaAccesso
    : (($surveyNuoveOggi == 1)
        ? "1 nuova survey inserita oggi"
        : "$surveyNuoveOggi nuove survey inserite oggi");
?>

<div class="box_in va-modern">

    <? if ($msg != "") { ?>
    <div class="card" style="margin-bottom:18px;border-left:4px solid #067647;">
        <div class="testo" style="padding:12px 14px;"><?= $msg ?></div>
    </div>
    <? } ?>

    <section class="hero">
        <div>
            <h2 class="hero__title">Benvenuto <?= $nominativoSafe ?>!</h2>
            <p class="hero__text"><?= htmlspecialchars($heroText, ENT_QUOTES, 'UTF-8') ?></p>

            <? if ($isUserDashboard) { ?>
            <div class="hero__actions">
                <button type="button" class="btn btn-primary" onclick="newSurvey()">
                    <i class="bi bi-plus-circle"></i>
                    <span>Nuova Survey</span>
                </button>
            </div>
            <? } ?>
        </div>

        <div class="hero__badge">
            <div class="hero__badge-label"><?= htmlspecialchars($heroBadgeLabel, ENT_QUOTES, 'UTF-8') ?></div>
            <div class="hero__badge-value"><?= (int)$heroBadgeValue ?></div>
            <div class="hero__badge-note"><?= htmlspecialchars($heroBadgeNote, ENT_QUOTES, 'UTF-8') ?></div>
        </div>
    </section>

    <? if ($isUserDashboard) { ?>
    <section class="stats-grid">
        <article class="stat-card">
            <div class="stat-card__head">
                <div class="stat-card__title">Totale Business Case</div>
                <div class="stat-card__icon"><i class="bi bi-collection"></i></div>
            </div>
            <div class="stat-card__value"><?= (int)$surveyTotali ?></div>
            <div class="stat-card__meta">Survey create nel tuo account</div>
        </article>

        <article class="stat-card">
            <div class="stat-card__head">
                <div class="stat-card__title">Survey In Corso</div>
                <div class="stat-card__icon"><i class="bi bi-hourglass-split"></i></div>
            </div>
            <div class="stat-card__value"><?= (int)$surveyInCorso ?></div>
            <div class="stat-card__meta">
                <span class="trend <?= $surveyInCorso > 0 ? 'trend--down' : 'trend--up' ?>">
                    <i class="bi <?= $surveyInCorso > 0 ? 'bi-arrow-repeat' : 'bi-check2' ?>"></i>
                    <span><?= $surveyInCorso > 0 ? 'Da completare' : 'Tutto completato' ?></span>
                </span>
            </div>
        </article>

        <article class="stat-card">
            <div class="stat-card__head">
                <div class="stat-card__title">Survey Completate</div>
                <div class="stat-card__icon"><i class="bi bi-check2-circle"></i></div>
            </div>
            <div class="stat-card__value"><?= (int)$surveyCompletate ?></div>
            <div class="stat-card__meta">Business case disponibili in consultazione</div>
        </article>

        <article class="stat-card">
            <div class="stat-card__head">
                <div class="stat-card__title">Ultima Attivita</div>
                <div class="stat-card__icon"><i class="bi bi-clock-history"></i></div>
            </div>
            <div class="stat-card__value" style="font-size:1.25rem;line-height:1.2;"><?= htmlspecialchars($ultimaSurvey, ENT_QUOTES, 'UTF-8') ?></div>
            <div class="stat-card__meta"><?= htmlspecialchars($notaAccesso, ENT_QUOTES, 'UTF-8') ?></div>
        </article>
    </section>

    <form name="frm1" id="frm1" method="post" action="<? echo $action ?>">
        <section class="card" id="user-business-case">
            <div class="card__head">
                <div>
                    <h3 class="card__title">Business Case</h3>
                    <p class="card__subtitle">Storico survey, stato elaborazione e accesso rapido a modifica o consultazione.</p>
                </div>

                <button type="button" class="btn btn-soft" onclick="newSurvey()">
                    <i class="bi bi-plus-circle"></i>
                    <span>Nuova Survey</span>
                </button>
            </div>

            <div class="table-wrap">
                <table class="tablegrid tablegrid3">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Survey</th>
                            <th>Data Creazione</th>
                            <th>Stato</th>
                            <th>Azioni</th>
                        </tr>
                    </thead>
                    <tbody>
                        <? if (is_array($aSurveysUsers) && count($aSurveysUsers) > 0) {
                            foreach ($aSurveysUsers as $r) {
                                $data_ins = Date_fromdbX($r['data_ins']);
                                $is_completed = !($r['data_elab'] == "0000-00-00 00:00:00" || $r['data_elab'] == "");
                                $stato = $is_completed ? "Completato" : "In corso";
                                $chipClass = $is_completed ? "chip chip--success" : "chip chip--warning";
                                $descrizione = trim(mydecodeTxt($r['descrizione']));
                                if ($descrizione == "") {
                                    $descrizione = "Survey #" . $r['id_survey'];
                                }
                        ?>
                        <tr>
                            <td><?= (int)$r['id'] ?></td>
                            <td><?= htmlspecialchars($descrizione, ENT_QUOTES, 'UTF-8') ?></td>
                            <td><?= htmlspecialchars($data_ins, ENT_QUOTES, 'UTF-8') ?></td>
                            <td><span class="<?= $chipClass ?>"><?= $stato ?></span></td>
                            <td>
                                <div class="actions">
                                    <? if ($is_completed) { ?>
                                    <button class="action-icon" type="button" onclick="viewSurvey(<?= (int)$r['id'] ?>)" title="Visualizza risultati">
                                        <i class="bi bi-eye"></i>
                                    </button>
                                    <? } else { ?>
                                    <button class="action-icon" type="button" onclick="editSurvey(<?= (int)$r['id'] ?>)" title="Continua survey">
                                        <i class="bi bi-pencil"></i>
                                    </button>
                                    <button class="action-icon" type="button" onclick="deleteSurvey(<?= (int)$r['id'] ?>)" title="Elimina survey">
                                        <i class="bi bi-trash"></i>
                                    </button>
                                    <? } ?>
                                </div>
                            </td>
                        </tr>
                        <? }
                        } else { ?>
                        <tr>
                            <td colspan="5" style="text-align:center;color:#667085;">Nessuna survey disponibile. Avvia la prima compilazione per creare un nuovo business case.</td>
                        </tr>
                        <? } ?>
                    </tbody>
                </table>
            </div>

            <p class="footer-note">Le survey in corso possono essere riprese in qualsiasi momento; quelle completate restano disponibili in sola consultazione.</p>

            <input type="hidden" name="MSID" value="<?=$MSID?>" />
            <input type="hidden" name="sz" value="<?=$sezione?>" />
            <input type="hidden" name="azione" value="" />
            <input type="hidden" name="id" value="0" />
            <input type="hidden" name="id_utente" value="<?=$id_utente?>" />
            <input type="hidden" name="id_item" value="<?=$id_item ?? ''?>" />
            <input type="hidden" name="step" value="<?=$stepto ?? ''?>" />
            <input type="hidden" name="tab" value="<?=$tab ?? ''?>" />
            <input type="hidden" name="tab2" value="<?=$tab2 ?? ''?>" />
            <input type="hidden" name="reloadSurvey" value="0" />
        </section>
    </form>

    <? } else { ?>
    <section class="stats-grid">
        <article class="stat-card">
            <div class="stat-card__head">
                <div class="stat-card__title">Survey Totali</div>
                <div class="stat-card__icon"><i class="bi bi-collection"></i></div>
            </div>
            <div class="stat-card__value"><?= (int)$surveyTotali ?></div>
            <div class="stat-card__meta">Totale business case presenti in piattaforma</div>
        </article>

        <article class="stat-card">
            <div class="stat-card__head">
                <div class="stat-card__title">Nuove Oggi</div>
                <div class="stat-card__icon"><i class="bi bi-calendar-plus"></i></div>
            </div>
            <div class="stat-card__value"><?= (int)$surveyNuoveOggi ?></div>
            <div class="stat-card__meta">Survey inserite nella giornata corrente</div>
        </article>

        <article class="stat-card">
            <div class="stat-card__head">
                <div class="stat-card__title">Survey In Corso</div>
                <div class="stat-card__icon"><i class="bi bi-hourglass-split"></i></div>
            </div>
            <div class="stat-card__value"><?= (int)$surveyInCorso ?></div>
            <div class="stat-card__meta">Compilazioni non ancora completate</div>
        </article>

        <article class="stat-card">
            <div class="stat-card__head">
                <div class="stat-card__title">Survey Completate</div>
                <div class="stat-card__icon"><i class="bi bi-check2-circle"></i></div>
            </div>
            <div class="stat-card__value"><?= (int)$surveyCompletate ?></div>
            <div class="stat-card__meta"><?= htmlspecialchars($notaAccesso, ENT_QUOTES, 'UTF-8') ?></div>
        </article>
    </section>

    <script>
    function editSurvey(id_item)
    {
        waitpage();
        document.frm1.id_item.value = id_item;
        document.frm1.id.value = 0;
        document.frm1.reloadSurvey.value = 1;
        document.frm1.sz.value = "surveys,1";
        document.frm1.submit();
    }

    function viewSurvey(id_item)
    {
        waitpage();
        document.frm1.id_item.value = id_item;
        document.frm1.id.value = 0;
        document.frm1.reloadSurvey.value = 1;
        document.frm1.sz.value = "surveys,3";
        document.frm1.submit();
    }

    function deleteSurvey(id_item)
    {
        if (!confirm("Sei sicuro di voler eliminare questa survey?")) return;
        waitpage();
        document.frm1.id_item.value = id_item;
        document.frm1.id.value = 0;
        document.frm1.sz.value = "surveys,0";
        document.frm1.azione.value = "delete";
        document.frm1.submit();
    }

    function newSurvey()
    {
        waitpage();
        document.frm1.azione.value = "";
        document.frm1.id.value = 0;
        document.frm1.sz.value = "surveys,2";
        document.frm1.submit();
    }
    </script>
    <? } ?>

</div>
