/* JavaScript Language Translate */
function _L(k,fallback=''){return window.FAX_LANG?.[k]||fallback||k;}


/* Modal - Core */
function openModal(title,body,actions=''){
const commonModal=document.getElementById('commonModal');
const modalTitle=document.getElementById('modalTitle');
const modalBody=document.getElementById('modalBody');
const modalActions=document.getElementById('modalActions');
if(!commonModal)return;
document.body.appendChild(commonModal);
commonModal.style.display='flex';
modalTitle.innerText=title;
modalBody.innerHTML=body;
modalActions.innerHTML=actions;
}
function closeModal(){
const commonModal=document.getElementById('commonModal');
const modalBody=document.getElementById('modalBody');
const modalActions=document.getElementById('modalActions');
if(!commonModal)return;
commonModal.style.display='none';
modalBody.innerHTML='';
modalActions.innerHTML='';
}


/* Modal - Post Helper */
function postToSelf(params={}){
const form=document.createElement('form');
form.method='POST';
form.action=window.location.href;
if(window.csrf){params.csrf=window.csrf;}
for(const k in params){
const i=document.createElement('input');
i.type='hidden';
i.name=k;
i.value=params[k];
form.appendChild(i);
}
document.body.appendChild(form);
form.submit();
}


/* Modal - Url Submit */
function submitByUrl(url){
const u=new URL(url,location.origin);
const form=document.createElement('form');
form.method='POST';
form.action=u.pathname;
u.searchParams.forEach((v,k)=>{
const i=document.createElement('input');
i.type='hidden';
i.name=k;
i.value=v;
form.appendChild(i);
});
document.body.appendChild(form);
form.submit();
}


/* Modal - Search (Integrated) */
function openSearchDialog(){
const e=window.FAX_ENV||{};
const params=new URLSearchParams(window.location.search);
const isSettingsPage=window.location.pathname.includes('fax_settings.php');
const isContactsPage=window.location.pathname.includes('fax_contacts.php');
let defaultView=isContactsPage?'all':(isSettingsPage?'profile':'');
const currentView=params.get('view')||window.VIEW_MODE||defaultView;
const currentSearch=e.search||'';
const searchMemo=e.withMemo===1;
let title=_L('search'),body='',actions='';
if(isContactsPage||(isSettingsPage&&currentView==='account')){
const targetAction=isSettingsPage?'fax_settings.php':'fax_contacts.php';
let submitView=currentView;
if(isContactsPage&&submitView==='profile')submitView='all';
body=`<form method="GET" id="searchForm" action="${targetAction}">
<input type="hidden" name="view" value="${submitView}">
<input type="text" name="q" class="modal-input" placeholder="${_L('keyword')}" value="${currentSearch}">
<div class="search-options" style="margin-top:10px;">
<label style="cursor:pointer;"><input type="checkbox" name="sm" value="1" ${searchMemo?'checked':''}>${_L('withMemo')}</label>
</div>
</form>`;
actions=`<button type="submit" form="searchForm" class="modal-btn danger half">${_L('search')}</button>
<button type="button" class="modal-btn half" onclick="closeModal()">${_L('cancel')}</button>`;
}else{
body=`<form method="get" id="faxSearchForm">
<input type="hidden" name="dir" value="${e.dir||''}">
<input type="text" name="q" class="modal-input" placeholder="${_L('keyword')}" value="${currentSearch}">
<div class="search-options">
<label><input type="checkbox" name="all_dirs" value="1" ${e.allDirs?'checked':''}>${_L('allDirs')}</label>
<label><input type="checkbox" name="with_memo" value="1" ${e.withMemo?'checked':''}>${_L('withMemo')}</label>
</div>
</form>`;
actions=`<button type="submit" form="faxSearchForm" class="modal-btn danger half">${_L('search')}</button>
<button type="button" class="modal-btn half" onclick="closeModal()">${_L('cancel')}</button>`;
}
openModal(title,body,actions);
}


