<?php
/** Biometric Attendance management (biometric_attendance add-on). */
if (session_status() === PHP_SESSION_NONE) session_start();
if (!isset($_SESSION['user_id'])) { header('Location: ../index.php'); exit; }

require_once '../config.php';
requireModule('biometric_attendance');
require_once __DIR__ . '/../includes/biometric_lib.php';

$role = $_SESSION['role'] ?? '';
if (!biometric_can_manage($role)) { header('Location: ../dashboard.php?error=no_access'); exit; }

$conn = getDBConnection();
biometric_ensure_tables($conn);
$base = defined('BASE_URL') ? rtrim(BASE_URL, '/') : '';
$endpointUrl = $base . '/attendance/device_endpoint.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Biometric Attendance — EduTrack</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="../css/style.css">
</head>
<body>
<div class="wrapper">
    <nav id="sidebar" class="sidebar"><?php echo buildSidebar('biometric/index.php'); ?></nav>
    <div class="main-content">
        <header class="header">
            <button class="btn-toggle" id="sidebarToggle"><i class="fas fa-bars"></i></button>
            <div class="header-right"><span class="text-muted"><i class="fas fa-user-circle me-2"></i><?php echo htmlspecialchars((string)($_SESSION['full_name'] ?? '')); ?></span></div>
        </header>
        <main class="content">
            <div class="content-header d-flex align-items-center gap-3">
                <div style="background:linear-gradient(135deg,#4338ca,#3730a3);border-radius:12px;width:44px;height:44px;display:flex;align-items:center;justify-content:center;">
                    <i class="fas fa-fingerprint text-white fa-lg"></i>
                </div>
                <div><h2 class="mb-0">Biometric Attendance</h2><p class="text-muted mb-0 small">Fingerprint &amp; facial clock-in — devices and browser kiosk</p></div>
                <a href="kiosk.php" target="_blank" class="btn btn-primary ms-auto"><i class="fas fa-camera me-1"></i>Open Face Kiosk</a>
            </div>

            <ul class="nav nav-tabs mb-3">
                <li class="nav-item"><a class="nav-link active" href="#" onclick="showTab('devices');return false;" id="tabDevicesBtn">Devices</a></li>
                <li class="nav-item"><a class="nav-link" href="#" onclick="showTab('enroll');return false;" id="tabEnrollBtn">Enrollment</a></li>
                <li class="nav-item"><a class="nav-link" href="#" onclick="showTab('punches');return false;" id="tabPunchesBtn">Recent Punches</a></li>
                <li class="nav-item"><a class="nav-link" href="#" onclick="showTab('help');return false;" id="tabHelpBtn">Setup &amp; Devices</a></li>
            </ul>

            <!-- Devices -->
            <div id="tabDevices">
                <div class="d-flex justify-content-between mb-2"><h5>Registered Devices</h5>
                    <button class="btn btn-success btn-sm" onclick="editDevice()"><i class="fas fa-plus me-1"></i>Add Device</button></div>
                <div class="card"><div class="table-responsive"><table class="table table-hover mb-0">
                    <thead class="table-light"><tr><th>Name</th><th>Serial</th><th>Type</th><th>Connection</th><th>Location</th><th>Last seen</th><th></th></tr></thead>
                    <tbody id="devBody"><tr><td colspan="7" class="text-center text-muted py-3">Loading…</td></tr></tbody>
                </table></div></div>
            </div>

            <!-- Enrollment -->
            <div id="tabEnroll" style="display:none">
                <div class="row g-3">
                    <div class="col-lg-5"><div class="card"><div class="card-body">
                        <h6><i class="fas fa-fingerprint me-1"></i>Enrol Fingerprint mapping</h6>
                        <p class="small text-muted">Map a person to the user ID stored on the terminal.</p>
                        <input id="fpSearch" class="form-control form-control-sm mb-1" placeholder="Search student/staff">
                        <select id="fpResults" class="form-select form-select-sm mb-2" size="4"></select>
                        <input id="fpDevUser" class="form-control form-control-sm mb-2" placeholder="Device user ID (e.g. 101)">
                        <button class="btn btn-primary btn-sm w-100" onclick="enrollFp()">Enrol fingerprint mapping</button>
                        <div class="small mt-2" id="fpMsg"></div>
                    </div></div></div>
                    <div class="col-lg-7"><div class="card"><div class="card-body">
                        <h6><i class="fas fa-list me-1"></i>Enrollments</h6>
                        <div class="table-responsive"><table class="table table-sm">
                            <thead class="table-light"><tr><th>Person</th><th>Method</th><th>Device user</th><th></th></tr></thead>
                            <tbody id="enrBody"></tbody></table></div>
                        <p class="small text-muted mb-0">For facial enrolment use the <a href="kiosk.php?mode=enroll" target="_blank">Face Kiosk (enrol mode)</a>.</p>
                    </div></div></div>
                </div>
            </div>

            <!-- Punches -->
            <div id="tabPunches" style="display:none">
                <div class="card"><div class="table-responsive"><table class="table table-sm table-hover mb-0">
                    <thead class="table-light"><tr><th>Time</th><th>Device</th><th>Method</th><th>Dir</th><th>Person</th><th>Attendance</th><th></th></tr></thead>
                    <tbody id="punchBody"><tr><td colspan="7" class="text-center text-muted py-3">Loading…</td></tr></tbody>
                </table></div></div>
            </div>

            <!-- Help -->
            <div id="tabHelp" style="display:none">
                <div class="card mb-3"><div class="card-body">
                    <h6><i class="fas fa-network-wired me-1"></i>Connect a ZKTeco terminal (wired or Wi-Fi)</h6>
                    <ol class="small mb-0">
                        <li>On the device: <b>Menu → Comm → Cloud Server / ADMS</b>.</li>
                        <li>Set <b>Server Address</b> to this host and <b>Server Path</b> to <code><?php echo htmlspecialchars($endpointUrl); ?></code></li>
                        <li>Choose Ethernet (wired) or Wi-Fi (wireless) under <b>Comm → Network</b>.</li>
                        <li>Register the device here (Devices tab) using its <b>Serial Number</b> (Menu → System Info).</li>
                        <li>Enrol each person on the device, then map their device user ID here (Enrollment tab).</li>
                    </ol>
                </div></div>
                <div class="card"><div class="card-body">
                    <h6><i class="fas fa-microchip me-1"></i>Recommended devices</h6>
                    <div class="table-responsive"><table class="table table-sm">
                        <thead class="table-light"><tr><th>Model</th><th>Capability</th><th>Connectivity</th><th>Notes</th></tr></thead>
                        <tbody id="recBody"></tbody></table></div>
                </div></div>
            </div>
        </main>
    </div>
