<?php
echo "<!--elencoutenti -->\n";

if (!isset($tab) || $tab == "")
    $tab = 0;
if (!isset($tab2))
    $tab2 = 0;
if (!isset($npage))
    $npage = 0;
if (!isset($id))
    $id = 0;
if (!isset($id_item))
    $id_item = 0;

$errmsg = "";

if (!isset($ord))
    $ord = my_statevar_read("ordUtenti");
if (!isset($searchstr))
    $searchstr = my_statevar_read("searchstrUtenti");
if (!isset($nxpage))
    $nxpage = my_statevar_read("nxpageUtenti");
if (!isset($filtro1)){
    $filtro1 = getU_VAR("filtro1Utenti", $_idutente);
    #my_statevar_read("filtro1Utenti");
} else {
    setU_VAR("filtro1Utenti", $filtro1, $_idutente);
}
if (!isset($filtro2)){
    $filtro2 = getU_VAR("filtro2Utenti", $_idutente);
    #my_statevar_read("filtro1Utenti");
} else {
    setU_VAR("filtro2Utenti", $filtro2, $_idutente);
}

if (!isset($isubsezione) || $isubsezione == "")
    $isubsezione = 0;
if (empty($nxpage))
    $nxpage = 50;

if ($azione == "delUser") {
    $sql = "DELETE FROM t_utenti WHERE id_utenti=$id";
    $mydbU->ExecSql($sql);

    $sql = "DELETE FROM t_utenti_note WHERE id_utente=$id";
    $mydbU->ExecSql($sql);
}

if($azione=="insUser")
{

     $a_usrparams = find_post("usr_");
     $usrparams = serialize($a_usrparams); 

     foreach ($a_usrparams as $k => $v){

    	$a_usrparams[$k] = myencodeTxt($v);

    }

    extract($a_usrparams);
    $a_usrfparams = find_post("usrf_");
    $usrfparams = serialize($a_usrfparams); 

    foreach ($a_usrfparams as $k => $v){
    	$a_usrfparams[$k] = myencodeTxt($v);
    }

    extract($a_usrfparams);

    $sql = "INSERT INTO $tbl_utenti (nome, cognome, username, password, email, level, data_ins, tipo, tipo_reg, stato ) VALUES (";
    $sql .= "'$usr_nome', '$usr_cognome', '$usr_username', '$usr_password', '$usr_email', '$usr_level', NOW(), '1', '1', '1') ";
    $mydbU->ExecSql($sql);

    //echo $sql;
    $idu = $mydbU->LastInsertedId;

    

  if($idu>1 ){
        $errmsg = "L'Utente &egrave; stato inserito!";
        }				

}