/* Modal - New Folder */
function openNewFolderDialog(){
const body=`<input type="text" id="newFolderName" placeholder="${_L('folderAlert')}">`;
const actions=`<button class="modal-btn danger half" onclick="createNewFolder()">${_L('create')}</button><button class="modal-btn half" onclick="closeModal()">${_L('cancel')}</button>`;
openModal(_L('newFolder'),body,actions);
setTimeout(()=>{
document.getElementById('newFolderName')?.focus();
},100);
}
function createNewFolder(){
const e=window.FAX_ENV;
const n=document.getElementById('newFolderName')?.value.trim();
if(!n){
modalAlert(_L('folderAlert'));
return;
}
const form=document.createElement('form');
form.method='POST';
form.action=e.isInbox?e.inboxEdit:e.outboxEdit;
const inputs={cmd:'addfolder',folder:n,csrf:e.csrf};
for(const k in inputs){
const i=document.createElement('input');
i.type='hidden';
i.name=k;
i.value=inputs[k];
form.appendChild(i);
}
document.body.appendChild(form);
form.submit();
}


/* Modal - Delete Fax&Folder */
let deleteTargetUrl='';
function openDeleteDialog(url,msg,type){
deleteTargetUrl=url;
const title=(type==='folder')?_L('deleteFolder'):_L('deleteFax');
const body=`<p>${msg}</p>`;
const actions=`<button class="modal-btn danger half" onclick="confirmDelete()">${_L('delete')}</button><button class="modal-btn half" onclick="closeModal()">${_L('cancel')}</button>`;
openModal(title,body,actions);
}
function submitDelete(url){
const u=new URL(url,location.origin);
const form=document.createElement('form');
form.method='POST';
form.action=u.pathname;
u.searchParams.forEach((v,k)=>{
const i=document.createElement('input');
i.type='hidden';
i.name=k;
i.value=v;
form.appendChild(i);
});
const csrfToken=document.getElementById('csrf')?.value||window.FAX_ENV?.csrf;
if(csrfToken){
const i=document.createElement('input');
i.type='hidden';
i.name='csrf';
i.value=csrfToken;
form.appendChild(i);
}
document.body.appendChild(form);
form.submit();
}
function confirmDelete(){if(!deleteTargetUrl)return;closeModal();submitDelete(deleteTargetUrl);
}


/* Modal - Fax Unread */
let unreadTargetUrl='';
function openUnreadDialog(url,msg){
unreadTargetUrl=url;
const body=`<p>${msg}</p>`;
const actions=`<button class="modal-btn danger half" onclick="confirmUnread()">${_L('ok')}</button><button class="modal-btn half" onclick="closeModal()">${_L('cancel')}</button>`;
openModal(_L('unread'),body,actions);
}
function confirmUnread(){if(!unreadTargetUrl)return;closeModal();submitByUrl(unreadTargetUrl);
}


/* Modal - Resend */
let resendTargetUrl='';
function openResendDialog(u,m){
resendTargetUrl=u;
openModal(_L('resendFax'),`<p>${m}</p>`,`<button class="modal-btn danger half" onclick="confirmResend()">${_L('resendFax')}</button><button class="modal-btn half" onclick="closeModal()">${_L('cancel')}</button>`);
}
function confirmResend(){if(!resendTargetUrl)return;closeModal();submitByUrl(resendTargetUrl);
}


/* Modal - Cancel Schedule */
function openCancelScheduleDialog(){
openModal(_L('cancelSchedule'),`<p>${_L('cancelScheduleContent')}</p>`,`<button class="modal-btn danger half" onclick="confirmCancelSchedule()">${_L('ok')}</button><button class="modal-btn half" onclick="closeModal()">${_L('cancel')}</button>`);
}
function confirmCancelSchedule(){closeModal();postToSelf({cmd:'cancelSchedule'});
}


