<?php
session_start();

// Check if user is logged in
if (!isset($_SESSION['user_id']) || $_SESSION['auth_step'] !== 'pin') {
    header('Location: login.php');
    exit;
}

// Fetch user profile data
$user_profile = null;
try {
    require_once 'config/database.php';
    $database = new Database();
    $db = $database->getConnection();
    
    $stmt = $db->prepare("SELECT first_name, last_name, profile_picture FROM users WHERE id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $user_profile = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    error_log("Error fetching user profile: " . $e->getMessage());
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PIN Verification - Ocean Bank Cooperation</title>
    
    <!-- CSS Dependencies -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/boxicons@2.0.7/css/boxicons.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&display=swap" rel="stylesheet">

    <style>
        :root {
            --primary-color: #2563eb;
            --secondary-color: #1e40af;
            --background-color: #f0f2f5;
        }

        body {
            font-family: 'Poppins', sans-serif;
            background: linear-gradient(135deg, #2563eb, #1e40af);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 1rem;
        }

        .pin-container {
            background: white;
            border-radius: 20px;
            padding: 1.5rem; /* Reduced padding */
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            max-width: 360px;
            width: 100%;
        }

        /* Compact profile section */
        .profile-section {
            display: flex;
            align-items: center;
            margin-bottom: 0.75rem; /* Reduced margin */
        }
        
        .profile-image {
            width: 50px; /* Smaller image */
            height: 50px;
            border-radius: 50%;
            object-fit: cover;
            border: 2px solid var(--primary-color);
            margin-right: 1rem;
        }
        
        .profile-text {
            text-align: left;
        }
        
        .profile-text h5 {
            margin-bottom: 0;
            font-size: 1rem;
        }
        
        .profile-text p {
            margin-bottom: 0;
            font-size: 0.8rem;
            color: #6b7280;
        }

        /* Compact timer */
        .timer-container {
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 0.75rem; /* Reduced margin */
        }

        .timer {
            width: 40px; /* Smaller timer */
            height: 40px;
            position: relative;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 0.5rem;
        }

        .timer-circle {
            width: 100%;
            height: 100%;
            border-radius: 50%;
            border: 2px solid #e2e8f0;
            border-top-color: var(--primary-color);
            animation: spin 1s linear infinite;
        }

        .timer-count {
            position: absolute;
            font-size: 0.9rem;
            font-weight: 600;
            color: var(--primary-color);
        }

        /* Compact PIN display */
        .pin-display {
            background: #f8fafc;
            border-radius: 10px;
            padding: 0.75rem; /* Reduced padding */
            text-align: center;
            margin-bottom: 0.75rem; /* Reduced margin */
            display: flex;
            justify-content: center;
            gap: 0.75rem; /* Reduced gap */
        }

        .pin-dot {
            width: 10px; /* Smaller dots */
            height: 10px;
            border-radius: 50%;
            background: #e2e8f0;
            transition: all 0.3s ease;
        }

        .pin-dot.filled {
            background: var(--primary-color);
            transform: scale(1.2);
        }

        /* Compact keyboard */
        .virtual-keyboard {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 6px; /* Reduced gap */
            margin-bottom: 0.75rem; /* Reduced margin */
        }

        .key {
            background: white;
            border: 1px solid #e2e8f0; /* Thinner border */
            border-radius: 8px; /* Smaller radius */
            padding: 0.5rem; /* Reduced padding */
            font-size: 1.25rem; /* Smaller font */
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            user-select: none;
            height: 45px; /* Reduced height */
        }

        .key:hover {
            background: #f8fafc;
            transform: translateY(-1px); /* Smaller transform */
            border-color: var(--primary-color);
        }

        .key:active {
            transform: translateY(0);
            background: #e2e8f0;
        }

        /* Compact action buttons */
        .action-buttons {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 8px; /* Reduced gap */
        }

        .action-buttons button {
            padding: 0.5rem; /* Reduced padding */
            border-radius: 8px; /* Smaller radius */
            border: none;
            font-weight: 500;
            font-size: 0.9rem; /* Smaller font */
            transition: all 0.3s ease;
        }

        .btn-clear {
            background: #f1f5f9;
            color: #64748b;
        }

        .btn-clear:hover {
            background: #e2e8f0;
        }

        .btn-submit {
            background: var(--primary-color);
            color: white;
        }

        .btn-submit:hover {
            background: var(--secondary-color);
        }

        .btn-submit:disabled {
            opacity: 0.7;
            cursor: not-allowed;
        }

        /* Compact footer links */
        .footer-links {
            display: flex;
            justify-content: space-between;
            margin-top: 0.75rem; /* Reduced margin */
            font-size: 0.75rem; /* Smaller font */
        }
        
        .footer-links a {
            color: var(--primary-color);
            text-decoration: none;
        }
        
        .footer-links a:hover {
            text-decoration: underline;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }
    </style>
</head>
<body>

<div class="pin-container">
    <!-- Compact profile section with horizontal layout -->
    <?php if ($user_profile): ?>
    <div class="profile-section">
        <img src="<?php echo !empty($user_profile['profile_picture']) ? 'uploads/profiles/' . htmlspecialchars($user_profile['profile_picture']) : 'customer/assets/images/default-avatar.png'; ?>" 
             alt="Profile" class="profile-image">
        <div class="profile-text">
            <h5>Welcome, <?php echo htmlspecialchars($user_profile['first_name']); ?>!</h5>
            <p>Enter your 4-digit PIN</p>
        </div>
    </div>
    <?php else: ?>
    <div class="text-center mb-2">
        <h5>Enter Your PIN</h5>
        <p class="text-muted small">Please enter your 4-digit PIN</p>
    </div>
    <?php endif; ?>

    <!-- Compact timer with inline layout -->
    <div class="timer-container">
        <div class="timer">
            <div class="timer-circle"></div>
            <span class="timer-count">60</span>
        </div>
        <small class="text-muted">Time remaining</small>
    </div>

    <div class="pin-display">
        <div class="pin-dot"></div>
        <div class="pin-dot"></div>
        <div class="pin-dot"></div>
        <div class="pin-dot"></div>
    </div>

    <div class="virtual-keyboard" id="virtualKeyboard">
        <!-- Keys will be generated dynamically -->
    </div>

    <div class="action-buttons">
        <button class="btn-clear" onclick="clearPin()">Clear</button>
        <button class="btn-submit" onclick="submitPin()" id="submitButton" disabled>Submit</button>
    </div>
    
    <div class="footer-links">
        <a href="forgot-pin.php">Forgot PIN?</a>
        <a href="logout.php">Not you? Logout</a>
    </div>
</div>

<!-- Scripts -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
let currentPin = '';
const maxLength = 4;
let timeLeft = 60;
let timerId = null;

function startTimer() {
    const timerCount = document.querySelector('.timer-count');
    
    timerId = setInterval(() => {
        timeLeft--;
        timerCount.textContent = timeLeft;
        
        if (timeLeft <= 0) {
            clearInterval(timerId);
            handleTimeout();
        }
    }, 1000);
}

function handleTimeout() {
    clearPin();
    generateKeyboard();
    Swal.fire({
        icon: 'error',
        title: 'Time Expired',
        text: 'Please try again',
        confirmButtonColor: '#2563eb'
    }).then(() => {
        timeLeft = 60;
        startTimer();
    });
}

function generateKeyboard() {
    const keyboard = document.getElementById('virtualKeyboard');
    const numbers = Array.from({length: 10}, (_, i) => i);
    
    for (let i = numbers.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [numbers[i], numbers[j]] = [numbers[j], numbers[i]];
    }

    keyboard.innerHTML = '';
    
    numbers.forEach(num => {
        const key = document.createElement('div');
        key.className = 'key';
        key.textContent = num;
        key.onclick = () => addDigit(num);
        keyboard.appendChild(key);
    });
}

function addDigit(digit) {
    if (currentPin.length < maxLength) {
        currentPin += digit;
        updateDisplay();
        
        if (currentPin.length === maxLength) {
            document.getElementById('submitButton').disabled = false;
        }
    }
}

function updateDisplay() {
    const dots = document.querySelectorAll('.pin-dot');
    dots.forEach((dot, index) => {
        dot.classList.toggle('filled', index < currentPin.length);
    });
}

function clearPin() {
    currentPin = '';
    updateDisplay();
    document.getElementById('submitButton').disabled = true;
}

function submitPin() {
    if (currentPin.length !== maxLength) {
        Swal.fire({
            icon: 'error',
            title: 'Invalid PIN',
            text: 'Please enter a 4-digit PIN'
        });
        return;
    }

    clearInterval(timerId);

    fetch('verify_pin.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ pin: currentPin })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            window.location.href = 'customer/dashboard.php';
        } else {
            Swal.fire({
                icon: 'error',
                title: 'Invalid PIN',
                text: data.message || 'Please try again'
            });
            clearPin();
            generateKeyboard();
            timeLeft = 60;
            startTimer();
        }
    })
    .catch(error => {
        Swal.fire({
            icon: 'error',
            title: 'Error',
            text: 'An error occurred. Please try again.'
        });
        clearPin();
        generateKeyboard();
        timeLeft = 60;
        startTimer();
    });
}

// Initialize
document.addEventListener('DOMContentLoaded', () => {
    generateKeyboard();
    startTimer();
});

// Handle physical keyboard input
document.addEventListener('keydown', (e) => {
    if (e.key >= '0' && e.key <= '9') {
        addDigit(parseInt(e.key));
    } else if (e.key === 'Backspace') {
        clearPin();
    } else if (e.key === 'Enter') {
        submitPin();
    }
});
</script>

</body>
</html>
