<?php
include 'db.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$error = '';

// Handle login
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $pin = trim($_POST['pin']);
    
    if (empty($pin)) {
        $error = 'Please enter PIN';
    } else {
        // Check all active order takers to find matching PIN/password
        $stmt = $conn->prepare("SELECT id, name, employee_id, password, is_active FROM order_takers WHERE is_active = 1");
        $stmt->execute();
        $result = $stmt->get_result();
        
        $login_successful = false;
        $matched_order_taker = null;
        
        while ($order_taker = $result->fetch_assoc()) {
            // Check if entered PIN matches the password (for new numeric PINs) or verify against hashed password
            if ($pin === $order_taker['password'] || password_verify($pin, $order_taker['password'])) {
                $login_successful = true;
                $matched_order_taker = $order_taker;
                break;
            }
        }
        
        if ($login_successful && $matched_order_taker) {
            // Login successful
            $_SESSION['tablet_order_taker_id'] = $matched_order_taker['id'];
            $_SESSION['tablet_order_taker_name'] = $matched_order_taker['name'];
            $_SESSION['tablet_order_taker_employee_id'] = $matched_order_taker['employee_id'];
            $_SESSION['tablet_logged_in'] = true;
            
            // Redirect to tablet order system
            header('Location: tablet_order.php');
            exit;
        } else {
            $error = 'Invalid PIN';
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <title>Tablet Login - ITRPOS</title>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    
    <style>
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        .login-container {
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            padding: 2.5rem;
            width: 100%;
            max-width: 450px;
        }
        
        .login-header {
            text-align: center;
            margin-bottom: 2rem;
        }
        
        .login-header i {
            font-size: 3.5rem;
            color: #667eea;
            margin-bottom: 1rem;
        }
        
        .login-header h3 {
            color: #333;
            margin-bottom: 0.5rem;
            font-weight: 600;
        }
        
        .pin-display {
            background: #f8f9fa;
            border: 3px solid #e9ecef;
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 2rem;
            text-align: center;
            min-height: 60px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 2rem;
            letter-spacing: 0.5rem;
            font-weight: bold;
            color: #333;
        }
        
        .pin-display:focus-within {
            border-color: #667eea;
            box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
        }
        
        .numpad {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 15px;
            margin-bottom: 1.5rem;
        }
        
        .numpad-btn {
            background: #f8f9fa;
            border: 2px solid #e9ecef;
            border-radius: 15px;
            padding: 20px;
            font-size: 1.8rem;
            font-weight: 600;
            color: #333;
            cursor: pointer;
            transition: all 0.2s ease;
            min-height: 70px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .numpad-btn:hover {
            background: #e9ecef;
            border-color: #667eea;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        }
        
        .numpad-btn:active {
            transform: translateY(0);
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }
        
        .numpad-btn.zero {
            grid-column: 2;
        }
        
        .action-buttons {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
            margin-bottom: 1.5rem;
        }
        
        .action-btn {
            background: #dc3545;
            color: white;
            border: none;
            border-radius: 15px;
            padding: 15px 20px;
            font-size: 1.1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }
        
        .action-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(220, 53, 69, 0.4);
        }
        
        .action-btn.backspace {
            background: #ffc107;
            color: #333;
        }
        
        .action-btn.backspace:hover {
            box-shadow: 0 5px 15px rgba(255, 193, 7, 0.4);
        }
        
        .btn-login {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
            border-radius: 15px;
            padding: 18px;
            font-size: 1.2rem;
            font-weight: 600;
            width: 100%;
            color: white;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .btn-login:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(102, 126, 234, 0.4);
        }
        
        .btn-login:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }
        
        .alert {
            border-radius: 15px;
            border: none;
            padding: 15px 20px;
            margin-bottom: 1.5rem;
        }
        
        .alert-danger {
            background: #f8d7da;
            color: #721c24;
        }
        
        .hidden-input {
            position: absolute;
            left: -9999px;
            opacity: 0;
        }
        
        @media (max-width: 480px) {
            .login-container {
                margin: 20px;
                padding: 2rem;
            }
            
            .numpad-btn {
                padding: 15px;
                font-size: 1.5rem;
                min-height: 60px;
            }
            
            .pin-display {
                font-size: 1.5rem;
                padding: 15px;
                min-height: 50px;
            }
        }
    </style>
</head>
<body>
    <div class="login-container">
        <div class="login-header">
            <i class="fas fa-tablet-alt"></i>
            <h3>Tablet Login</h3>
            <p class="text-muted">Enter your PIN to access the order system</p>
        </div>
        
        <?php if ($error): ?>
            <div class="alert alert-danger" role="alert">
                <i class="fas fa-exclamation-triangle me-2"></i>
                <?= htmlspecialchars($error) ?>
            </div>
        <?php endif; ?>
        
        <form method="POST" id="pinForm">
            <!-- Hidden input for PIN -->
            <input type="text" name="pin" id="pinInput" class="hidden-input" autocomplete="off">
            
            <!-- PIN Display -->
            <div class="pin-display" id="pinDisplay">
                <span class="pin-dots"></span>
            </div>
            
            <!-- Numpad -->
            <div class="numpad">
                <button type="button" class="numpad-btn" data-number="1">1</button>
                <button type="button" class="numpad-btn" data-number="2">2</button>
                <button type="button" class="numpad-btn" data-number="3">3</button>
                <button type="button" class="numpad-btn" data-number="4">4</button>
                <button type="button" class="numpad-btn" data-number="5">5</button>
                <button type="button" class="numpad-btn" data-number="6">6</button>
                <button type="button" class="numpad-btn" data-number="7">7</button>
                <button type="button" class="numpad-btn" data-number="8">8</button>
                <button type="button" class="numpad-btn" data-number="9">9</button>
                <button type="button" class="numpad-btn zero" data-number="0">0</button>
            </div>
            
            <!-- Action Buttons -->
            <div class="action-buttons">
                <button type="button" class="action-btn backspace" id="backspaceBtn">
                    <i class="fas fa-backspace"></i>
                    Backspace
                </button>
                <button type="button" class="action-btn" id="clearBtn">
                    <i class="fas fa-trash"></i>
                    Clear
                </button>
            </div>
            
            <!-- Login Button -->
            <button type="submit" class="btn-login" id="loginBtn" disabled>
                <i class="fas fa-sign-in-alt me-2"></i>
                Login
            </button>
        </form>
        
        <div class="text-center mt-3">
            <small class="text-muted">
                <i class="fas fa-info-circle me-1"></i>
                Contact administrator for your PIN
            </small>
        </div>
    </div>
    
    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            let currentPin = '';
            const pinInput = document.getElementById('pinInput');
            const pinDisplay = document.getElementById('pinDisplay');
            const loginBtn = document.getElementById('loginBtn');
            const pinForm = document.getElementById('pinForm');
            
            // Update pin display
            function updatePinDisplay() {
                const dots = '●'.repeat(currentPin.length);
                const placeholder = currentPin.length === 0 ? 'Enter PIN' : '';
                pinDisplay.innerHTML = `<span class="pin-dots">${dots || placeholder}</span>`;
                pinInput.value = currentPin;
                
                // Enable/disable login button
                loginBtn.disabled = currentPin.length === 0;
            }
            
            // Handle numpad button clicks
            document.querySelectorAll('.numpad-btn').forEach(btn => {
                btn.addEventListener('click', function(e) {
                    e.preventDefault();
                    const number = this.getAttribute('data-number');
                    
                    // Limit PIN length to 10 digits
                    if (currentPin.length < 10) {
                        currentPin += number;
                        updatePinDisplay();
                        
                        // Add visual feedback
                        this.style.transform = 'scale(0.95)';
                        setTimeout(() => {
                            this.style.transform = '';
                        }, 100);
                    }
                });
            });
            
            // Handle backspace
            document.getElementById('backspaceBtn').addEventListener('click', function(e) {
                e.preventDefault();
                if (currentPin.length > 0) {
                    currentPin = currentPin.slice(0, -1);
                    updatePinDisplay();
                    
                    // Add visual feedback
                    this.style.transform = 'scale(0.95)';
                    setTimeout(() => {
                        this.style.transform = '';
                    }, 100);
                }
            });
            
            // Handle clear
            document.getElementById('clearBtn').addEventListener('click', function(e) {
                e.preventDefault();
                currentPin = '';
                updatePinDisplay();
                
                // Add visual feedback
                this.style.transform = 'scale(0.95)';
                setTimeout(() => {
                    this.style.transform = '';
                }, 100);
            });
            
            // Handle form submission
            pinForm.addEventListener('submit', function(e) {
                if (currentPin.length === 0) {
                    e.preventDefault();
                    return false;
                }
                
                // Add loading state
                loginBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Logging in...';
                loginBtn.disabled = true;
            });
            
            // Handle keyboard input (optional - for testing)
            document.addEventListener('keydown', function(e) {
                if (e.key >= '0' && e.key <= '9') {
                    e.preventDefault();
                    if (currentPin.length < 10) {
                        currentPin += e.key;
                        updatePinDisplay();
                    }
                } else if (e.key === 'Backspace') {
                    e.preventDefault();
                    if (currentPin.length > 0) {
                        currentPin = currentPin.slice(0, -1);
                        updatePinDisplay();
                    }
                } else if (e.key === 'Enter') {
                    e.preventDefault();
                    if (currentPin.length > 0) {
                        pinForm.submit();
                    }
                } else if (e.key === 'Escape') {
                    e.preventDefault();
                    currentPin = '';
                    updatePinDisplay();
                }
            });
            
            // Initialize display
            updatePinDisplay();
            
            // Prevent zoom on iOS
            document.addEventListener('touchstart', function(e) {
                if (e.touches.length > 1) {
                    e.preventDefault();
                }
            });
            
            // Prevent double-tap zoom
            let lastTouchEnd = 0;
            document.addEventListener('touchend', function(e) {
                const now = (new Date()).getTime();
                if (now - lastTouchEnd <= 300) {
                    e.preventDefault();
                }
                lastTouchEnd = now;
            }, false);
        });
    </script>
</body>
</html>