/* Modal - Memo(Alert) */
function openMemoAlert(el){
const memo=el.dataset.memo||'',date=el.dataset.date||'';
openModal(_L('faxMemo'),`<div class="memo-alert"><p>${memo}</p></div><div style="margin-top:8px;">${date?'🕒 '+date:''}</div>`,`<button class="modal-btn" onclick="closeModal()">${_L('ok')}</button>`);
}


/* Modal - Memo(All Version) */
function openMemoDialog(el){
if(!window.MEMO_FORM_HTML)return;
window.memoFax=el?.dataset.fax||'';window.memoDir=el?.dataset.dir||'';
const formHtml=window.MEMO_FORM_HTML.replace('value="<?=ns($faxName)?>"','value="'+window.memoFax+'"').replace('value="<?=ns($dir)?>"','value="'+window.memoDir+'"');
openModal(_L('faxMemo'),formHtml,window.MEMO_ACTIONS_HTML||'');
}
function saveMemo(){document.getElementById('memoForm')?.submit();}
window.confirmDeleteMemo=function(){
const form=document.getElementById('memoForm');if(!form)return;
const textarea=form.querySelector('textarea[name="memo"]');if(textarea)textarea.value='';
const formData=new FormData(form);
fetch(form.action,{method:form.method,body:formData}).finally(()=>{
closeModal();
const memoEl=document.querySelector(`.memo-icon[data-fax="${window.memoFax}"][data-dir="${window.memoDir}"]`);
if(memoEl){memoEl.dataset.memo='';memoEl.dataset.date='';memoEl.style.display='none';}
if(window.MEMO_FORM_HTML){
window.MEMO_FORM_HTML=window.MEMO_FORM_HTML.replace(/value=".*?"/g,m=>{
if(m.includes('name="fax"'))return`value="${window.memoFax}"`;
if(m.includes('name="dir"'))return`value="${window.memoDir}"`;
return m;
}).replace(/<textarea.*?>.*?<\/textarea>/s,`<textarea name="memo" rows="5" placeholder="${FAX_LANG.memokeyword}"></textarea>`).replace(/<div class="memo-time">.*?<\/div>/s,'').replace(/<\?php if\(\$memoTime\):\?>.*?<\?php endif;\?>/gs,'');
}
});
};


/* Modal - Rename Folder */
function openRenameFolderDialog(path){
const name=path.split('/').pop();
const body=`<input type="text" id="renameFolderInput" value="${name}" class="modal-input">`;
const actions=`<button class="modal-btn danger half" onclick="confirmRenameFolder('${path}')">${_L('ok')}</button><button class="modal-btn half" onclick="closeModal()">${_L('cancel')}</button>`;
openModal(_L('renameFolder'),body,actions);
setTimeout(()=>{document.getElementById('renameFolderInput')?.focus();},100);
}
function confirmRenameFolder(oldPath){
const input=document.getElementById('renameFolderInput');if(!input)return;
const newName=input.value.trim();
if(!newName){modalAlert(_L('folderAlert'));return;}
closeModal();
postToSelf({cmd:'renameFolder',old:oldPath,new:newName});
}


/* Modal - Fax Move */
let moveTargetPath='';let _moveSource='';
document.addEventListener('click',e=>{const btn=e.target.closest('.btn-move,#btn-move-trigger,#btn-move-link');if(!btn)return;openMoveDialog.call(btn,e);});
document.addEventListener('click',e=>{if(!e.target.classList.contains('folder-name'))return;document.querySelectorAll('#folderTree .folder-name.selected').forEach(el=>el.classList.remove('selected'));e.target.classList.add('selected');moveTargetPath=e.target.dataset.path;});
function openMoveDialog(e){
e.preventDefault();
_moveSource=this.dataset.path;
if(!window.FOLDER_TREE_HTML)return;
const body=`<div id="folderTree">${window.FOLDER_TREE_HTML}</div>`;
const actions=`<button class="modal-btn danger half" onclick="confirmMove()">${_L('move')}</button><button class="modal-btn half" onclick="closeModal()">${_L('cancel')}</button>`;
openModal(_L('move'),body,actions);
const selected=document.querySelector('#folderTree .folder-name.selected');
if(selected)moveTargetPath=selected.dataset.path;
}
function confirmMove(){
if(!_moveSource||!moveTargetPath)return;
closeModal();
postToSelf({cmd:'moveFax',path:_moveSource,location:moveTargetPath});
}


