<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
include '../include/config.php';

$error = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $pin = trim($_POST['pin']);
    
    $stmt = $conn->prepare("SELECT patient_id, first_name, last_name, email, portal_active, login_pin FROM patients WHERE (patient_id LIKE CONCAT(?, '%') OR login_pin = ?) AND portal_active = 1 LIMIT 1");
    $stmt->bind_param("ss", $pin, $pin);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 1) {
        $user = $result->fetch_assoc();
        
        $_SESSION['patient_id'] = $user['patient_id'];
        $_SESSION['patient_name'] = $user['first_name'] . ' ' . $user['last_name'];
        $_SESSION['patient_email'] = $user['email'];
        
        header("Location: dashboard.php");
        exit();
    } else {
        $error = "Invalid PIN. Please enter the 4-digit PIN from your hospital card.";
    }
    $stmt->close();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
    <title>Private Patient Login - UHD</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css">
    <style>
        body {
            background: linear-gradient(135deg, #0a3d2f 0%, #064e3b 100%);
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        
        .login-container {
            max-width: 450px;
            width: 100%;
        }
        
        .login-card {
            background: rgba(255, 255, 255, 0.98);
            border-radius: 30px;
            box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.3);
            overflow: hidden;
        }
        
        .card-header {
            background: linear-gradient(135deg, #0f6b4c, #064e3b);
            color: white;
            text-align: center;
            padding: 35px 20px;
        }
        
        .card-header i {
            font-size: 4rem;
            margin-bottom: 15px;
        }
        
        .card-header h2 {
            font-weight: 800;
            margin-bottom: 5px;
        }
        
        .card-body {
            padding: 35px;
        }
        
        .pin-input {
            width: 100%;
            text-align: center;
            font-size: 2rem;
            letter-spacing: 10px;
            font-weight: bold;
            padding: 15px;
            border: 2px solid #e0e0e0;
            border-radius: 15px;
            font-family: monospace;
        }
        
        .pin-input:focus {
            border-color: #0f6b4c;
            outline: none;
        }
        
        .keypad {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 12px;
            margin-top: 25px;
        }
        
        .keypad-btn {
            background: #f0f2f5;
            border: none;
            padding: 18px;
            font-size: 1.5rem;
            font-weight: bold;
            border-radius: 20px;
            transition: all 0.2s;
            cursor: pointer;
        }
        
        .keypad-btn:active {
            transform: scale(0.95);
        }
        
        .keypad-btn.clear {
            background: #dc3545;
            color: white;
        }
        
        .keypad-btn.clear:active {
            background: #c82333;
        }
        
        .keypad-btn.enter {
            background: #0f6b4c;
            color: white;
        }
        
        .btn-login {
            background: #0f6b4c;
            color: white;
            border: none;
            border-radius: 50px;
            padding: 14px;
            font-weight: bold;
            width: 100%;
            margin-top: 20px;
        }
        
        .btn-login:hover {
            background: #0a523b;
        }
        
        .error-alert {
            background: #f8d7da;
            color: #721c24;
            border-radius: 15px;
            padding: 12px;
            margin-bottom: 20px;
            text-align: center;
        }
        
        .forgot-link {
            text-align: center;
            margin-top: 20px;
        }
        
        .forgot-link a {
            color: #0f6b4c;
            text-decoration: none;
            font-size: 0.85rem;
        }
        
        @media (max-width: 768px) {
            .card-body {
                padding: 25px;
            }
            .pin-input {
                font-size: 1.5rem;
                letter-spacing: 5px;
            }
            .keypad-btn {
                padding: 15px;
                font-size: 1.2rem;
            }
        }
    </style>
</head>
<body>
<div class="login-container">
    <div class="login-card">
        <div class="card-header">
            <i class="fas fa-lock"></i>
            <h2>Private Patient Portal</h2>
            <p>Enter your 4-digit PIN to access your health records</p>
        </div>
        <div class="card-body">
            <?php if($error): ?>
                <div class="error-alert">
                    <i class="fas fa-exclamation-triangle me-2"></i> <?= htmlspecialchars($error) ?>
                </div>
            <?php endif; ?>
            
            <form method="POST" id="pinForm">
                <input type="password" name="pin" id="pinInput" class="pin-input" maxlength="4" pattern="[0-9]{4}" inputmode="numeric" autofocus required placeholder="●●●●">
                
                <div class="keypad">
                    <button type="button" class="keypad-btn" data-num="1">1</button>
                    <button type="button" class="keypad-btn" data-num="2">2</button>
                    <button type="button" class="keypad-btn" data-num="3">3</button>
                    <button type="button" class="keypad-btn" data-num="4">4</button>
                    <button type="button" class="keypad-btn" data-num="5">5</button>
                    <button type="button" class="keypad-btn" data-num="6">6</button>
                    <button type="button" class="keypad-btn" data-num="7">7</button>
                    <button type="button" class="keypad-btn" data-num="8">8</button>
                    <button type="button" class="keypad-btn" data-num="9">9</button>
                    <button type="button" class="keypad-btn clear" id="clearBtn">C</button>
                    <button type="button" class="keypad-btn" data-num="0">0</button>
                    <button type="button" class="keypad-btn enter" id="enterBtn">✓</button>
                </div>
            </form>
            
            <div class="forgot-link">
                <a href="pin_login.php"><i class="fas fa-qrcode"></i> Scan QR code instead</a>
                &nbsp;|&nbsp;
                <a href="login.php"><i class="fas fa-envelope"></i> Email login</a>
            </div>
        </div>
    </div>
</div>

<script>
    const pinInput = document.getElementById('pinInput');
    const pinForm = document.getElementById('pinForm');
    
    // Add numbers to PIN input
    document.querySelectorAll('.keypad-btn[data-num]').forEach(btn => {
        btn.addEventListener('click', function() {
            let currentVal = pinInput.value;
            if (currentVal.length < 4) {
                pinInput.value = currentVal + this.getAttribute('data-num');
            }
            if (pinInput.value.length === 4) {
                pinForm.submit();
            }
        });
    });
    
    // Clear button
    document.getElementById('clearBtn').addEventListener('click', function() {
        pinInput.value = '';
    });
    
    // Enter button
    document.getElementById('enterBtn').addEventListener('click', function() {
        if (pinInput.value.length === 4) {
            pinForm.submit();
        }
    });
    
    // Restrict manual input to numbers only
    pinInput.addEventListener('input', function(e) {
        this.value = this.value.replace(/[^0-9]/g, '').slice(0, 4);
    });
    
    // Focus on page load
    pinInput.focus();
</script>
</body>
</html>