<?php
echo "<!-- inc.editlabels.php -->\n";
?>
<!-- Flag Icons CSS per le bandiere SVG -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/lipis/flag-icons@7.2.3/css/flag-icons.min.css" />
<?php

// Includi il file delle azioni (salva)
include_once('inc.editlabels.actions.php');

if($isubsezione == 0)
{
    // Gestione ricerca
    $search = isset($_POST['search']) ? trim($_POST['search']) : (isset($_GET['search']) ? trim($_GET['search']) : '');
    
    if($tab == 3) {
        $condl = "AND l.nome NOT LIKE 'menu_%'";
    } elseif($tab == 1) {
        $condl = "AND l.nome LIKE 'menu_%' AND s._virtual = 0 AND s.menu = '1'";
    }
    
    // Condizione di ricerca
    $search_cond = '';
    if($search != '') {
        $search_escaped = $mydb->Escape('%'.$search.'%');
        $search_cond = " AND (l.nome LIKE $search_escaped OR l.des LIKE $search_escaped OR l.valore LIKE $search_escaped)";
    }
    
    // Lista delle labels - solo quelle associate a sezioni con visibility='public'
    $sql = "SELECT l.*, g.nome as nome_gruppo, g.label as label_gruppo
            FROM t_labels l
            INNER JOIN t_sezioni s ON l.id_sezione = s.id_sezione
            LEFT JOIN t_labels_gruppi g ON l.id_gruppo = g.id_labels_gruppi
            WHERE s.visibility = 'public'
            $condl
            $search_cond
            AND l.visibile = 1
            ORDER BY g.nome ASC, l.nome ASC";
    $res = $mydb->DoSelect($sql);
    $total_found = count($res);
?>

<div style="margin-bottom:20px;">
    <h2>Gestione Etichette (Labels)</h2>
    <p><strong>Nota:</strong> Le etichette sono utilizzate per i testi fissi nel sito.</p>
</div>

<!-- Campo di ricerca -->
<div style="margin-bottom:20px; padding:15px; background:#fff; border-radius:8px; border:1px solid #ddd;">
    <form name="frmsearch" method="post" action="<?=$action?>" style="display:flex; gap:10px; align-items:flex-end;">
        <input type="hidden" name="MSID" value="<?=$MSID?>" />
        <input type="hidden" name="sezione" value="cms" />
        <input type="hidden" name="tab" value="<?=$tab?>" />
        
        <div style="flex:1; max-width:400px;">
            <label style="display:block; margin-bottom:5px; font-weight:bold; font-size:13px;">
                <i class="bi bi-search" style="margin-right:5px;"></i> Cerca
            </label>
            <input type="text" name="search" value="<?=htmlspecialchars($search)?>" 
                   style="width:100%; padding:8px 12px; border:1px solid #ccc; border-radius:4px; font-size:14px; box-sizing:border-box;"
                   placeholder="Nome, descrizione o testo italiano..." />
        </div>
        
        <button type="submit" class="button" style="width:120px;">
            <div><i class="bi bi-search" style="margin-right:5px;"></i> Cerca</div>
        </button>
        
        <?php if($search != '') { ?>
        <button type="button" onclick="document.frmsearch.search.value=''; document.frmsearch.submit();" class="button buttonrev" style="width:120px;">
            <div><i class="bi bi-x-circle" style="margin-right:5px;"></i> Reset</div>
        </button>
        <?php } ?>
    </form>
    
    <?php if($search != '') { ?>
    <div style="margin-top:10px; font-size:13px; color:#666;">
        <strong>Risultati:</strong> <?=$total_found?> etichett<?=$total_found==1?'a':'e'?> trovata/e per "<strong><?=htmlspecialchars($search)?></strong>"
    </div>
    <?php } ?>
</div>

<? if($_level > $OPERLEVEL && $tab==3 ) { ?>
<!-- Form aggiunta nuova label -->
<div style="margin-bottom:30px; padding:20px; background:#f8f9fa; border-radius:8px; border:1px solid #ddd;">
    <h3 style="margin-top:0;"><i class="bi bi-plus-circle" style="margin-right:5px;"></i> Aggiungi Nuova Label</h3>
    
    <form name="frmnewlabel" method="post" action="<?=$action?>">
        <input type="hidden" name="MSID" value="<?=$MSID?>" />
        <input type="hidden" name="sezione" value="cms" />
        <input type="hidden" name="tab" value="<?=$tab?>" />
        <input type="hidden" name="azione" value="crea" />
        
        <div style="display:grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap:15px; margin-bottom:15px;">
            <div>
                <label style="display:block; margin-bottom:5px; font-weight:bold; font-size:13px;">Nome (chiave) *</label>
                <input type="text" name="nome_new" required 
                       style="width:100%; padding:8px; border:1px solid #ccc; border-radius:4px; font-size:13px; box-sizing:border-box;"
                       placeholder="es: titolo_home" />
                <small style="color:#666; font-size:11px;">Solo lettere minuscole, numeri e underscore</small>
            </div>
            
            <div>
                <label style="display:block; margin-bottom:5px; font-weight:bold; font-size:13px;">Valore Default *</label>
                <input type="text" name="valore_new" required 
                       style="width:100%; padding:8px; border:1px solid #ccc; border-radius:4px; font-size:13px; box-sizing:border-box;"
                       placeholder="Testo in italiano" />
                <small style="color:#666; font-size:11px;">Valore iniziale in italiano</small>
            </div>
            
            <div>
                <label style="display:block; margin-bottom:5px; font-weight:bold; font-size:13px;">Gruppo</label>
                <select name="id_gruppo_new" 
                        style="width:100%; padding:8px; border:1px solid #ccc; border-radius:4px; font-size:13px; box-sizing:border-box;">
                    <option value="">- Nessun gruppo -</option>
                    <?php
                    $sql_gruppi = "SELECT * FROM t_labels_gruppi ORDER BY nome ASC";
                    $gruppi = $mydb->DoSelect($sql_gruppi);
                    if(is_array($gruppi)) {
                        foreach($gruppi as $g) {
                            $g_label = $g['label'] != '' ? $g['label'] : $g['nome'];
                            echo '<option value="'.$g['id_labels_gruppi'].'">'.htmlspecialchars($g_label).'</option>';
                        }
                    }
                    ?>
                </select>
            </div>
            
            <div>
                <label style="display:block; margin-bottom:5px; font-weight:bold; font-size:13px;">Pagina (Sezione) *</label>
                <select name="id_sezione_new" required 
                        style="width:100%; padding:8px; border:1px solid #ccc; border-radius:4px; font-size:13px; box-sizing:border-box;">
                    <option value="">- Seleziona pagina -</option>
                    <?php
                    $sql_sez = "SELECT * FROM t_sezioni WHERE visibility='public' ORDER BY ordine_menu ASC, nome ASC";
                    $sezioni = $mydb->DoSelect($sql_sez);
                    if(is_array($sezioni)) {
                        foreach($sezioni as $s) {
                            echo '<option value="'.$s['id_sezione'].'">'.htmlspecialchars($s['nome']).'</option>';
                        }
                    }
                    ?>
                </select>
            </div>
        </div>
        
        <div style="margin-bottom:15px;">
            <label style="display:block; margin-bottom:5px; font-weight:bold; font-size:13px;">Descrizione</label>
            <input type="text" name="des_new" 
                   style="width:100%; padding:8px; border:1px solid #ccc; border-radius:4px; font-size:13px; box-sizing:border-box;"
                   placeholder="Breve descrizione dell'utilizzo" />
        </div>
        
        <button type="submit" class="button">
            <div>
                <i class="bi bi-plus-circle" style="margin-right:5px;"></i>
                Crea Label
            </div>
        </button>
    </form>
</div>
<? } ?>

<form name="frmins" method="post" action="<?=$action?>">

<div class="labels-table-container">
<table width="100%" border="0" cellspacing="0" cellpadding="0" class="labels-table">
  <thead>
  <tr>
    <th width="5%">ID</th>
    <th width="15%">Gruppo</th>
    <th width="20%">Testo Italiano</th>
    <? if($_level > $OPERLEVEL ) { ?>
    <th width="20%">Nome (chiave)</th>
    <? } ?>
    <th width="25%">Descrizione</th>
    <th width="15%">Azioni</th>
  </tr>
  </thead>
  <tbody>

<?php
if(count($res) == 0) {
    echo '<tr><td colspan="6" align="center" style="padding:40px;">📝 Nessuna etichetta presente.</td></tr>';
}

foreach($res as $row)
{
    $id_label = $row['id_label'];
    $nome = $row['nome'];
    $valore = $row['valore'];
    $des = $row['des'];
    $nome_gruppo = $row['nome_gruppo'] ?? '';
    $label_gruppo = $row['label_gruppo'] ?? '';
    
    // Usa label_gruppo se disponibile, altrimenti nome_gruppo
    $gruppo_display = ($label_gruppo != '') ? $label_gruppo : $nome_gruppo;
    if($gruppo_display == '') $gruppo_display = '<span style="color:#999;">-</span>';
    
    // Carica il valore italiano dalla tabella traduzioni
    $sql_it = "SELECT valore FROM t_testi_labels WHERE id_label=".$id_label." AND lang='it'";
    $mydb->DoSelect($sql_it);
    $row_it = $mydb->GetRow();
    $valore_it = ($row_it && $row_it['valore'] != '') ? $row_it['valore'] : $valore;
    if($valore_it != "") $valore_it = mydecodeTxt($valore_it);

    //PATCH TEMP
    $id_sez_label = $row['id_sezione'];
    $id_sezs_label = "";
    if($row['id_sezioni'] != '') $id_sezs_label = trim(str_replace("|", "", $row['id_sezioni']));
    if($id_sez_label == '' || $id_sez_label == '0' || $id_sez_label == -1) {
        $id_sez_label = $id_sezs_label; 
        if($id_sez_label == '') $id_sez_label = 1; // Default alla sezione 1


         $sql = "UPDATE t_labels SET id_sezione=".$id_sez_label." WHERE id_label=".$id_label;
        $mydb->ExecSql($sql);
    }
?>
  <tr class="label-row">
    <td class="label-id"><?=$id_label?></td>
    <td class="label-group"><?=$gruppo_display?></td>
    <td class="label-value"><strong><?=mydecodeTxt($valore_it)?></strong></td>
    <? if($_level > $OPERLEVEL ) { ?>
    <td class="label-name"><?=mydecodeTxt($nome)?></td>
    <? } ?>
    <td class="label-desc"><?=mydecodeTxt($des)?></td>
    <td class="label-actions">
        <button type="button" class="btn-translate" onclick="document.frmins.sezione.value='cms,1'; document.frmins.id_label.value='<?=$id_label?>'; document.frmins.submit();" title="Modifica traduzioni">
            <svg class="btn-icon" width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M4.5 11H5.914L12.5 4.414L11.086 3L4.5 9.586V11ZM13.207 3.707L12.293 2.793C11.902 2.402 11.269 2.402 10.878 2.793L10.086 3.586L11.5 5L12.293 4.207C12.684 3.816 12.684 3.183 12.293 2.793L13.207 3.707Z" fill="currentColor"/>
                <path d="M2 13.5C2 13.776 2.224 14 2.5 14H13.5C13.776 14 14 13.776 14 13.5V7.5C14 7.224 13.776 7 13.5 7H11V8H13V13H3V8H5V7H2.5C2.224 7 2 7.224 2 7.5V13.5Z" fill="currentColor"/>
            </svg>
            <span class="translate-text">Traduci</span>
        </button>
        <? if($_level > $OPERLEVEL ) { ?>
        <button type="button" class="btn-delete" onclick="if(confirm('Sei sicuro di voler eliminare questa etichetta e tutte le sue traduzioni?')) { document.frmins.azione.value='elimina'; document.frmins.id_label.value='<?=$id_label?>'; document.frmins.submit(); }" title="Elimina etichetta">
            <svg class="btn-icon" width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M5.5 5.5C5.77614 5.5 6 5.72386 6 6V12C6 12.2761 5.77614 12.5 5.5 12.5C5.22386 12.5 5 12.2761 5 12V6C5 5.72386 5.22386 5.5 5.5 5.5Z" fill="currentColor"/>
                <path d="M8 5.5C8.27614 5.5 8.5 5.72386 8.5 6V12C8.5 12.2761 8.27614 12.5 8 12.5C7.72386 12.5 7.5 12.2761 7.5 12V6C7.5 5.72386 7.72386 5.5 8 5.5Z" fill="currentColor"/>
                <path d="M11 6C11 5.72386 10.7761 5.5 10.5 5.5C10.2239 5.5 10 5.72386 10 6V12C10 12.2761 10.2239 12.5 10.5 12.5C10.7761 12.5 11 12.2761 11 12V6Z" fill="currentColor"/>
                <path fill-rule="evenodd" clip-rule="evenodd" d="M14.5 3C14.5 3.27614 14.2761 3.5 14 3.5H13.5V13.5C13.5 14.0523 13.0523 14.5 12.5 14.5H3.5C2.94772 14.5 2.5 14.0523 2.5 13.5V3.5H2C1.72386 3.5 1.5 3.27614 1.5 3C1.5 2.72386 1.72386 2.5 2 2.5H5.5V1.5C5.5 0.947715 5.94772 0.5 6.5 0.5H9.5C10.0523 0.5 10.5 0.947715 10.5 1.5V2.5H14C14.2761 2.5 14.5 2.72386 14.5 3ZM6.5 2.5V1.5H9.5V2.5H6.5ZM3.5 3.5V13.5H12.5V3.5H3.5Z" fill="currentColor"/>
            </svg>
            <span class="delete-text">Elimina</span>
        </button>
        <? } ?>
    </td>
  </tr>

<?php
}
?>
  </tbody>
</table>
</div>

        <input type="hidden" name="MSID" value="<?=$MSID?>" />
        <input type="hidden" name="sezione" value="cms" />
        <input type="hidden" name="azione" value="" />
        <input type="hidden" name="id_label" value="" />
        
        <input type="hidden" name="tab" value="<?=$tab?>" />
        <input type="hidden" name="tab2" value="<?=$tab2 ?? ''?>" />  
        
        <input type="hidden" name="ord" value="<?=$ord?>" />
</form>

<?php
}
else if($isubsezione == 1)
{
    // Form di modifica traduzioni
    $id_label = isset($_POST['id_label']) ? (int)$_POST['id_label'] : 0;
    
    if($id_label == 0) {
        echo "<div class='boxerr'>ID label non valido!</div>";
        return;
    }
    
    // Carica info label
    $sql = "SELECT * FROM t_labels WHERE id_label=".$id_label;
    $mydb->DoSelect($sql);
    $label_info = $mydb->GetRow();
    
    if(!$label_info) {
        echo "<div class='boxerr'>Etichetta non trovata!</div>";
        return;
    }
    
    $nome = $label_info['nome'];
    $valore_default = $label_info['valore'];
    $des = $label_info['des'];
    
    // Carica traduzioni esistenti
    $testi_lingue = array();
    $sql = "SELECT lang, valore FROM t_testi_labels WHERE id_label=".$id_label;
    $res_lingue = $mydb->DoSelect($sql);
    if(is_array($res_lingue)) {
        foreach($res_lingue as $row_lang) {
            $testi_lingue[$row_lang['lang']] = $row_lang['valore'];
        }
    }
?>

<div style="margin-bottom:20px;">
    <h2>Traduzioni per: <code><?=htmlspecialchars($nome)?></code></h2>
    <?php if($des != '') { ?>
    <p><strong>Descrizione:</strong> <?=htmlspecialchars($des)?></p>
    <?php } ?>
</div>

<form name="frmlabel" method="post" action="<?=$action?>">
    <input type="hidden" name="MSID" value="<?=$MSID?>" />
    <input type="hidden" name="sezione" value="cms,1" />
    <input type="hidden" name="tab" value="<?=$tab?>" />
    <input type="hidden" name="tab2" value="<?=$tab2 ?? ''?>" />
    <input type="hidden" name="ord" value="<?=$ord?>" />
    <input type="hidden" name="id_label" value="<?=$id_label?>" />
    <input type="hidden" name="azione" value="salva" />
    
    <table width="100%" border="0" cellspacing="5" cellpadding="5" class="tbladmin">
        <tr>
            <td width="20%" class="tbladmin_label">Nome (chiave):</td>
            <td>
                <strong><?=htmlspecialchars($nome)?></strong>
                <br><small>Questo campo non è modificabile</small>
            </td>
        </tr>
        
        <tr>
            <td width="20%" class="tbladmin_label">Valore Default:</td>
            <td>
                <strong><?=htmlspecialchars($valore_default)?></strong>
                <br><small>Valore originale nel database (campo "valore" in t_labels)</small>
            </td>
        </tr>
        
        <tr>
            <td width="20%" class="tbladmin_label" style="vertical-align:top; padding-top:15px;">Descrizione:</td>
            <td>
                <textarea name="des" rows="2" style="width:100%; max-width:600px; padding:8px; border:1px solid #ccc; border-radius:4px; font-size:13px; box-sizing:border-box;"><?=$des?></textarea>
                <br><small style="color:#666; font-size:11px;">Descrizione per identificare l'utilizzo di questa label</small>
            </td>
        </tr>
        
        <tr>
            <td class="tbladmin_label" style="vertical-align:top; padding-top:15px;">Traduzioni:</td>
            <td>
                <!-- Lingue disponibili -->
                <div style="display:flex; flex-wrap:wrap; gap:20px; max-width:100%;">
                    <?php 
                    // Mappa codici lingua a flag-icons (SVG)
                    $flags = array(
                        'it' => 'it',
                        'en' => 'gb',
                        'fr' => 'fr',
                        'es' => 'es',
                        'de' => 'de'
                    );
                    
                    foreach($_vlanguage as $idx => $lang_code) {
                        if($_vlanguage_enabled[$idx] == '1') {
                            $valore_lang = isset($testi_lingue[$lang_code]) ? $testi_lingue[$lang_code] : '';
                            
                            // Per l'italiano, usa il valore di default da t_labels se non c'è traduzione
                            if($lang_code == 'it' && $valore_lang == '') {
                                $valore_lang = $valore_default;
                            }
                            
                            $flag_code = isset($flags[$lang_code]) ? $flags[$lang_code] : 'un';
                            $lang_name = $_vdeslanguage[$idx];
                    ?>
                    <div style="flex:1 1 calc(60% - 10px); min-width:280px; max-width:100%; margin-bottom:15px; box-sizing:border-box;">
                        <label style="display:block; margin-bottom:8px; font-weight:bold; font-size:14px;">
                            <span class="fi fi-<?=$flag_code?>" style="margin-right:8px; width:24px; height:18px; display:inline-block; vertical-align:middle; border-radius:2px;"></span>
                            Testo (<?=strtoupper($lang_code)?>)
                        </label>
                        <textarea name="valore_<?=$lang_code?>" rows="1" style="width:100%; max-width:100%; padding:8px; border:1px solid #ccc; border-radius:4px; font-size:13px; box-sizing:border-box; resize:vertical;"><?=$valore_lang?></textarea>
                        <small style="color:#666; font-size:11px;">Traduzione in <?=ucfirst($lang_name)?></small>
                    </div>
                    <?php 
                        }
                    }
                    ?>
                </div>
            </td>
        </tr>
        
        <tr>
            <td></td>
            <td style="padding-top:20px;">
                <div class="button" onclick="waitpage();document.frmlabel.azione.value='salva'; document.frmlabel.submit();"><div>Salva Traduzioni</div></div>
                
                &nbsp;&nbsp;
                <div class="button buttonrev" onclick="document.frmlabel.azione.value=''; document.frmlabel.sezione.value='cms'; document.frmlabel.submit();"><div>Annulla</div></div>
            </td>
        </tr>
    </table>
</form>

<form name="frmins" method="post" action="<?=$action?>">
        <input type="hidden" name="MSID" value="<?=$MSID?>" />
        <input type="hidden" name="sezione" value="cms" />
        <input type="hidden" name="azione" value="" />
        <input type="hidden" name="tab" value="<?=$tab?>" />
        <input type="hidden" name="tab2" value="<?=$tab2 ?? ''?>" />  

</form>

<?php
}
?>

