<?php
if (session_status() === PHP_SESSION_NONE) session_start();
if (!isset($_SESSION['user_id'])) { header('Location: ../index.php'); exit; }
require_once '../config.php';
require_once '../includes/canteen_helpers.php';
canteen_require_active();
canteen_require_role(['admin', 'headteacher']);

$settings = canteen_get_settings();
if (empty($settings['fingerprint_enabled'])) {
    header('Location: settings.php?tab=hardware&error=fingerprint_disabled');
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Fingerprint Enrollment — EduTrack</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <link rel="stylesheet" href="../css/style.css">
    <style>
        .student-card { border: 2px solid #e9ecef; border-radius: 12px; padding: 1.25rem; }
        .student-card.selected { border-color: #0d6efd; background: #f0f6ff; }
        .student-photo { width: 80px; height: 80px; border-radius: 50%; object-fit: cover; }
        #enrollStatus {
            border-radius: 12px; padding: 1.5rem; text-align: center; display: none;
        }
        #enrollStatus.success { background: #d1e7dd; color: #0a3622; }
        #enrollStatus.error   { background: #f8d7da; color: #58151c; }
        #enrollStatus.working { background: #fff3cd; color: #664d03; }
    </style>
</head>
<body>
<div class="wrapper">
    <nav id="sidebar" class="sidebar">
        <?php echo buildSidebar('canteen/enroll_fingerprint.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">
                <div class="dropdown">
                    <button class="btn btn-link dropdown-toggle" type="button" data-bs-toggle="dropdown">
                        <i class="fas fa-user-circle me-2"></i><?php echo htmlspecialchars((string)($_SESSION['full_name'] ?? '')); ?>
                    </button>
                    <ul class="dropdown-menu dropdown-menu-end">
                        <li><a class="dropdown-item" href="../dashboard.php"><i class="fas fa-home me-2"></i>Dashboard</a></li>
                    </ul>
                </div>
            </div>
        </header>
        <main class="content">
            <div class="content-header">
                <h2><i class="fas fa-fingerprint me-2"></i>Fingerprint Enrollment</h2>
                <p class="text-muted">Enroll a student's fingerprint for canteen access.</p>
            </div>

            <div class="row justify-content-center">
                <div class="col-lg-7">

                    <!-- Privacy notice (cannot be dismissed) -->
                    <div class="alert alert-warning border-warning mb-4" role="alert">
                        <h6 class="alert-heading fw-bold"><i class="fas fa-shield-alt me-2"></i>Biometric Data Notice</h6>
                        <ul class="mb-0 small">
                            <li>Fingerprint data is stored <strong>only in your school's database</strong>.</li>
                            <li>No biometric data is transmitted to ORIC Network or any external service.</li>
                            <li>Your school must obtain <strong>parent/guardian consent</strong> before enrollment.</li>
                            <li>Students may decline — QR code is always their alternative.</li>
                            <li>Complies with Ghana's Data Protection Act 2012 (Act 843).</li>
                        </ul>
                    </div>

                    <!-- Step 1: Search student -->
                    <div class="card mb-3" id="stepSearch">
                        <div class="card-header fw-semibold">Step 1 — Find Student</div>
                        <div class="card-body">
                            <div class="input-group">
                                <input type="text" id="studentSearch" class="form-control"
                                       placeholder="Name or student ID…" autocomplete="off">
                                <button class="btn btn-primary" id="btnSearch">
                                    <i class="fas fa-search"></i>
                                </button>
                            </div>
                            <div id="searchResults" class="mt-3"></div>
                        </div>
                    </div>

                    <!-- Step 2: Confirm student + consent -->
                    <div class="card mb-3 d-none" id="stepConfirm">
                        <div class="card-header fw-semibold">Step 2 — Confirm &amp; Consent</div>
                        <div class="card-body">
                            <div class="student-card selected d-flex align-items-center gap-3 mb-3" id="selectedCard">
                                <img id="selPhoto" src="" alt="" class="student-photo">
                                <div>
                                    <div class="fw-bold fs-5" id="selName"></div>
                                    <div class="text-muted" id="selClass"></div>
                                    <div class="text-muted small" id="selCode"></div>
                                    <span id="fpAlreadyEnrolled" class="badge bg-success d-none mt-1">
                                        <i class="fas fa-check me-1"></i>Fingerprint already enrolled
                                    </span>
                                </div>
                            </div>
                            <div class="form-check mb-3">
                                <input class="form-check-input" type="checkbox" id="consentCheck">
                                <label class="form-check-label small" for="consentCheck">
                                    I confirm that the parent/guardian of this student has given consent
                                    for biometric enrollment in accordance with Ghana's Data Protection Act 2012.
                                </label>
                            </div>
                            <button class="btn btn-primary" id="btnProceedEnroll" disabled>
                                <i class="fas fa-fingerprint me-2"></i>Proceed to Fingerprint Scan
                            </button>
                            <button class="btn btn-outline-secondary ms-2" id="btnReselect">
                                <i class="fas fa-times me-1"></i>Choose Different Student
                            </button>
                        </div>
                    </div>

                    <!-- Step 3: Scan fingerprint -->
                    <div class="card mb-3 d-none" id="stepScan">
                        <div class="card-header fw-semibold">Step 3 — Scan Fingerprint</div>
                        <div class="card-body text-center py-4">
                            <i class="fas fa-fingerprint fa-5x text-primary mb-3"></i>
                            <p class="mb-2">Place your finger on the scanner and follow the browser prompt.</p>
                            <p class="text-muted small mb-3">Chrome / Edge will display a security dialog. Choose your fingerprint scanner.</p>
                            <button class="btn btn-lg btn-success" id="btnStartScan">
                                <i class="fas fa-play me-2"></i>Start Fingerprint Scan
                            </button>
                            <button class="btn btn-outline-secondary ms-2" id="btnCancelScan">Cancel</button>
                        </div>
                    </div>

                    <!-- Status -->
                    <div id="enrollStatus" class="mb-3">
                        <i id="statusIcon" class="fa-4x mb-3"></i>
                        <h5 id="statusTitle"></h5>
                        <p id="statusMsg" class="mb-3"></p>
                        <button class="btn btn-primary d-none" id="btnEnrollAnother">
                            <i class="fas fa-plus me-1"></i>Enroll Another Student
                        </button>
                    </div>

                </div>
            </div>
        </main>
    </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.2/js/bootstrap.bundle.min.js"></script>
<script>
'use strict';
(function () {

let selectedStudent = null;

// ── Student search ─────────────────────────────────────────────────────────
document.getElementById('btnSearch').addEventListener('click', doSearch);
document.getElementById('studentSearch').addEventListener('keydown', e => {
    if (e.key === 'Enter') doSearch();
});

function doSearch() {
    const q = document.getElementById('studentSearch').value.trim();
    if (!q) return;
    const resultsEl = document.getElementById('searchResults');
    resultsEl.innerHTML = '<div class="text-muted small"><i class="fas fa-circle-notch fa-spin me-1"></i>Searching…</div>';

    const fd = new FormData();
    fd.append('q', q);
    fd.append('limit', '8');

    fetch('../ajax/canteen_student_search.php', { method: 'POST', body: fd })
        .then(r => r.json())
        .then(data => {
            if (!data.success || !data.students.length) {
                resultsEl.innerHTML = '<p class="text-muted small">No students found.</p>';
                return;
            }
            resultsEl.innerHTML = data.students.map(s => `
                <div class="student-card d-flex align-items-center gap-3 mb-2 cursor-pointer"
                     style="cursor:pointer"
                     data-id="${s.id}" data-name="${escHtml(s.name)}" data-class="${escHtml(s.class_name)}"
                     data-code="${escHtml(s.student_code)}" data-photo="${escHtml(s.photo_url)}"
                     data-fp="${s.has_fingerprint ? '1' : '0'}">
                    <img src="${s.photo_url || '../assets/img/no-photo.png'}" class="student-photo" alt="">
                    <div>
                        <div class="fw-semibold">${escHtml(s.name)}</div>
                        <div class="text-muted small">${escHtml(s.class_name)} · ID: ${escHtml(s.student_code)}</div>
                        ${s.has_fingerprint ? '<span class="badge bg-success">Fingerprint enrolled</span>' : ''}
                    </div>
                </div>
            `).join('');
            resultsEl.querySelectorAll('.student-card').forEach(card => {
                card.addEventListener('click', () => selectStudent(card.dataset));
            });
        })
        .catch(() => {
            resultsEl.innerHTML = '<p class="text-danger small">Search failed. Please try again.</p>';
        });
}

function selectStudent(data) {
    selectedStudent = { id: parseInt(data.id), name: data.name, class_name: data.class, code: data.code, photo: data.photo };

    document.getElementById('selPhoto').src = data.photo || '../assets/img/no-photo.png';
    document.getElementById('selName').textContent  = data.name;
    document.getElementById('selClass').textContent = data.class;
    document.getElementById('selCode').textContent  = 'ID: ' + data.code;

    const fpBadge = document.getElementById('fpAlreadyEnrolled');
    fpBadge.classList.toggle('d-none', data.fp !== '1');

    document.getElementById('consentCheck').checked = false;
    document.getElementById('btnProceedEnroll').disabled = true;

    document.getElementById('stepSearch').querySelector('.card-body').style.display = 'none';
    document.getElementById('stepConfirm').classList.remove('d-none');
    document.getElementById('stepScan').classList.add('d-none');
}

document.getElementById('consentCheck').addEventListener('change', function () {
    document.getElementById('btnProceedEnroll').disabled = !this.checked;
});

document.getElementById('btnProceedEnroll').addEventListener('click', function () {
    document.getElementById('stepConfirm').classList.add('d-none');
    document.getElementById('stepScan').classList.remove('d-none');
});

document.getElementById('btnReselect').addEventListener('click', function () {
    selectedStudent = null;
    document.getElementById('stepConfirm').classList.add('d-none');
    document.getElementById('stepSearch').querySelector('.card-body').style.removeProperty('display');
    document.getElementById('searchResults').innerHTML = '';
    document.getElementById('studentSearch').value = '';
    document.getElementById('studentSearch').focus();
});

document.getElementById('btnCancelScan').addEventListener('click', function () {
    document.getElementById('stepScan').classList.add('d-none');
    document.getElementById('stepConfirm').classList.remove('d-none');
});

// ── Fingerprint enrollment ─────────────────────────────────────────────────
document.getElementById('btnStartScan').addEventListener('click', async function () {
    if (!selectedStudent) return;
    this.disabled = true;
    this.innerHTML = '<i class="fas fa-circle-notch fa-spin me-2"></i>Waiting for scanner…';

    // 1. Get fresh challenge
    let challenge;
    try {
        const resp = await fetch('../ajax/canteen_webauthn_challenge.php', { method: 'POST', credentials: 'same-origin' });
        const data = await resp.json();
        if (!data.success) throw new Error(data.message);
        challenge = data.challenge;
    } catch (err) {
        showStatus('error', 'fas fa-times-circle text-danger', 'Failed to get challenge', err.message);
        this.disabled = false;
        this.innerHTML = '<i class="fas fa-play me-2"></i>Start Fingerprint Scan';
        return;
    }

    // 2. Encode student ID as user ID bytes
    const enc = new TextEncoder();
    const userId = new Uint8Array(8);
    new DataView(userId.buffer).setUint32(0, selectedStudent.id, false);

    // 3. navigator.credentials.create()
    let credential;
    try {
        credential = await navigator.credentials.create({
            publicKey: {
                rp: { name: document.title, id: window.location.hostname },
                user: {
                    id: userId,
                    name: 'student_' + selectedStudent.id,
                    displayName: selectedStudent.name,
                },
                challenge: b64uDecode(challenge),
                pubKeyCredParams: [
                    { type: 'public-key', alg: -7  },  // ES256
                    { type: 'public-key', alg: -257 }, // RS256
                ],
                authenticatorSelection: {
                    authenticatorAttachment: 'cross-platform',
                    userVerification: 'required',
                    residentKey: 'discouraged',
                },
                timeout: 60000,
                attestation: 'none',
            }
        });
    } catch (err) {
        const msg = err.name === 'NotAllowedError'
            ? 'Scan was cancelled or timed out. Please try again.'
            : err.message;
        showStatus('error', 'fas fa-times-circle text-danger', 'Scan failed', msg);
        this.disabled = false;
        this.innerHTML = '<i class="fas fa-play me-2"></i>Retry Fingerprint Scan';
        return;
    }

    // 4. Extract public key (SPKI DER) using getPublicKey()
    let publicKeyB64 = '';
    if (credential.response.getPublicKey) {
        const pkDer = credential.response.getPublicKey();
        if (pkDer) {
            publicKeyB64 = btoa(String.fromCharCode(...new Uint8Array(pkDer)));
        }
    }

    if (!publicKeyB64) {
        showStatus('error', 'fas fa-times-circle text-danger', 'Enrollment failed',
            'Could not extract public key. Please use Chrome 90+ or Edge 90+.');
        this.disabled = false;
        this.innerHTML = '<i class="fas fa-play me-2"></i>Retry Fingerprint Scan';
        return;
    }

    // 5. POST to server
    const credId = b64uEncode(credential.rawId);
    const clientDataB64u = b64uEncode(credential.response.clientDataJSON);

    const fd = new FormData();
    fd.append('student_id',       selectedStudent.id);
    fd.append('credential_id',    credId);
    fd.append('public_key',       publicKeyB64);
    fd.append('client_data_json', clientDataB64u);

    try {
        const resp = await fetch('../ajax/canteen_webauthn_enroll.php', {
            method: 'POST', credentials: 'same-origin', body: fd
        });
        const data = await resp.json();
        if (data.success) {
            showStatus('success', 'fas fa-check-circle text-success', 'Fingerprint Enrolled!', data.message, true);
        } else {
            showStatus('error', 'fas fa-times-circle text-danger', 'Enrollment failed', data.message);
            this.disabled = false;
            this.innerHTML = '<i class="fas fa-play me-2"></i>Retry Fingerprint Scan';
        }
    } catch {
        showStatus('error', 'fas fa-times-circle text-danger', 'Network error', 'Please try again.');
        this.disabled = false;
        this.innerHTML = '<i class="fas fa-play me-2"></i>Retry Fingerprint Scan';
    }
});

function showStatus(type, iconClass, title, msg, showAnother = false) {
    const el = document.getElementById('enrollStatus');
    el.className = type;
    el.style.display = 'block';
    document.getElementById('statusIcon').className = iconClass + ' fa-4x mb-3';
    document.getElementById('statusTitle').textContent = title;
    document.getElementById('statusMsg').textContent   = msg;
    document.getElementById('btnEnrollAnother').classList.toggle('d-none', !showAnother);
    document.getElementById('stepScan').classList.add('d-none');
    document.getElementById('stepConfirm').classList.add('d-none');
}

document.getElementById('btnEnrollAnother').addEventListener('click', function () {
    selectedStudent = null;
    document.getElementById('enrollStatus').style.display = 'none';
    document.getElementById('stepSearch').querySelector('.card-body').style.removeProperty('display');
    document.getElementById('stepConfirm').classList.add('d-none');
    document.getElementById('stepScan').classList.add('d-none');
    document.getElementById('searchResults').innerHTML = '';
    document.getElementById('studentSearch').value = '';
    document.getElementById('studentSearch').focus();
});

// ── Helpers ────────────────────────────────────────────────────────────────
function b64uDecode(str) {
    const b64 = str.replace(/-/g, '+').replace(/_/g, '/') + '=='.slice(0, (4 - str.length % 4) % 4);
    const bin = atob(b64);
    return Uint8Array.from(bin, c => c.charCodeAt(0));
}

function b64uEncode(buf) {
    const bytes = new Uint8Array(buf instanceof ArrayBuffer ? buf : buf.buffer || buf);
    let bin = '';
    bytes.forEach(b => { bin += String.fromCharCode(b); });
    return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
}

function escHtml(s) {
    return String(s).replace(/[&<>"']/g,
        c => ({ '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;' })[c]);
}

})();
</script>
</body>
</html>
