<?php
// pages/attendance_kiosk.php
// No auth required? Or maybe a generic "kiosk" login? 
// User said "Mobile optimized for touch page". Usually runs on a tablet at entrance.
// We'll allow it without specific role but maybe require at least being logged in as any user (e.g. 'viewer' account for the kiosk tablet).
requireRole('any');

// Fetch all members for JS searching
$stmt = $pdo->query("SELECT id, full_name FROM members WHERE status='Available' ORDER BY full_name ASC");
$members = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<div class="kiosk-container">
    <div class="kiosk-header-actions">
        <a href="index.php?page=dashboard" class="btn btn-kiosk-exit">
            <i class="fas fa-arrow-left"></i> Exit Kiosk
        </a>
    </div>
    
    <div class="kiosk-clock" id="clock">00:00:00</div>
    <div class="kiosk-date" id="date">Loading Date...</div>
    
    <div class="kiosk-search-box">
        <input type="text" id="memberSearch" placeholder="Start typing your name..." autocomplete="off">
    </div>
    
    <div style="margin-top: 15px;">
        <a href="index.php?page=attendance_kiosk_manual" class="btn" style="background-color: #333; border: 1px solid #555; color: #aaa; font-size: 0.9rem;">
            <i class="fas fa-keyboard"></i> Manual Entry / Late Arrival
        </a>
    </div>
    
    <div id="searchResults" class="kiosk-results"></div>
    
    <div id="message" class="kiosk-message" style="display:none;"></div>
</div>

<style>
    @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;800&display=swap');
    
    body.attendance_kiosk-page {
        background-color: #000;
        color: #fff;
        display: flex;
        justify-content: center;
        align-items: center; 
        min-height: 100vh;
        margin: 0;
    }
    .kiosk-container {
        width: 100%;
        max-width: 600px;
        text-align: center;
        padding: 20px;
        position: relative;
    }
    .kiosk-clock {
        font-size: 8rem;
        font-weight: 800;
        margin-bottom: 0px;
        color: var(--primary-color);
        font-family: 'Poppins', sans-serif;
        letter-spacing: -2px;
        line-height: 1;
    }
    .kiosk-date {
        font-size: 2.2rem;
        color: #888;
        margin-bottom: 40px;
        font-family: 'Poppins', sans-serif;
        font-weight: 400;
    }
    .kiosk-header-actions {
        position: absolute;
        top: 20px;
        right: 20px;
    }
    .btn-kiosk-exit {
        background-color: #222;
        border: 1px solid #444;
        color: #888;
        font-size: 0.8rem;
        padding: 5px 12px;
    }
    
    @media (max-width: 600px) {
        .kiosk-clock { font-size: 5rem; }
        .kiosk-date { font-size: 1.4rem; }
        .kiosk-header-actions { position: static; margin-bottom: 20px; text-align: right; }
    }
    .kiosk-search-box input {
        width: 100%;
        padding: 20px;
        font-size: 1.5rem;
        border-radius: 10px;
        border: 2px solid #555;
        background: #222;
        color: #fff;
        text-align: center;
    }
    .kiosk-search-box input:focus {
        border-color: var(--accent-color);
        outline: none;
    }
    .kiosk-results {
        margin-top: 20px;
        display: flex;
        flex-direction: column;
        gap: 10px;
        max-height: 400px;
        overflow-y: auto;
    }
    .member-card {
        background: #333;
        padding: 15px;
        border-radius: 8px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        cursor: pointer;
        transition: transform 0.1s;
    }
    .member-card:active {
        transform: scale(0.98);
    }
    .member-name {
        font-size: 1.2rem;
        font-weight: bold;
    }
    .btn-action {
        padding: 10px 20px;
        border-radius: 5px;
        font-weight: bold;
        border: none;
        cursor: pointer;
    }
    .btn-signin { background-color: var(--success-color); color: white; }
    .btn-signout { background-color: var(--danger-color); color: white; }
    
    .kiosk-message {
        margin-top: 20px;
        padding: 20px;
        background: #444;
        border-radius: 8px;
        font-size: 1.2rem;
        animation: fadeIn 0.3s;
    }
    @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
</style>

<script>
const members = <?php echo json_encode($members); ?>;
let searchInput = document.getElementById('memberSearch');
let resultsDiv = document.getElementById('searchResults');
let messageDiv = document.getElementById('message');

// Clock
function updateClock() {
    const now = new Date();
    document.getElementById('clock').innerText = now.toLocaleTimeString();
    document.getElementById('date').innerText = now.toDateString();
}
setInterval(updateClock, 1000);
updateClock();

// Search Filter
searchInput.addEventListener('input', (e) => {
    const term = e.target.value.toLowerCase();
    resultsDiv.innerHTML = '';
    
    if (term.length < 2) return;
    
    const matches = members.filter(m => m.full_name.toLowerCase().includes(term));
    
    matches.slice(0, 5).forEach(m => { // Show top 5
        checkStatusAndRender(m);
    });
});

async function checkStatusAndRender(member) {
    // Check if member is signed in today
    const res = await fetch(`api/attendance_action.php?check_status=1&member_id=${member.id}`);
    const data = await res.json();
    
    const card = document.createElement('div');
    card.className = 'member-card';
    
    let btnHtml = '';
    if (data.signed_in) {
        btnHtml = `<button class="btn-action btn-signout" onclick="toggleAttendance(${member.id}, 'out')">Sign Out</button>`;
    } else {
        btnHtml = `<button class="btn-action btn-signin" onclick="toggleAttendance(${member.id}, 'in')">Sign In</button>`;
    }
    
    card.innerHTML = `<span class="member-name">${member.full_name}</span> ${btnHtml}`;
    resultsDiv.appendChild(card);
}

async function toggleAttendance(memberId, type) {
    const res = await fetch('api/attendance_action.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: `member_id=${memberId}&type=${type}`
    });
    const result = await res.json();
    
    if (result.success) {
        showMessage(result.message, 'success');
        searchInput.value = '';
        resultsDiv.innerHTML = '';
    } else {
        showMessage(result.message, 'error');
    }
}

function showMessage(msg, type) {
    messageDiv.innerText = msg;
    messageDiv.style.backgroundColor = type === 'success' ? 'var(--success-color)' : 'var(--danger-color)';
    messageDiv.style.display = 'block';
    
    setTimeout(() => {
        messageDiv.style.display = 'none';
    }, 3000);
}
</script>
