<?php
/**
 * Canteen Scanner PIN Login
 * Accessible without a full EduTrack login — canteen staff only need the 4-digit PIN.
 * Valid EduTrack role sessions bypass this page entirely (redirected from scanner.php).
 */
if (session_status() === PHP_SESSION_NONE) session_start();
require_once '../config.php';
require_once '../includes/canteen_helpers.php';

canteen_require_active();

// Already authenticated (EduTrack session or PIN session)
if (!empty($_SESSION['user_id']) || !empty($_SESSION['canteen_staff_authenticated'])) {
    header('Location: scanner.php');
    exit;
}

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $pin = trim((string)($_POST['pin'] ?? ''));

    if ($pin === '' || !preg_match('/^\d{4,8}$/', $pin)) {
        $error = 'Enter a valid 4-digit PIN.';
    } else {
        $conn     = getDBConnection();
        $settings = canteen_get_settings();
        $hash     = $settings['scanner_pin_hash'] ?? '';

        if ($hash === '' || $hash === null) {
            $error = 'No PIN has been set. Ask an administrator to configure one in Canteen → Settings.';
        } elseif (!password_verify($pin, $hash)) {
            $error = 'Incorrect PIN. Try again.';
            // Log failed attempt
            logActivity($conn, 0, 'canteen_pin_fail', 'Failed PIN attempt from ' . ($_SERVER['REMOTE_ADDR'] ?? 'unknown'));
        } else {
            $_SESSION['canteen_staff_authenticated'] = true;
            $_SESSION['canteen_staff_auth_time']     = time();
            logActivity($conn, 0, 'canteen_pin_login', 'Canteen staff authenticated via PIN');
            header('Location: scanner.php');
            exit;
        }
        $conn->close();
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Canteen Scanner — Sign In</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">
    <style>
        * { box-sizing: border-box; }
        body {
            min-height: 100dvh;
            background: linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            font-family: 'Segoe UI', sans-serif;
            padding: 1rem;
        }
        .login-card {
            background: #fff;
            border-radius: 20px;
            padding: 2.5rem 2rem;
            width: 100%;
            max-width: 380px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.4);
            text-align: center;
        }
        .scanner-icon {
            width: 80px; height: 80px;
            background: linear-gradient(135deg, #4CAF50, #2e7d32);
            border-radius: 50%;
            display: flex; align-items: center; justify-content: center;
            margin: 0 auto 1.5rem;
            font-size: 2rem; color: #fff;
        }
        .pin-input {
            letter-spacing: 0.5em;
            font-size: 2rem;
            text-align: center;
            font-weight: 700;
            border: 2px solid #e0e0e0;
            border-radius: 12px;
            padding: 0.75rem;
            width: 100%;
            transition: border-color 0.2s;
        }
        .pin-input:focus { border-color: #4CAF50; outline: none; box-shadow: 0 0 0 3px rgba(76,175,80,.2); }
        .btn-unlock {
            background: linear-gradient(135deg, #4CAF50, #2e7d32);
            border: none; color: #fff;
            padding: 0.85rem 2rem;
            font-size: 1.1rem; font-weight: 600;
            border-radius: 12px; width: 100%;
            transition: opacity 0.2s;
        }
        .btn-unlock:hover { opacity: 0.9; color: #fff; }
        .numpad { display: grid; grid-template-columns: repeat(3, 1fr); gap: 0.75rem; margin-top: 1.5rem; }
        .numpad-btn {
            background: #f5f5f5; border: none;
            border-radius: 12px; padding: 1rem;
            font-size: 1.4rem; font-weight: 600; color: #333;
            transition: background 0.15s;
            cursor: pointer;
        }
        .numpad-btn:active, .numpad-btn:hover { background: #e0f2e9; }
        .numpad-btn.del { font-size: 1.1rem; color: #e53935; }
    </style>
</head>
<body>
<div class="login-card">
    <div class="scanner-icon"><i class="fas fa-utensils"></i></div>
    <h4 class="fw-bold mb-1">Canteen Scanner</h4>
    <p class="text-muted mb-3">Enter your 4-digit PIN to begin</p>

    <?php if ($error): ?>
        <div class="alert alert-danger py-2 mb-3" role="alert"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <form method="post" id="pinForm" autocomplete="off">
        <input type="password" name="pin" id="pinInput" class="pin-input mb-3"
               maxlength="8" pattern="\d{4,8}" inputmode="numeric"
               placeholder="• • • •" required autofocus>
        <button type="submit" class="btn-unlock">
            <i class="fas fa-unlock me-2"></i>Unlock Scanner
        </button>
    </form>

    <!-- On-screen numpad for touch devices -->
    <div class="numpad" id="numpad" aria-label="Numeric keypad">
        <?php for ($d = 1; $d <= 9; $d++): ?>
        <button type="button" class="numpad-btn" data-digit="<?= $d ?>"><?= $d ?></button>
        <?php endfor; ?>
        <button type="button" class="numpad-btn del" data-action="clear">CLR</button>
        <button type="button" class="numpad-btn" data-digit="0">0</button>
        <button type="button" class="numpad-btn del" data-action="del"><i class="fas fa-backspace"></i></button>
    </div>

    <p class="mt-3 mb-0 text-muted small">
        <i class="fas fa-shield-alt me-1"></i>
        Staff with an EduTrack account can <a href="../index.php">sign in</a> instead.
    </p>
</div>

<script>
(function () {
    const input  = document.getElementById('pinInput');
    const numpad = document.getElementById('numpad');

    numpad.addEventListener('click', function (e) {
        const btn = e.target.closest('[data-digit],[data-action]');
        if (!btn) return;
        if (btn.dataset.digit !== undefined) {
            if (input.value.length < 8) input.value += btn.dataset.digit;
        } else if (btn.dataset.action === 'del') {
            input.value = input.value.slice(0, -1);
        } else if (btn.dataset.action === 'clear') {
            input.value = '';
        }
        input.focus();
    });

    // Auto-submit when 4 digits entered via numpad
    input.addEventListener('input', function () {
        if (input.value.length >= 4 && /^\d+$/.test(input.value)) {
            // Brief pause so user sees all digits, then submit
            setTimeout(() => document.getElementById('pinForm').submit(), 300);
        }
    });
})();
</script>
</body>
</html>