/* Modal - Contacts (Base) */
function openContactModal(mode,data=null,isAdmin=false){
const title=mode==='edit'?_L('editContact'):_L('addContact');
const csrf=window.csrf||"";
const finalIsAdmin=isAdmin||(typeof IS_ADMIN!=='undefined'&&IS_ADMIN===true);
let typeHtml='';
if(finalIsAdmin){const currentOrigin=(data&&data.origin)?data.origin:'users';
typeHtml=`<select name="type" id="contactType" class="modal-input" style="margin-bottom:10px;"><option value="users" ${currentOrigin==='users'?'selected' : ''}>${_L('users')} ${_L('contacts')}</option><option value="public" ${currentOrigin==='public'?'selected' : ''}>${_L('public')} ${_L('contacts')}</option></select>`;}
else{typeHtml=`<input type="hidden" name="type" value="users">`;}
const body=`<form id="contactForm" method="POST" autocomplete="on"><input type="hidden" name="cmd" value="${mode}"><input type="hidden" name="id" value="${data?data.id:''}"><input type="hidden" name="csrf" value="${csrf}">${typeHtml}<input type="text" name="name" autocomplete="name" placeholder="${_L('name')}" class="modal-input" style="margin-bottom:10px;" value="${data?data.name:''}" required><input type="text" name="fax" autocomplete="tel" placeholder="${_L('faxNumber')}" class="modal-input" style="margin-bottom:10px;" value="${data?data.fax:''}" oninput="this.value=this.value.replace(/[^0-9]/g,'')" required><textarea name="memo" autocomplete="off" placeholder="${_L('memoPlaceholder')}" class="modal-input" style="height:100px;">${data?data.memo:''}</textarea></form>`;
const actions=`<button type="button" class="modal-btn danger half" onclick="submitContactForm()">${_L('save')}</button><button type="button" class="modal-btn half" onclick="closeModal()">${_L('cancel')}</button>`;
openModal(title,body,actions);
}
window.submitContactForm=function(){const form=document.getElementById('contactForm');if(form&&form.reportValidity())form.submit();};


/* Modal - Contacts (Section) */
function openContactCategoryDialog(currentView){
const body=`
<button class="modal-option ${currentView==='all'?'active':''}" onclick="location.href='fax_contacts.php?view=all'">${_L('all')} ${_L('contacts')}</button>
<button class="modal-option ${currentView==='public'?'active':''}" onclick="location.href='fax_contacts.php?view=public'">${_L('public')} ${_L('contacts')}</button>
<button class="modal-option ${currentView==='users'?'active':''}" onclick="location.href='fax_contacts.php?view=users'">${_L('user')} ${_L('contacts')}</button>`;
openModal(_L('section'),body,`<button class="modal-btn" onclick="closeModal()">${_L('cancel')}</button>`);
}



/* Modal - Settings (Memo Alert) */
function openCMemoAlert(el){
const memo=el.dataset.memo||'',date=el.dataset.date||'';
openModal(_L('contactMemo'),`<div class="memo-alert"><p>${memo}</p></div>`,`<button class="modal-btn" onclick="closeModal()">${_L('ok')}</button>`);
}


/* Modal - Contacts (Delete) */
function openContactDeleteDialog(id,name,type){
const msg=_L('deleteConfirmMsg');
const body=`${msg}`;
const actions=`<button type="button" class="modal-btn danger half" onclick="postToSelf({cmd:'delete',id:'${id}',type:'${type}'})">${_L('delete')}</button><button type="button" class="modal-btn half" onclick="closeModal()">${_L('cancel')}</button>`;
openModal(_L('deleteContact'),body,actions);
}