</div>

<!-- Device modal -->
<div class="modal fade" id="devModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content">
    <form id="devForm"><div class="modal-header"><h5 class="modal-title" id="devTitle">Add Device</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
    <div class="modal-body"><input type="hidden" id="dev_id">
        <div class="row g-2">
            <div class="col-12"><label class="form-label small">Name</label><input id="dev_name" class="form-control" required></div>
            <div class="col-6"><label class="form-label small">Serial number</label><input id="dev_serial" class="form-control" required></div>
            <div class="col-6"><label class="form-label small">Type</label><select id="dev_type" class="form-select">
                <option value="fingerprint">Fingerprint</option><option value="face">Face</option><option value="hybrid">Face + Fingerprint</option></select></div>
            <div class="col-6"><label class="form-label small">Connection</label><select id="dev_conn" class="form-select">
                <option value="wired">Wired (Ethernet/USB)</option><option value="wireless">Wireless (Wi-Fi)</option></select></div>
            <div class="col-6"><label class="form-label small">Direction</label><select id="dev_dir" class="form-select">
                <option value="auto">Auto (device decides)</option><option value="in">Clock-in</option><option value="out">Clock-out</option></select></div>
            <div class="col-6"><label class="form-label small">IP address</label><input id="dev_ip" class="form-control"></div>
            <div class="col-6"><label class="form-label small">Location</label><input id="dev_loc" class="form-control"></div>
            <div class="col-12"><div class="form-check"><input class="form-check-input" type="checkbox" id="dev_active" checked><label class="form-check-label small" for="dev_active">Active</label></div></div>
        </div>
    </div>
    <div class="modal-footer"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
        <button class="btn btn-success" type="submit">Save</button></div></form>
</div></div></div>

