<?php
// pages/attendance_kiosk_manual.php
requireRole('any');

// Fetch Members
$members = $pdo->query("SELECT id, full_name, unit FROM members WHERE status='Available' ORDER BY full_name ASC")->fetchAll();
?>
<div class="kiosk-container">
    <div class="kiosk-header">
        <h1>Manual Sign In/Out</h1>
        <p>If you cannot find your name on the main screen, use this form.</p>
    </div>

    <!-- Message Display -->
    <div id="message" class="kiosk-message" style="display:none; margin-bottom: 20px;"></div>

    <div class="card" style="max-width: 500px; margin: 0 auto; text-align: left;">
        <form id="manualForm">
            
            <div class="form-group">
                <label>Date</label>
                <input type="date" id="date_input" class="form-control" style="font-size: 1.2rem; padding: 10px;" required>
            </div>

            <div class="form-group">
                <label>Time</label>
                <input type="time" id="time_input" class="form-control" style="font-size: 1.2rem; padding: 10px;" required>
            </div>

            <div class="form-group">
                <label>Member Name</label>
                <input list="members_datalist" id="member_input" class="form-control" placeholder="Start typing name..." style="font-size: 1.2rem; padding: 10px;" required autocomplete="off">
                <datalist id="members_datalist">
                    <?php foreach($members as $m): ?>
                    <option data-value="<?php echo $m['id']; ?>" value="<?php echo htmlspecialchars($m['full_name']); ?>">
                        <?php echo htmlspecialchars($m['unit'] ? $m['unit'] : 'Member'); ?>
                    </option>
                    <?php endforeach; ?>
                </datalist>
                <input type="hidden" id="member_id_hidden">
            </div>
            
            <div style="display: flex; gap: 10px; margin-top: 20px;">
                <button type="button" class="btn btn-action btn-signin" onclick="submitManual('in')" style="flex: 1;">Sign In</button>
                <button type="button" class="btn btn-action btn-signout" onclick="submitManual('out')" style="flex: 1;">Sign Out</button>
            </div>
        </form>
    </div>
    
    <div style="margin-top: 30px;">
        <a href="index.php?page=attendance_kiosk" class="btn" style="background-color: #555;">&laquo; Back to Main Kiosk</a>
    </div>
    
    <div id="timerDisplay" style="margin-top: 20px; color: #777; font-size: 0.9rem;">Auto-reverting in 5:00</div>
</div>

<style>
    body.attendance_kiosk_manual-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;
    }
    .btn-action {
        font-size: 1.1rem;
        padding: 15px;
    }
    .btn-signin { background-color: var(--success-color); border:none; color:white; cursor:pointer; border-radius:4px;}
    .btn-signout { background-color: var(--danger-color); border:none; color:white; cursor:pointer; border-radius:4px;}
    
    .kiosk-message {
        padding: 15px;
        border-radius: 8px;
        font-weight: bold;
    }
</style>

<script>
    // Set Default Date & Time
    const now = new Date();
    const timeString = now.toTimeString().substring(0, 5);
    const dateString = now.toISOString().split('T')[0];
    
    document.getElementById('date_input').value = dateString;
    document.getElementById('time_input').value = timeString;

    // Member Input Logic (Handle Datalist ID)
    const memberInput = document.getElementById('member_input');
    const memberHidden = document.getElementById('member_id_hidden');
    const memberOptions = document.getElementById('members_datalist').options;

    memberInput.addEventListener('input', function() {
        const val = this.value;
        // Find option with this value
        let foundId = '';
        for (let i = 0; i < memberOptions.length; i++) {
            if (memberOptions[i].value === val) {
                foundId = memberOptions[i].getAttribute('data-value');
                break;
            }
        }
        memberHidden.value = foundId;
    });

    // Idle Timer (5 mins = 300 seconds)
    let idleTime = 300;
    const timerDisplay = document.getElementById('timerDisplay');
    
    const idleInterval = setInterval(() => {
        idleTime--;
        
        let mins = Math.floor(idleTime / 60);
        let secs = idleTime % 60;
        timerDisplay.innerText = `Auto-reverting in ${mins}:${secs < 10 ? '0'+secs : secs}`;
        
        if (idleTime <= 0) {
            window.location.href = 'index.php?page=attendance_kiosk';
        }
    }, 1000);

    // Reset timer on interaction
    document.addEventListener('mousemove', resetTimer);
    document.addEventListener('keypress', resetTimer);
    document.addEventListener('touchstart', resetTimer);

    function resetTimer() {
        idleTime = 300;
    }

    async function submitManual(type) {
        const memberId = memberHidden.value;
        const dateVal = document.getElementById('date_input').value;
        const timeVal = document.getElementById('time_input').value; // HH:mm
        const messageDiv = document.getElementById('message');
        
        if (!memberId) {
            alert("Please select a valid member from the list.");
            return;
        }
        if (!dateVal || !timeVal) {
             alert("Please select date and time.");
             return;
        }
        
        // Construct DateTime string
        const customDateTime = `${dateVal} ${timeVal}:00`;

        try {
            const res = await fetch('api/attendance_action.php', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: `member_id=${memberId}&type=${type}&custom_time=${customDateTime}`
            });
            
            // Handle HTTP Errors
            if (!res.ok) {
                const text = await res.text();
                // Try to parse if json
                try {
                    const errJson = JSON.parse(text);
                    throw new Error(errJson.message || "Server Error " + res.status);
                } catch(e) {
                    throw new Error("Server Error: " + res.status + " " + text.substring(0, 50));
                }
            }

            const result = await res.json();
            
            messageDiv.innerText = result.message;
            messageDiv.style.display = 'block';
            messageDiv.style.backgroundColor = result.success ? 'var(--success-color)' : 'var(--danger-color)';
            
            if (result.success) {
                // Reset form?
                memberInput.value = '';
                memberHidden.value = '';
                // Reset Time to now
                const n = new Date();
                document.getElementById('time_input').value = n.toTimeString().substring(0, 5);
            }
        } catch (error) {
            console.error(error);
            messageDiv.innerText = "Error: " + error.message;
            messageDiv.style.display = 'block';
            messageDiv.style.backgroundColor = 'var(--danger-color)';
        }
    }
</script>