/* Site - Fax Read(Index, Inbox) */
document.addEventListener('click',e=>{
const link=e.target.closest('.fax-link');
if(!link)return;
if(link.classList.contains('fax-read'))return;
const csrf=document.getElementById('csrf')?.value||'';
fetch('include/service/fax_read.php',{
method:'POST',
headers:{'Content-Type':'application/x-www-form-urlencoded'},
body:new URLSearchParams({file:link.dataset.file,dir:link.dataset.dir,csrf:csrf})
}).finally(()=>{const row=link.closest('tr');
if(!row)return;
row.querySelectorAll('.fax-new').forEach(b=>b.remove());
row.querySelectorAll('.fax-link').forEach(l=>{l.classList.remove('fax-unread');l.classList.add('fax-read');
});
});
});


/* Modal - Alarm - Alert*/
function modalAlert(msg,onClose){
const actions=`<button class="modal-btn danger half" id="modalAlertOk">${_L('ok')}</button>`;
openModal(_L('alert'),`<p>${msg}</p>`,actions);
setTimeout(()=>{
document.getElementById('modalAlertOk')?.addEventListener('click',()=>{closeModal();if(typeof onClose==='function')onClose();
});
},0);
}


/* Modal - Alarm - Help*/
function modalHelp(msg,onClose){
const actions=`<button class="modal-btn danger half" id="modalAlertOk">${_L('ok')}</button>`;
openModal(_L('help'),`<p>${msg}</p>`,actions);
setTimeout(()=>{
document.getElementById('modalAlertOk')?.addEventListener('click',()=>{closeModal();if(typeof onClose==='function')onClose();
});
},0);
}


/* Modal - Alarm - Confirm */
function modalConfirm(msg,onOk){
const actions=`<button class="modal-btn danger half" id="modalConfirmOk">${_L('ok')}</button><button class="modal-btn half" onclick="closeModal()">${_L('cancel')}</button>`;
openModal(_L('alert'),`<p>${msg}</p>`,actions);
setTimeout(()=>{document.getElementById('modalConfirmOk')?.addEventListener('click',()=>{closeModal();if(typeof onOk==='function')onOk();
});
},0);
}


/* Modal - Settings (Category) */
function openSettingsDialog(){openSettingsCategoryDialog(VIEW_MODE);}
function openSettingsCategoryDialog(currentView){
const body=`
<button class="modal-option ${currentView==='profile'?'active':''}" onclick="location.href='?view=profile'">${_L('Profile')}</button>
<button class="modal-option ${currentView==='system'?'active':''}" onclick="location.href='?view=system'">${_L('System')}</button>
<button class="modal-option ${currentView==='permissions'?'active':''}" onclick="location.href='?view=permissions'">${_L('Permissions')}</button>
<button class="modal-option ${currentView==='account'?'active':''}" onclick="location.href='?view=account'">${_L('Account')}</button>`;
openModal(_L('section'),body,`<button class="modal-btn" onclick="closeModal()">${_L('cancel')}</button>`);
}


/* Modal - Settings (Account Delete) */
function openUserDeleteDialog(username,csrfToken){
const msg=_L('deleteConfirm');
const body=`<p>${msg}</p>`;
const actions=`<button type="button" class="modal-btn danger half" onclick="submitUserDelete('${username}','${csrfToken}')">${_L('delete')}</button><button type="button" class="modal-btn half" onclick="closeModal()">${_L('cancel')}</button>`;
openModal(_L('deleteAccount'),body,actions);
}
function submitUserDelete(username,csrfToken){
const form=document.createElement('form');
form.method='POST';
form.innerHTML=`<input type="hidden" name="csrf" value="${csrfToken}"><input type="hidden" name="mode" value="account"><input type="hidden" name="user_action" value="delete"><input type="hidden" name="username" value="${username}">`;
document.body.appendChild(form);
form.submit();
}


