<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

$static_url = dirname($_SERVER['SCRIPT_NAME']) . '/assets/';
include 'session_check.php';

$page_title = 'Textos do App';

$page_content = '
<div class="card mb-6">

<div class="card-header border-0 pt-6">

<div class="card-title">
<div>
<h3 class="mb-1">📝 Textos do Aplicativo</h3>
<div class="text-muted fs-7">Edite os textos fixos do app sem recompilar o APK.</div>
</div>
</div>

<div class="card-toolbar gap-2">

<button type="button" class="btn btn-light-primary" onclick="rebuildTextCache()">
<i class="fas fa-sync"></i> Reconstruir cache
</button>

<button type="button" class="btn btn-light-danger" onclick="restoreAllDefaults()">
<i class="fas fa-trash"></i> Restaurar tudo
</button>

</div>

</div>


<div class="card-body pt-0">

<div class="row g-4 mb-6">

<div class="col-md-6">

<div class="input-group">

<div class="input-group">

<span class="input-group-text bg-dark border-dark text-light">
<i class="fas fa-search"></i>
</span>

<input
type="text"
id="search_texts"
class="form-control bg-dark border-dark"
placeholder="Buscar textos do aplicativo..."
style="color:#ffffff; caret-color:#ffffff;"
>

</div>


</div>

<div class="col-md-6 d-flex align-items-center text-muted fs-7" id="texts_summary">
Carregando textos...
</div>

</div>


<div class="table-responsive">

<table class="table align-middle table-row-dashed fs-6 gy-4">

<thead>
<tr class="text-start text-gray-700 fw-bold fs-7 text-uppercase gs-0">

<th class="min-w-300px">Texto padrão</th>
<th class="min-w-300px">Texto atual</th>
<th class="min-w-150px">Atualizado</th>
<th class="min-w-150px text-end">Ações</th>

</tr>
</thead>

<tbody id="app_texts_table_body"></tbody>

</table>

</div>

</div>

</div>


<div class="modal fade" id="text_modal" tabindex="-1">

<div class="modal-dialog modal-dialog-centered mw-900px">

<div class="modal-content">

<div class="modal-header">

<h2 class="fw-bold mb-1">Editar texto</h2>

<button type="button" class="btn-close" data-bs-dismiss="modal"></button>

</div>

<div class="modal-body">

<input type="hidden" id="modal_key_name">

<div class="mb-5">
<label class="fw-semibold fs-6 mb-2">Texto padrão</label>
<div class="form-control form-control-solid" id="modal_default_value"></div>
</div>

<div class="mb-3">
<label class="fw-semibold fs-6 mb-2">Texto atual</label>

<textarea
class="form-control"
id="modal_current_value"
rows="4"
placeholder="Digite o novo texto"
></textarea>

</div>

</div>

<div class="modal-footer">

<button class="btn btn-light" data-bs-dismiss="modal">
Cancelar
</button>

<button class="btn btn-light-danger" onclick="restoreCurrentItem()">
<i class="fas fa-undo"></i> Restaurar
</button>

<button class="btn btn-primary" onclick="saveCurrentItem()">
<i class="fas fa-save"></i> Salvar
</button>

</div>

</div>

</div>

</div>

';

include 'includes/layout.php';
?>

<script>

let textRows=[];

function escapeHtml(value){

return String(value ?? "")
.replace(/&/g,"&amp;")
.replace(/</g,"&lt;")
.replace(/>/g,"&gt;")
.replace(/"/g,"&quot;")
.replace(/'/g,"&#039;");

}



function loadTexts(){

fetch("actions/app_texts_actions.php",{

method:"POST",
headers:{ "Content-Type":"application/json"},
body:JSON.stringify({action:"view"})

})

.then(res=>res.json())

.then(data=>{

if(!data.success){

Swal.fire("Erro",data.message,"error");
return;

}

textRows=data.data||[];

renderTable(textRows);
updateSummary();

});

}



function renderTable(data){

const tbody=document.getElementById("app_texts_table_body");

tbody.innerHTML=data.map(item=>{

return`

<tr>

<td>${escapeHtml(item.default_value)}</td>

<td>
<div class="fw-semibold">
${escapeHtml(item.current_value)}
</div>
</td>

<td>
<span class="text-muted fs-8">
${escapeHtml(item.updated_at || "-")}
</span>
</td>

<td class="text-end">

<button class="btn btn-sm btn-light-primary me-2"
onclick="openEditModal('${escapeHtml(item.key_name)}')">

<i class="fas fa-edit"></i> Editar

</button>

<button class="btn btn-sm btn-light-danger"
onclick="restoreOne('${escapeHtml(item.key_name)}')">

<i class="fas fa-undo"></i>

</button>

</td>

</tr>

`;

}).join("");

}



function searchTexts(){

const search=document
.getElementById("search_texts")
.value
.toLowerCase()
.trim();

if(!search){

renderTable(textRows);
return;

}

const filtered=textRows.filter(item=>{

const defaultText=(item.default_value||"").toLowerCase();
const currentText=(item.current_value||"").toLowerCase();

return defaultText.includes(search) || currentText.includes(search);

});

renderTable(filtered);

}



function updateSummary(){

const total=textRows.length;

const custom=textRows.filter(item=>
(item.current_value||"") !== (item.default_value||"")
).length;

document.getElementById("texts_summary").innerText=
`${total} textos • ${custom} personalizados`;

}



function openEditModal(key){

const row=textRows.find(i=>i.key_name===key);
if(!row)return;

document.getElementById("modal_key_name").value=row.key_name;
document.getElementById("modal_default_value").innerText=row.default_value;
document.getElementById("modal_current_value").value=row.current_value;

new bootstrap.Modal(document.getElementById("text_modal")).show();

}



function saveCurrentItem(){

const key=document.getElementById("modal_key_name").value;
const value=document.getElementById("modal_current_value").value;

fetch("actions/app_texts_actions.php",{

method:"POST",
headers:{ "Content-Type":"application/json"},
body:JSON.stringify({

action:"update",
key_name:key,
current_value:value

})

})

.then(r=>r.json())
.then(data=>{

Swal.fire("Sucesso",data.message,"success");

bootstrap.Modal.getInstance(
document.getElementById("text_modal")
).hide();

loadTexts();

});

}



function restoreOne(key){

fetch("actions/app_texts_actions.php",{

method:"POST",
headers:{ "Content-Type":"application/json"},
body:JSON.stringify({

action:"restore_one",
key_name:key

})

})

.then(r=>r.json())
.then(data=>{

Swal.fire("Sucesso",data.message,"success");
loadTexts();

});

}



function restoreAllDefaults(){

Swal.fire({

title:"Restaurar todos os textos?",
icon:"warning",
showCancelButton:true

}).then(result=>{

if(!result.isConfirmed)return;

fetch("actions/app_texts_actions.php",{

method:"POST",
headers:{ "Content-Type":"application/json"},
body:JSON.stringify({action:"restore_all"})

})

.then(r=>r.json())
.then(data=>{

Swal.fire("Sucesso",data.message,"success");
loadTexts();

});

});

}



function rebuildTextCache(){

fetch("actions/app_texts_actions.php",{

method:"POST",
headers:{ "Content-Type":"application/json"},
body:JSON.stringify({action:"rebuild_cache"})

})

.then(r=>r.json())
.then(data=>{

Swal.fire("Sucesso","Cache reconstruído","success");

});

}



document
.getElementById("search_texts")
.addEventListener("keyup",function(e){

if(e.key==="Enter"){
searchTexts();
}else{
searchTexts();
}

});



document.addEventListener("DOMContentLoaded",loadTexts);

</script>