<!-- Assign punch modal -->
<div class="modal fade" id="assignModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content">
    <div class="modal-header"><h5 class="modal-title">Assign punch to person</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
    <div class="modal-body">
        <input type="hidden" id="assign_punch_id">
        <input id="asSearch" class="form-control form-control-sm mb-1" placeholder="Search student/staff">
        <select id="asResults" class="form-select form-select-sm" size="5"></select>
    </div>
    <div class="modal-footer"><button class="btn btn-primary" onclick="doAssign()">Assign</button></div>
</div></div></div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="../js/main.js"></script>
<script>
function esc(s){const d=document.createElement('div');d.textContent=s==null?'':s;return d.innerHTML;}
let fpPerson=null, asPerson=null;
function showTab(t){
  ['devices','enroll','punches','help'].forEach(x=>{
    document.getElementById('tab'+x.charAt(0).toUpperCase()+x.slice(1)).style.display = (x===t)?'':'none';
    document.getElementById('tab'+x.charAt(0).toUpperCase()+x.slice(1)+'Btn').classList.toggle('active',x===t);
  });
  if(t==='devices')loadDevices(); if(t==='enroll'){loadEnroll();} if(t==='punches')loadPunches();
}

function loadDevices(){
  fetch('ajax/api.php?action=devices_list').then(r=>r.json()).then(d=>{
    const b=document.getElementById('devBody');
    b.innerHTML=d.data.length?d.data.map(x=>`<tr>
      <td>${esc(x.name)} ${x.active==1?'':'<span class="badge bg-secondary">off</span>'}</td>
      <td><code>${esc(x.serial_number)}</code></td><td>${esc(x.device_type)}</td>
      <td>${x.connection==='wireless'?'<i class="fas fa-wifi"></i> Wi-Fi':'<i class="fas fa-network-wired"></i> Wired'}</td>
      <td>${esc(x.location||'—')}</td><td class="small text-muted">${esc(x.last_seen||'never')}</td>
      <td><button class="btn btn-sm btn-outline-primary" onclick='editDevice(${JSON.stringify(x)})'><i class="fas fa-pen"></i></button>
          <button class="btn btn-sm btn-outline-danger" onclick="delDevice(${x.id})"><i class="fas fa-trash"></i></button></td>
    </tr>`).join(''):'<tr><td colspan="7" class="text-center text-muted py-3">No devices yet.</td></tr>';
    document.getElementById('recBody').innerHTML=(d.recommended||[]).map(r=>`<tr><td><b>${esc(r[0])}</b></td><td>${esc(r[1])}</td><td>${esc(r[2])}</td><td class="small">${esc(r[3])}</td></tr>`).join('');
  });
}
function editDevice(x){
  document.getElementById('devForm').reset();
  document.getElementById('dev_id').value=x?x.id:0;
  document.getElementById('devTitle').textContent=x?'Edit Device':'Add Device';
  if(x){dev_name.value=x.name;dev_serial.value=x.serial_number;dev_type.value=x.device_type;dev_conn.value=x.connection;dev_dir.value=x.direction;dev_ip.value=x.ip_address||'';dev_loc.value=x.location||'';dev_active.checked=(x.active==1);}
  new bootstrap.Modal(document.getElementById('devModal')).show();
}
document.getElementById('devForm').addEventListener('submit',function(e){
  e.preventDefault();
  const fd=new FormData();fd.append('action','save_device');fd.append('id',dev_id.value);
  fd.append('name',dev_name.value);fd.append('serial_number',dev_serial.value);fd.append('device_type',dev_type.value);
  fd.append('connection',dev_conn.value);fd.append('direction',dev_dir.value);fd.append('ip_address',dev_ip.value);
  fd.append('location',dev_loc.value);if(dev_active.checked)fd.append('active','1');
  fetch('ajax/api.php',{method:'POST',body:fd}).then(r=>r.json()).then(d=>{if(d.success){bootstrap.Modal.getInstance(document.getElementById('devModal')).hide();loadDevices();}else alert(d.message);});
});
function delDevice(id){ if(!confirm('Remove this device?'))return;
  const fd=new FormData();fd.append('action','delete_device');fd.append('id',id);
  fetch('ajax/api.php',{method:'POST',body:fd}).then(r=>r.json()).then(()=>loadDevices()); }