if ($tab == 0 || $tab == 1 || $tab == 2) {

    switch ($ord) {
        case 0: {

                $orderby = "tu.cognome ASC";
            } break;

        case 1: {

                $orderby = "tu.cognome DESC";
            } break;
        case 2: {

                $orderby = "tu.email ASC";
            } break;
        case 3: {

                $orderby = "tu.email DESC";
            } break;
        case 4: {

                $orderby = "tu.data_ins ASC";
            } break;
        case 5: {

                $orderby = "tu.data_ins DESC";
            } break;

        case 6: {

                $orderby = "tp.titolo ASC";
            } break;
        case 7: {

                $orderby = "tp.titolo DESC";
            } break;
        case 8: {

            $orderby = "tp.data_rif ASC";
            } break;
            
        case 9: {

                $orderby = "tp.data_rif DESC";
            } break;


        default: {
            $ord = 0;
            $orderby = "tu.cognome ASC";
        }
}

    $cond = " ";
    $from = "";
    
    if ($searchstr != "") {
        $cond = " AND (tu.nome LIKE '%$searchstr%' OR tu.cognome LIKE '%$searchstr%' OR tu.email LIKE '%$searchstr%') ";
    }
    

    //if($filtro1 != "" && $filtro1>2) $filtro1="";
    //if($filtro2 != "" && $filtro2>2) $filtro2="";
    
    if($filtro1 != "" && $filtro1>0)
    {

    }
        if($filtro2 != "" && $filtro2>0)
    {

    }

    $ntot = 0;
    $a_utenti = array();

    if ($tab == 0)
        $sql = "SELECT COUNT(*) FROM t_utenti as tu $from WHERE tu.level<'$SUPLEVEL' $cond";
    elseif ($tab == 1)
        $sql = "SELECT COUNT(*) FROM t_utenti_temp as tu $cond";
    elseif ($tab == 2)
        $sql = "SELECT COUNT(*) FROM t_utenti as tu $from WHERE  tu.level & '$SUPLEVEL' AND tu.level<$SADMINLEVEL $cond";
    $mydb->DoSelect($sql);
    if (($rcount = $mydb->GetRow())) {
        $ntot = $rcount[0];
        $ntotpage = floor($ntot / $nxpage);
        if ($ntotpage != $ntot / $nxpage)
            $ntotpage++;

        $nn = $npage * $nxpage;


        if ($tab == 0)
            $sql = "SELECT tu.* FROM t_utenti as tu $from WHERE  tu.level<'$SUPLEVEL'  $cond ORDER BY $orderby LIMIT $nn, $nxpage";# ";
        elseif ($tab == 1)
            $sql = "SELECT tu.* FROM t_utenti_temp as tu $cond ORDER BY $orderby LIMIT $nn, $nxpage";# ";
        elseif ($tab == 2)
            $sql = "SELECT tu.* FROM t_utenti as tu $from WHERE   tu.level & '$SUPLEVEL' AND tu.level<$SADMINLEVEL  $cond ORDER BY $orderby LIMIT $nn, $nxpage";# ";
//echo $sql;        
        $a_utenti = $mydb->DoSelect($sql);
    }
}
?>
<script>

    function setTab(t)
    {
        document.frmins.tab.value = t;
        document.frmins.tab2.value = 0;
         waitpage();
        document.frmins.submit();
    }

    function setTab2(t)
    {
        waitpage();
        document.frmins.tab2.value = t;
        document.frmins.submit();
    }

    function editUser(id) {

        document.frmmenu.sezione.value = 'utenti,1';
        document.frmmenu.id.value = id;
        document.frmmenu.submit();

    }


    function delUser(id) {

        if (confirm('ATTENZIONE: confermi la cancellazione dell\'utente?'))
        {
            document.frmmenu.azione.value = 'delUser';
            document.frmmenu.id.value = id;
            document.frmmenu.submit();
        }
    }

    function back() {

        document.frmmenu.sezione.value = 'utenti,0';
        document.frmmenu.params.value = 'tab=<?=$tab?>';
        document.frmmenu.id.value = 0;
        document.frmmenu.submit();

    }

    function refresh()
    {
        waitpage();
        document.frmins.submit();
    }
    function esporta()
    {
        document.frmins.esporta.checked = true;
        refresh();
    }

    function setOrd(strord) {

        var ord = '<?= $ord ?>';

        if (strord == 'nome')
        {
            if (ord == '0')
                ord = 1;
            else
                ord = '0';
        }
        if (strord == 'email')
        {
            if (ord == '2')
                ord = 3;
            else
                ord = '2';
        }
        if (strord == 'data_reg')
        {
            if (ord == '4')
                ord = 5;
            else
                ord = '4';
        }


        waitpage();
        document.frmins.ord.value = ord;
        document.frmins.submit();
    }
    
function addGruppo()
{
    document.frmins.azione.value='addGruppo';
     waitpage();
    document.frmins.submit();
}
function editGruppo(id)
{
   document.frmmenu.sezione.value = 'utenti,3';
   document.frmmenu.id.value = id;
   waitpage();
   document.frmmenu.submit();
}
function delGruppo(id)
{
   document.frmmenu.azione.value = 'delGruppo';
   document.frmmenu.id.value = id;
   waitpage();
   document.frmmenu.submit();
}

