<?php require_once __DIR__.'/layout/header.php'; ?>
<?php require_once __DIR__.'/layout/sidebar.php'; ?>

<style>

.main {
  margin-left: 200px;
  padding: 24px;
}

h1 {
  margin-top: 0;
}

.section {
  margin-top: 32px;
}

.section h2 {
  font-size: 16px;
  margin-bottom: 12px;
}

.box {
  background: #fff;
  padding: 16px;
  border-radius: 4px;
  box-shadow: 0 1px 2px rgba(0,0,0,0.05);
}

pre {
  background: #f9fafb;
  padding: 12px;
  border-radius: 4px;
  font-size: 13px;
  overflow-x: auto;
}

.loading {
  color: #6b7280;
}

.error {
  color: #b91c1c;
  background: #fee2e2;
  padding: 12px;
}

.success {
  color: #065f46;
  background: #d1fae5;
  padding: 12px;
}

input[type="file"] {
  margin-top: 12px;
}

button {
  margin-top: 12px;
  padding: 10px 18px;
  font-size: 14px;
  cursor: pointer;
  border-radius: 4px;
  border: none;
}

button.primary {
  background: #2563eb;
  color: white;
}

button.primary:disabled {
  background: #93c5fd;
  cursor: not-allowed;
}

</style>


<main class="main">

<h1>MD Templates</h1>


<div class="section">

<h2>Active Template</h2>

<div id="activeState" class="loading">Loading active template…</div>

<div id="activeBox" class="box" style="display:none">

<div style="margin-bottom:12px">

<button type="button" id="toggleRawJson" class="primary">
Show Raw Template JSON
</button>

</div>

<pre id="activeTemplateSummary"></pre>

<pre id="activeTemplateJson" style="display:none;margin-top:12px"></pre>

</div>

</div>



<div class="section">

<h2>Import New Template</h2>

<div class="box">

<p>
Upload both CSV files exported from Excel:
<br><strong>MD_Template_Questions.csv</strong>
<br><strong>MD_Template_Signatures.csv</strong>
</p>


<div style="margin-bottom:16px">

<button type="button" id="downloadQuestions" class="primary">
Download Questions CSV Template
</button>

<button type="button" id="downloadSignatures" class="primary" style="margin-left:8px">
Download Signatures CSV Template
</button>

</div>


<div style="margin-bottom:12px">

<label style="font-size:14px">

CSV delimiter:

<select id="csvDelimiter">
<option value="auto" selected>Auto-detect</option>
<option value=",">Comma (,)</option>
<option value=";">Semicolon (;)</option>
<option value="|">Pipe (|)</option>
<option value="\t">Tab</option>
</select>

</label>

</div>


<form id="uploadForm">

<label>
Questions CSV
<input type="file" id="questionsFile" name="questions" accept=".csv" required>
</label>

<br>

<label>
Signatures CSV
<input type="file" id="signaturesFile" name="signatures" accept=".csv" required>
</label>

<br>

<button type="submit" id="uploadBtn" class="primary" disabled>
Import & Activate
</button>

</form>

<div id="uploadResult" style="margin-top:12px"></div>

</div>

</div>

</main>



<script>

/* ================= CSRF ================= */

let CSRF_TOKEN = null

fetch('/auth/csrf_token.php',{credentials:'include'})
.then(r=>r.json())
.then(d=>CSRF_TOKEN=d.csrf_token)

function csrfFetch(url,options={}){

return fetch(url,{

...options,

credentials:'include',

headers:{
...(options.headers||{}),
'X-CSRF-Token':CSRF_TOKEN
}

})

}


/* ================= CSV DOWNLOAD ================= */

function downloadCsv(filename,content){

const blob=new Blob([content],{type:'text/csv;charset=utf-8;'})

const url=URL.createObjectURL(blob)

const a=document.createElement('a')

a.href=url
a.download=filename

document.body.appendChild(a)
a.click()

document.body.removeChild(a)
URL.revokeObjectURL(url)

}


document.addEventListener('DOMContentLoaded',()=>{

const qBtn=document.getElementById('downloadQuestions')
const sBtn=document.getElementById('downloadSignatures')

if(qBtn){

qBtn.addEventListener('click',()=>{

const d=getSelectedDelimiter()

const csv=[

[
'section',
'question_key',
'label',
'type',
'required',
'options',
'no_default',
'compliant_options',
'deviation_requires_comment',
'deviation_requires_photo',
'group_key',
'group_min_required',
'allow_deviation',
'allow_photo',
'required_if_question',
'required_if_value'
].join(d),

[
'Site',
'Level for Declaration',
'text',
'',
'',
'no',
'no',
'yes',
'Exact level of safe declaration for working place'
].join(d)

].join('\r\n')+'\r\n'

downloadCsv('MD_Template_Questions.csv',csv)

})

}


if(sBtn){

sBtn.addEventListener('click',()=>{

const d=getSelectedDelimiter()

const csv=[

['order','role','label','required','repeatable','phase'].join(d),
['1','miner','Miner Signature','1','0','draft'].join(d),
['2','assistant','Assistant Signature','1','0','draft'].join(d),
['3','team','Team Member','0','1','draft'].join(d),
['10','shiftboss','Shiftboss Approval','yes','post_submit'].join(d)

].join('\r\n')+'\r\n'

downloadCsv('MD_Template_Signatures.csv',csv)

})

}

})