// Enrollment
document.getElementById('fpSearch').addEventListener('keyup',e=>{ if(e.key==='Enter'){searchP('fp');} });
function searchP(which){
  const q=document.getElementById(which+'Search').value;
  fetch(`ajax/api.php?action=search_persons&q=${encodeURIComponent(q)}`).then(r=>r.json()).then(d=>{
    document.getElementById(which+'Results').innerHTML=d.data.map(p=>`<option value="${p.type}:${p.id}" data-label="${esc(p.label)}">${esc(p.label)}</option>`).join('');
  });
}
document.getElementById('fpResults').addEventListener('change',function(){const o=this.selectedOptions[0];fpPerson=o?{v:o.value,label:o.dataset.label}:null;});
function enrollFp(){
  if(!fpPerson){alert('Select a person.');return;}
  const [type,id]=fpPerson.v.split(':');
  const fd=new FormData();fd.append('action','enroll_fingerprint');fd.append('person_type',type);fd.append('person_id',id);
  fd.append('person_name',fpPerson.label);fd.append('device_user_id',document.getElementById('fpDevUser').value);
  fetch('ajax/api.php',{method:'POST',body:fd}).then(r=>r.json()).then(d=>{document.getElementById('fpMsg').innerHTML=d.success?'<span class="text-success">'+esc(d.message)+'</span>':'<span class="text-danger">'+esc(d.message)+'</span>';if(d.success)loadEnroll();});
}
function loadEnroll(){
  fetch('ajax/api.php?action=enrollments_list').then(r=>r.json()).then(d=>{
    document.getElementById('enrBody').innerHTML=d.data.length?d.data.map(e=>`<tr>
      <td>${esc(e.person_name||(e.person_type+' #'+e.person_id))}</td><td>${esc(e.method)}</td><td>${esc(e.device_user_id||'—')}</td>
      <td><button class="btn btn-sm btn-outline-danger py-0" onclick="delEnroll(${e.id})"><i class="fas fa-times"></i></button></td>
    </tr>`).join(''):'<tr><td colspan="4" class="text-center text-muted">No enrollments.</td></tr>';
  });
}
function delEnroll(id){ const fd=new FormData();fd.append('action','delete_enrollment');fd.append('id',id);
  fetch('ajax/api.php',{method:'POST',body:fd}).then(r=>r.json()).then(()=>loadEnroll()); }

// Punches
function loadPunches(){
  fetch('ajax/api.php?action=punches_list').then(r=>r.json()).then(d=>{
    document.getElementById('punchBody').innerHTML=d.data.length?d.data.map(p=>`<tr>
      <td class="small">${esc(p.punch_time)}</td><td>${esc(p.device_name||p.source)}</td><td>${esc(p.method)}</td><td>${esc(p.direction)}</td>
      <td>${p.matched==1?esc(p.person_type+' #'+p.person_id):'<span class="text-warning">unmatched</span>'}</td>
      <td>${p.attendance_written==1?'<i class="fas fa-check text-success"></i>':'—'}</td>
      <td>${p.matched==1?'':`<button class="btn btn-sm btn-outline-primary py-0" onclick="openAssign(${p.id})">Assign</button>`}</td>
    </tr>`).join(''):'<tr><td colspan="7" class="text-center text-muted py-3">No punches yet.</td></tr>';
  });
}
function openAssign(id){document.getElementById('assign_punch_id').value=id;asPerson=null;document.getElementById('asResults').innerHTML='';new bootstrap.Modal(document.getElementById('assignModal')).show();}
document.getElementById('asSearch').addEventListener('keyup',e=>{ if(e.key==='Enter'){searchP('as');} });
document.getElementById('asResults').addEventListener('change',function(){const o=this.selectedOptions[0];asPerson=o?o.value:null;});
function doAssign(){
  if(!asPerson){alert('Select a person.');return;}
  const [type,id]=asPerson.split(':');
  const fd=new FormData();fd.append('action','assign_punch');fd.append('punch_id',document.getElementById('assign_punch_id').value);
  fd.append('person_type',type);fd.append('person_id',id);
  fetch('ajax/api.php',{method:'POST',body:fd}).then(r=>r.json()).then(d=>{alert(d.message);if(d.success){bootstrap.Modal.getInstance(document.getElementById('assignModal')).hide();loadPunches();}});
}
loadDevices();
</script>
</body>
</html>