function backtoSurveys()
{
    document.frmmenu.sezione.value = 'utenti,1';
    document.frmmenu.id.value = <?=$id?>;
    document.frmmenu.tab2.value = 1;
    document.frmmenu.strparam.value = '';
    waitpage();
    document.frmmenu.submit();
}

function viewSurvey(id_item)
{
    waitpage();
    document.frmmenu.sezione.value = 'utenti,4';
    document.frmmenu.id.value = <?=$id?>;
    document.frmmenu.tab2.value = 1;
    document.frmmenu.strparam.value = 'id_item=' + id_item;
    document.frmmenu.submit();
}
</script>
<div class="box_cnt box_in va-modern">
    
<?
if($errmsg!=""){
?>
<div class="boxerr">
    <?=$errmsg?>
</div>
<? } ?>

<?
$cl = "";
if($level>$GESTLEVEL) $cl = "tabmenuadmin";
if ($isubsezione == 0) {
    ?>
        <section class="card" style="margin-bottom:18px;">
            <div class="card__head">
                <div>
                    <h3 class="card__title">Utenti</h3>
                    <p class="card__subtitle">Gestione elenco utenti e stato account.</p>
                </div>
            </div>

            <div class="filters" style="margin-bottom:0;">
                <button type="button" class="filter-pill <? if ($tab == 0) echo "is-active"; ?>" onclick="setTab(0)">
                    <i class="bi bi-people"></i>
                    <span>Elenco utenti</span>
                </button>
            </div>
        </section>

        <div class="box_cnt va-content" style="text-align:left">
    <?
    if ($tab == 0) {

        ?>

                    <form name="frmins" method="post" action="<? echo $action ?>" >
                        <section class="card" style="margin-bottom:18px;">
                            <div class="card__head">
                                <div>
                                    <h3 class="card__title">Elenco utenti</h3>
                                    <p class="card__subtitle">Totale record: <?= (int)$ntot ?></p>
                                </div>
                            </div>

                            <div class="va-toolbar">
                                <div class="va-search">
                                    <i class="bi bi-search"></i>
                                    <input id="searchstr" class="control" type="text" name="searchstr" value="<?= htmlspecialchars((string)$searchstr, ENT_QUOTES, 'UTF-8') ?>" placeholder="Cerca per email o nominativo">
                                </div>

                                <button type="button" class="btn btn-soft va-btn" onclick="refresh()">
                                    <i class="bi bi-funnel"></i>
                                    <span>Filtra</span>
                                </button>

                                <? if ($searchstr != "") { ?>
                                <button type="button" class="btn btn-danger va-btn" onclick="document.frmins.searchstr.value='';refresh()">
                                    <i class="bi bi-x-circle"></i>
                                    <span>Reset</span>
                                </button>
                                <? } ?>

                                <div class="va-rows">
                                    <span>Righe:</span>
                                    <input class="control" type="text" name="nxpage" value="<?= htmlspecialchars((string)$nxpage, ENT_QUOTES, 'UTF-8') ?>">
                                </div>

                                <button type="button" class="btn btn-soft va-btn" onclick="document.frmins.submit()">
                                    <i class="bi bi-arrow-repeat"></i>
                                    <span>Applica</span>
                                </button>
                            </div>

<? /*
<div style="text-align: left" class="testo_evi">
<? if($esporta=='1')
{
    #$sqlfull = "SELECT * FROM t_utenti WHERE level<='1'  $cond ORDER BY $orderby ";
                              $sqlfull = "SELECT tu.* FROM t_utenti as tu, t_prodotti as tp WHERE tu.id_rel=tp.id AND tu.level<='1'  $cond ORDER BY $orderby ";# ";
    $a_full = $mydb->DoSelect($sqlfull);
    include "esporta.inc.php";
    
    ?>
<a href="download.php?path=csv&f=elenco.xls&t=<?=time()?>" target="_blank">scarica xls</a><br/>
<a href="download.php?path=csv&f=elenco.csv&t=<?=time()?>" target="_blank">scarica csv</a><br/>
<a href="download.php?path=csv&f=elenco.xlsx&t=<?=time()?>" target="_blank">scarica xlsx</a><br/> 
</div>  
<?
                              } */
?>

                            <?
                            $pagmode = '1';
                            $frm = "document.frmins";
                            $szp = (isset($sz) && $sz!="") ? $sz : "utenti";
                            $href0 = "?MSID=$MSID&sz=$szp";
                            if ($ntot > 0) {
                            ?>
                            <div class="admtitolo" align="left">
                                <? include "paginazione.php"; ?>
                            </div>
                            <? } ?>

                            <?
                            $html = '<table cellpadding="6" cellspacing="0">
                                <thead>
                                    <tr>
                                        <th>Nominativo</th>
                                        <th>Email</th>
                                        <th>Data registrazione</th>
                                        <th>Account</th>
                                        
                                    </tr>
                                </thead>

                                <tbody>
                                ';
                            $csv = "Nominativo;Email;Data registrazione;;\n";
                            ?>

                            <div class="table-wrap"  style="margin-top:12px;">
                                <table>
                                    <thead>
                                        <tr>
                                            <th>#</th>
                                            <th onclick="setOrd('nome')" style="cursor:pointer;">Nominativo</th>
                                            <th onclick="setOrd('email')" style="cursor:pointer;">Email</th>
                                            <th onclick="setOrd('data_reg')" style="cursor:pointer;">Data registrazione</th>
                                            <th>Account</th>
                                            <th>Azioni</th>
                                        </tr>
                                    </thead>

                                    <tbody>
                                    <?
                                    $i = 0;
                                    if (is_array($a_utenti))
                                    foreach ($a_utenti as $k => $r) {
                                        $i++;
                                        $nome = mydecodeTxt($r['nome']);
                                        $cognome = mydecodeTxt($r['cognome']) . " " . $nome;
                                        $email = mydecodeTxt($r['email']);
                                        $data_reg = Date_fromdbX($r['data_ins']);
                                        $idu = $r['id_utenti'];

                                        $stato=$r['stato'];
                                        $icostato = "verified.png";
                                        $altstato = "Attivo";
                                        if($stato=='0') {
                                            $icostato = "notaccept.png";
                                            $altstato = "Non attivo";
                                        }

                                        if($r['data_confermato']=="")  $icoemail = "notaccept.png";
                                        else $icoemail = "verified.png";
                                        $profilo = "";
                                    ?>
                                        <tr>
                                            <td data-label=""><?= $i + $nn ?></td>
                                            <td data-label="Cognome"><?= $cognome ?></td>
                                            <td data-label="Email"><?= $email ?></td>
                                            <td data-label="Data registrazione"><?= $data_reg ?></td>
                                            <td><img src="main/contents/icone/<?=$icostato?>" class="ico18" title="<?=$altstato?>" /></td>
                                            <td>
                                                <div class="actions">
                                                    <button class="action-icon" type="button" onclick="editUser(<?= $idu ?>)" title="Modifica">
                                                        <i class="bi bi-pencil"></i>
                                                    </button>
                                                    <button class="action-icon" type="button" onclick="delUser(<?= $idu ?>)" title="Elimina">
                                                        <i class="bi bi-trash"></i>
                                                    </button>
                                                </div>
                                            </td>
                                        </tr>
                                    <?
                                        $html .= '<tr>'
                                                . '<td>'.$cognome.'</td>'
                                                . '<td>'.$email.'</td>'
                                                . '<td>'.$data_reg.'</td>'
                                                . '<td></td>'
                                                . '</tr>
                                                ';
                                        $csv .= "$cognome;$email;$data_reg;;\n";
                                    }
                                    ?>
                                    </tbody>
                                </table>
                            </div>

                            <?
                            $html .= '</tbody>
                            </table>
                            ';
                            ?>

                            <?
                            $pagmode = '1';
                            $frm = "document.frmins";
                            $szp = (isset($sz) && $sz!="") ? $sz : "utenti";
                            $href0 = "?MSID=$MSID&sz=$szp";
                            if ($ntot > 0) {
                            ?>
                            <div class="admtitolo" align="left" style="margin-top:12px;">
                                <? include "paginazione.php"; ?>
                            </div>
                            <? } ?>

                            <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="" />

                            <input type="hidden" name="tab" value="<?= $tab ?>" />
                            <input type="hidden" name="tab2" value="<?= $tab2 ?>" />

                            <input type="hidden" name="ord" value="<?= $ord ?>" />
                        </section>
                    </form>

                    <?
                    /*
                    $xls = new HtmlExcel();
                    #$xls->setCss($css);
                    $xls->addSheet("Utenti", $html);
                    #$xls->addSheet("Names", $names);
                    #$xls->headers();
                    $out = $xls->buildFile();
                    
                   # $fout = fopen("_csv/Utenti_".Date("Ymd").$_idutente.".xls","w");
                   # fputs($fout,$out);
                   # fclose($fout);
                    */
                    $fcsv = fopen("_csv/Utenti_".Date("Ymd").$_idutente.".csv","w");
                    fputs($fcsv,$csv);
                    fclose($fcsv);
                     /*
                    $fnamecsv = "Utenti_".Date("Ymd").$_idutente.".csv";
                    $fnamexls = "Utenti_".Date("Ymd").$_idutente.".xlsx";
                    
                    include "PhpSpreadsheet/xlsx.inc.php";
                    
                    ?>
                <div class="admtitolo" align="left">
                    <a href="<?=$urlbase?>_csv/<?=$fnamexls?>" target="_blank"><img src="main/contents/icone/xlsx-file.png" class="ico24" /> Scarica elenco</a>
                    </div>
                */
                    ?>
                <script>
                   <?
                   if(isset($filtro1) && $filtro1!="")
        {
                       echo "document.frmins.filtro1.value='$filtro1';\n";
                   }
                   if(isset($filtro2) && $filtro2!="")
                   {
                       echo "document.frmins.filtro2.value='$filtro2';\n";
                   }
                   ?>
                       function setFiltro1()
                       {
                           document.frmins.filtro2.value='';
                           waitpage();
                           document.frmins.submit();
                       }
                       function setFiltro2()
                       {
                           document.frmins.filtro1.value='';
                           waitpage();
                           document.frmins.submit();
                       }
                </script>
                    <?
                    
                    my_statevar_create("ordUtenti", $ord);
                    my_statevar_create("searchstrUtenti", $searchstr);
                    my_statevar_create("nxpageUtenti", $nxpage);
                    my_statevar_create("filtro1Utenti", $filtro1);
                    my_statevar_create("filtro2Utenti", $filtro2);

    } elseif ($tab == 1) {

        include "utentisurveys.inc.php";

        
    } elseif ($tab == 4) {
                    ?>

                    <?
                    $sql = "SELECT tu.* FROM t_utenti as tu WHERE tu.level<='$MAXUSERSLEVEL' AND data_confermato IS NULL ORDER BY data_ins DESC"; # ";
                    $a_utenti = $mydbU->DoSelect($sql);
                    ?>
                    

                    <form name="frmins" method="post" action="<? echo $action ?>" >
                        <section class="card" style="margin-bottom:18px;">
                            <div class="card__head">
                                <div>
                                    <h3 class="card__title">Utenti da confermare</h3>
                                    <p class="card__subtitle">Record in attesa conferma: <?= is_array($a_utenti) ? count($a_utenti) : 0 ?></p>
                                </div>
                            </div>

                            <div class="table-wrap">
                                <table>
                                    <thead>
                                        <tr>
                                            <th>#</th>
                                            <th onclick="setOrd('nome')" style="cursor:pointer;">Nominativo</th>
                                            <th onclick="setOrd('email')" style="cursor:pointer;">Email</th>
                                            <th>Conferma</th>
                                            <th onclick="setOrd('data_reg')" style="cursor:pointer;">Data registrazione</th>
                                            <th>Azioni</th>
                                        </tr>
                                    </thead>

                                    <tbody>
                                    <?
                                    $i = 0;
                                    if (is_array($a_utenti))
                                        foreach ($a_utenti as $k => $r) {
                                            $i++;
                                            $nome = mydecodeTxt($r['nome']);
                                            $cognome = mydecodeTxt($r['cognome']) . " " . $nome;
                                            $email = mydecodeTxt($r['email']);
                                            $data_reg = Date_fromdbX($r['data_ins']);
                                            $idu = $r['id_utenti'];
                                            $profilo = "";
                                            if($r['data_confermato']=="")  $icostato = "notaccept.png";
                                            else $icostato = "verified.png";
                                            ?>
                                            <tr>
                                                <td data-label=""><?= $i ?></td>
                                                <td data-label="Cognome"><?= $cognome ?></td>
                                                <td data-label="Email"><?= $email ?></td>
                                                <td><img src="main/contents/icone/<?=$icostato?>" class="ico18"/></td>
                                                <td data-label="Data registrazione"><?= $data_reg ?></td>
                                                <td>
                                                    <div class="actions">
                                                        <button class="action-icon" type="button" onclick="editUser(<?= $idu ?>)" title="Modifica">
                                                            <i class="bi bi-pencil"></i>
                                                        </button>
                                                        <button class="action-icon" type="button" onclick="delUser(<?= $idu ?>)" title="Elimina">
                                                            <i class="bi bi-trash"></i>
                                                        </button>
                                                    </div>
                                                </td>
                                            </tr>
                                            <?
                                        }
                                    ?>
                                    </tbody>
                                </table>
                            </div>

                            <input type="hidden" name="MSID" value="<?= $MSID ?>" />
                            <input type="hidden" name="sz" value="utenti" />
                            <input type="hidden" name="azione" value="" />
                            <input type="hidden" name="id" value="" />

                            <input type="hidden" name="tab" value="<?= $tab ?>" />
                            <input type="hidden" name="tab2" value="<?= $tab2 ?>" />

                            <input type="hidden" name="ord" value="<?= $ord ?>" />
                        </section>
                    </form>

                <? } elseif ($tab == 2) { 
                    
                    include "gruppiutenti.inc.php";

                }
?>
    </div>
        
    <? } elseif ($isubsezione == 1) { ?>

        <div class="form-actions" style="margin-bottom:12px;">
            <button type="button" class="btn btn-soft" onclick="back()">
                <i class="bi bi-arrow-left"></i>
                <span>Indietro</span>
            </button>
        </div>

        <?
        include "utente.php";
        ?>


    <? } elseif ($isubsezione == 2) { ?>

        <div class="form-actions" style="margin-bottom:12px;">
            <button type="button" class="btn btn-soft" onclick="back()">
                <i class="bi bi-arrow-left"></i>
                <span>Indietro</span>
            </button>
        </div>

        <?
        include "nuovoutente.php";
        ?>
    <? } elseif ($isubsezione == 3) { ?>

        <div class="form-actions" style="margin-bottom:12px;">
            <button type="button" class="btn btn-soft" onclick="back()">
                <i class="bi bi-arrow-left"></i>
                <span>Indietro</span>
            </button>
        </div>

        <?
        include "edit_gruppo.php";
        ?>
      <? } elseif ($isubsezione == 4) { ?>

        <div class="form-actions" style="margin-bottom:12px;">
            <button type="button" class="btn btn-soft" onclick="backtoSurveys()">
                <i class="bi bi-arrow-left"></i>
                <span>Indietro</span>
            </button>
        </div>

        <?
        include "showSurvey.php";
        ?>

    <? } ?>

</div>