function detectDelimiter(text){

const firstLine=text.split(/\r?\n/)[0]||''

const candidates=[',',';','|','\t']

let best={delim:',',count:0}

candidates.forEach(d=>{

const count=firstLine.split(d).length-1

if(count>best.count){

best={delim:d,count}

}

})

return best.count>0?best.delim:','

}


function getSelectedDelimiter(){

const sel=document.getElementById('csvDelimiter')

if(!sel) return ','

return sel.value==='auto'?',':sel.value

}


function readFirstLine(file){

return new Promise((resolve,reject)=>{

const reader=new FileReader()

reader.onload=()=>resolve(reader.result||'')
reader.onerror=reject

reader.readAsText(file.slice(0,2048))

})

}


/* ================= LOAD ACTIVE TEMPLATE ================= */

function loadActiveTemplate(){

const state=document.getElementById('activeState')
const box=document.getElementById('activeBox')

state.className='loading'
state.innerText='Loading active template…'
state.style.display='block'

box.style.display='none'

fetch('/md/templates/get_active_template.php',{credentials:'include'})

.then(r=>{

if(r.status===204) return null
if(!r.ok) throw new Error()

return r.json()

})

.then(data=>{

if(!data){

state.innerText='No active template'
return

}

const meta=data.meta
const tpl=data.template

const sections=tpl.sections||[]
const signatures=tpl.signatures?.items||[]

const questionCount=sections.reduce((sum,s)=>sum+(s.questions?.length||0),0)

const summaryEl=document.getElementById('activeTemplateSummary')
const jsonEl=document.getElementById('activeTemplateJson')
const toggleBtn=document.getElementById('toggleRawJson')

summaryEl.innerText=

`Version: ${meta.version}
Imported: ${meta.created_at}
Sections: ${sections.length}
Questions: ${questionCount}
Signatures: ${signatures.length}`

jsonEl.innerText=JSON.stringify(tpl,null,2)
jsonEl.style.display='none'

toggleBtn.innerText='Show Raw Template JSON'

toggleBtn.onclick=()=>{

const isVisible=jsonEl.style.display==='block'

jsonEl.style.display=isVisible?'none':'block'

toggleBtn.innerText=isVisible
?'Show Raw Template JSON'
:'Hide Raw Template JSON'

}

state.style.display='none'
box.style.display='block'

})

.catch(()=>{

state.className='error'
state.innerText='Failed to load active template.'

})

}


/* ================= UPLOAD ================= */

const questionsInput=document.getElementById('questionsFile')
const signaturesInput=document.getElementById('signaturesFile')
const uploadBtn=document.getElementById('uploadBtn')
const resultBox=document.getElementById('uploadResult')

function updateButtonState(){

uploadBtn.disabled=!(questionsInput.files.length && signaturesInput.files.length)

}

questionsInput.addEventListener('change',updateButtonState)
signaturesInput.addEventListener('change',updateButtonState)


document.getElementById('uploadForm').addEventListener('submit',async e=>{

e.preventDefault()

uploadBtn.disabled=true
resultBox.innerHTML=''

const delimiterSelect=document.getElementById('csvDelimiter')

let delimiter=delimiterSelect.value

if(delimiter==='auto'){

const qText=await readFirstLine(questionsInput.files[0])
const sText=await readFirstLine(signaturesInput.files[0])

const qDelim=detectDelimiter(qText)
const sDelim=detectDelimiter(sText)

delimiter=qDelim||sDelim||','

}

const formData=new FormData()

formData.append('questions',questionsInput.files[0])
formData.append('signatures',signaturesInput.files[0])
formData.append('delimiter',delimiter)


csrfFetch('/admin/md_templates_upload.php',{

method:'POST',
body:formData

})

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

.then(res=>{

if(!res.success) throw new Error(res.error||'Import failed')

resultBox.className='success'
resultBox.innerText='Template imported and activated successfully.'

questionsInput.value=''
signaturesInput.value=''

uploadBtn.disabled=true

loadActiveTemplate()

})

.catch(err=>{

resultBox.className='error'
resultBox.innerText=err.message

uploadBtn.disabled=false

})

})


document.addEventListener('DOMContentLoaded',()=>{

loadActiveTemplate()

})

</script>


<?php require_once __DIR__.'/layout/footer.php'; ?>