/* Modal - Settings (New & Edit Account) */
function openUserModal(mode,csrfToken,data=null){
const title=mode==='edit'?_L('editAccount'):_L('addAccount');
const isEdit=mode==='edit';
const isSelf=isEdit&&data&&(data.username===window.FAX_ENV?.currentUser);
const roleAttr=isSelf?'style="margin-bottom:10px;pointer-events:none;" tabindex="-1"':'style="margin-bottom:10px;"';
const body=`<form id="userModalForm" method="POST">
<input type="hidden" name="csrf" value="${csrfToken}">
<input type="hidden" name="mode" value="account">
<input type="hidden" name="user_action" value="${isEdit?'update':'add'}">
<select name="role" class="modal-input" ${roleAttr}>
<option value="view" ${data?.role==='view'?'selected':''}>${_L('View')} ${_L('Group')}</option>
<option value="user" ${data?.role==='user'?'selected':''}>${_L('Users')} ${_L('Group')}</option>
<option value="admin" ${data?.role==='admin'?'selected':''}>${_L('Admin')} ${_L('Group')}</option>
</select>
<input type="text" name="username" placeholder="${_L('id')}" class="modal-input" value="${data?data.username:''}" ${isEdit?'readonly':'required'} style="margin-bottom:10px;">
<input type="password" name="password" placeholder="${isEdit?_L('leaveBlankToKeep'):_L('password')}" class="modal-input" style="margin-bottom:10px;" ${isEdit?'':'required'}>
<input type="text" name="name" placeholder="${_L('name')}" class="modal-input" value="${data?data.name:''}" style="margin-bottom:10px;">
<textarea name="memo" placeholder="${_L('memo')}" class="modal-input" style="height:100px;">${data?data.memo:''}</textarea>
</form>`;
const actions=`<button type="button" class="modal-btn danger half" onclick="document.getElementById('userModalForm').submit()">${_L('save')}</button>
<button type="button" class="modal-btn half" onclick="closeModal()">${_L('cancel')}</button>`;
openModal(title,body,actions);
}


/* Modal - Settings (Memo Alert) */
function openSMemoAlert(el){
const memo=el.dataset.memo||'',date=el.dataset.date||'';
openModal(_L('accountMemo'),`<div class="memo-alert"><p>${memo}</p></div>`,`<button class="modal-btn" onclick="closeModal()">${_L('ok')}</button>`);
}


/* Modal - ESC Close */
document.addEventListener('keydown',e=>{if(e.key==='Escape'){closeModal();}});
document.addEventListener('DOMContentLoaded',function(){document.querySelectorAll('.help-text').forEach(el=>{el.style.cursor='help';el.addEventListener('click',function(e){e.stopPropagation();const key=this.dataset.help;modalHelp(_L(key));});});});


/* Modal - EXPORT (GLOBAL) */
window.openModal=openModal;
window.closeModal=closeModal;
window.openSearchDialog=openSearchDialog;
window.openNewFolderDialog=openNewFolderDialog;
window.createNewFolder=createNewFolder;
window.openDeleteDialog=openDeleteDialog;
window.openUnreadDialog=openUnreadDialog;
window.openResendDialog=openResendDialog;
window.openCancelScheduleDialog=openCancelScheduleDialog;
window.openMemoAlert=openMemoAlert;
window.openCMemoAlert=openCMemoAlert;
window.openSMemoAlert=openSMemoAlert;
window.openMemoDialog=openMemoDialog;
window.saveMemo=saveMemo;
window.confirmDeleteMemo=confirmDeleteMemo;
window.openMoveDialog=openMoveDialog;
window.confirmMove=confirmMove;
window.openRenameFolderDialog=openRenameFolderDialog;
window.confirmRenameFolder=confirmRenameFolder;
window.modalConfirm=modalConfirm;
window.modalAlert=modalAlert;
window.openContactModal=openContactModal;
window.openContactCategoryDialog=openContactCategoryDialog;
window.openContactDeleteDialog=openContactDeleteDialog;
