<?php

$pageName  = "Pincode";
include($_SERVER['DOCUMENT_ROOT']."/auth/header2.php");

if(@!$_SESSION['login']){
  header("Location:./login.php");
}
if(@$_SESSION['acct_no']){
  header("Location:./user/dashboard.php");
}
$viesConn="SELECT * FROM users WHERE acct_no = :acct_no";
$stmt = $conn->prepare($viesConn);

$stmt->execute([
  ':acct_no'=>$_SESSION['login']
]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);

$user_id = $row['id'];
$fullName = $row['firstname']." ".$row['lastname'];
$acct_no = $row['acct_no'];

if(isset($_POST['pincode_submit'])){
  $pincodeVerified = $_POST['input'];
  $old_otp = $row['acct_pin'];

  if(empty($pincodeVerified)){
     toast_alert('error','Enter Your Pincode');
  }elseif($pincodeVerified !== $old_otp){
       toast_alert('error','Invalid Pincode');
  }else{
       $_SESSION['acct_no'] = $acct_no;
       $_COOKIE['firstVisit'] = $acct_no;
      header("Location:./user/dashboard.php");
      exit;
  }
}
?>

<!doctype html>
<html lang="en">

<head>
    <title>PIN Verification - <?= $web_url ?></title>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="robots" content="index, follow">
    <meta name="apple-mobile-web-app-title" content="<?= $web_url ?>" />
    <meta name="application-name" content="<?= $web_url ?>" />
    <meta name="description" content="Swift and Secure Money Transfer to any bank account will become a breeze with <?= $web_url ?>." />
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
    <meta name="theme-color" content="#49786B">
    <link rel="shortcut icon" href="<?= $web_url ?>/admin/assets/images/favicon/<?= htmlspecialchars($page['favicon']) ?>" />
    
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    
    <!-- Lucide Icons -->
    <script src="https://unpkg.com/lucide@latest"></script>
    
    <!-- Fonts: Inter -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css" />
    
    <script>
    tailwind.config = {
        theme: {
            extend: {
                colors: {
                    primary: {
                        50:  '#f0f7f4',
                        100: '#d9ede3',
                        200: '#b3dbc7',
                        300: '#7fc29f',
                        400: '#4da576',
                        500: '#2d8659',
                        600: '#1f6b45',
                        700: '#195539',
                        800: '#15442e',
                        900: '#0d2a1c',
                    },
                    surface: {
                        100: '#FFFFFF',
                        200: '#F9F9F9',
                        300: '#DFE5E5',
                        400: '#BFC9C9',
                    },
                },
                fontFamily: {
                    sans: ['Inter', 'system-ui', 'sans-serif'],
                },
                boxShadow: {
                    'elegant': '0 8px 32px rgba(0, 0, 0, 0.12), 0 2px 8px rgba(0, 0, 0, 0.08)',
                },
                animation: {
                    'fade-in': 'fadeIn .4s ease-out',
                    'shake': 'shake 0.5s cubic-bezier(.36,.07,.19,.97) both',
                },
                keyframes: {
                    fadeIn: { 
                        '0%': { opacity: '0' }, 
                        '100%': { opacity: '1' } 
                    },
                    shake: {
                        '0%, 100%': { transform: 'translateX(0)' },
                        '10%, 30%, 50%, 70%, 90%': { transform: 'translateX(-10px)' },
                        '20%, 40%, 60%, 80%': { transform: 'translateX(10px)' },
                    }
                },
            }
        }
    }
    </script>
    
    <style>
    :root {
        --color-bg-base: #FFFFFF;
        --color-bg-surface: #F9F9F9;
        --color-bg-muted: #DFE5E5;
        --color-primary: #2d8659;
        --color-primary-dark: #1f6b45;
        --color-primary-light: #4da576;
        --color-text-primary: #0D1B23;
        --color-text-secondary: #4A4A4A;
        --color-text-muted: #7A7A7A;
        --color-text-inverse: #FFFFFF;
        --color-border: #E0E5E5;
        --color-border-dark: #C8D1D1;
        --color-status-success: #28A745;
        --color-status-warning: #EBBC46;
        --color-status-error: #D55672;
    }
    
    * { -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; }
    
    body {
        font-family: 'Inter', system-ui, sans-serif;
        background: #F9F9F9;
        min-height: 100vh;
        letter-spacing: -0.011em;
    }
    
    .auth-card {
        background: #FFFFFF;
        border: 1px solid var(--color-border);
        box-shadow: 0 8px 32px rgba(13, 27, 35, 0.06), 0 2px 8px rgba(13, 27, 35, 0.04);
    }
    
    .auth-input {
        background: #FFFFFF;
        border: 1px solid var(--color-border-dark);
        color: var(--color-text-primary);
        transition: border-color 0.2s ease;
    }
    
    .auth-input:focus {
        background: #FFFFFF;
        border-color: var(--color-primary);
        box-shadow: 0 0 0 2px rgba(73, 120, 107, 0.12);
        outline: none;
    }
    
    .auth-button {
        background: var(--color-primary);
        transition: background 0.2s ease;
    }
    
    .auth-button:hover:not(:disabled) {
        background: var(--color-primary-dark);
    }

    .auth-link {
        color: var(--color-primary);
        text-decoration: none;
        transition: color 0.2s ease;
    }
    
    .auth-link:hover { color: var(--color-primary-light); }

    .animate-shake { animation: shake 0.5s cubic-bezier(.36,.07,.19,.97) both; }

    @keyframes shake {
        0%, 100% { transform: translateX(0); }
        10%, 30%, 50%, 70%, 90% { transform: translateX(-10px); }
        20%, 40%, 60%, 80% { transform: translateX(10px); }
    }

    /* Desktop: show text input, hide keypad */
    @media (min-width: 1024px) {
        .mobile-keypad { display: none !important; }
        .desktop-input { display: block !important; }
    }
    /* Mobile: show keypad, hide text input */
    @media (max-width: 1023px) {
        .mobile-keypad { display: grid !important; }
        .desktop-input { display: none !important; }
    }
    </style>
</head>

<body class="antialiased overflow-x-hidden">
    
    <div class="min-h-screen flex items-center justify-center p-4">
        
        <div class="w-full max-w-6xl mx-auto">
            <div class="grid lg:grid-cols-2 gap-8 items-center">
                
                <!-- Left Side – Security Information (desktop only) -->
                <div class="hidden lg:block space-y-8">
                    <div class="mb-8">
                        <img src="<?= $web_url ?>/admin/assets/images/logo/<?= htmlspecialchars($page['image']) ?>" 
                             alt="<?= $web_url ?>" 
                             class="h-12 w-auto mb-6">
                    </div>
                    
                    <div class="space-y-6">
                        <h1 class="text-4xl font-semibold text-[#0D1B23] leading-tight">Secure Access</h1>
                        <p class="text-lg text-[#4A4A4A] leading-relaxed">
                            Two-factor authentication provides an additional layer of security for your banking operations. Enter your 4-digit PIN to continue.
                        </p>
                    </div>
                    
                    <div class="space-y-4">
                        <h3 class="text-sm font-semibold text-[#0D1B23] uppercase tracking-wider mb-4">Why PIN Verification?</h3>
                        <div class="space-y-4">
                            <div class="flex items-start space-x-4">
                                <div class="flex-shrink-0 w-10 h-10 rounded-lg bg-[#DFE5E5] flex items-center justify-center">
                                    <i data-lucide="shield-check" class="w-5 h-5 text-[#49786B]"></i>
                                </div>
                                <div>
                                    <p class="text-sm font-semibold text-[#0D1B23] mb-1">Enhanced Security</p>
                                    <p class="text-xs text-[#7A7A7A]">Two-factor authentication protects your account from unauthorized access</p>
                                </div>
                            </div>
                            <div class="flex items-start space-x-4">
                                <div class="flex-shrink-0 w-10 h-10 rounded-lg bg-[#DFE5E5] flex items-center justify-center">
                                    <i data-lucide="lock-keyhole" class="w-5 h-5 text-[#7A7A7A]"></i>
                                </div>
                                <div>
                                    <p class="text-sm font-semibold text-[#0D1B23] mb-1">Transaction Safety</p>
                                    <p class="text-xs text-[#7A7A7A]">Verify your identity before accessing sensitive banking operations</p>
                                </div>
                            </div>
                            <div class="flex items-start space-x-4">
                                <div class="flex-shrink-0 w-10 h-10 rounded-lg bg-[#DFE5E5] flex items-center justify-center">
                                    <i data-lucide="fingerprint" class="w-5 h-5 text-[#49786B]"></i>
                                </div>
                                <div>
                                    <p class="text-sm font-semibold text-[#0D1B23] mb-1">Identity Confirmation</p>
                                    <p class="text-xs text-[#7A7A7A]">Ensures only you can access your financial information</p>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="pt-8">
                        <div class="bg-white border border-[#E0E5E5] rounded-xl p-5">
                            <div class="flex items-start space-x-3">
                                <i data-lucide="info" class="w-5 h-5 text-[#7A7A7A] flex-shrink-0 mt-0.5"></i>
                                <div>
                                    <p class="text-sm font-semibold text-[#0D1B23] mb-2">Keep Your PIN Private</p>
                                    <p class="text-xs text-[#7A7A7A] leading-relaxed">
                                        Never share your PIN with anyone, including bank staff. We will never ask for your PIN via email or phone.
                                    </p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Right Side – PIN Card -->
                <div class="w-full">
                    <!-- Mobile Logo -->
                    <div class="lg:hidden text-center mb-8">
                        <img src="<?= $web_url ?>/admin/assets/images/logo/<?= htmlspecialchars($page['image']) ?>" 
                             alt="<?= $web_url ?>" 
                             class="h-10 w-auto mx-auto">
                    </div>
                    
                    <div id="pin-card" class="auth-card rounded-xl p-8 md:p-10 space-y-8">
                        
                        <!-- User Profile -->
                        <div class="text-center space-y-4">
                            <div class="relative inline-block">
                                <img src="<?= $web_url ?>/assets/user/profile/<?= $row['acct_image'] ?>" 
                                     alt="<?= $fullName ?>"
                                     class="w-20 h-20 rounded-xl object-cover border-2 border-[#C8D1D1]"
                                     onerror="this.src='<?= $web_url ?>/assets/user/profile/<?= $row['acct_image'] ?>'">
                                <div class="absolute -bottom-2 -right-2 w-8 h-8 rounded-lg bg-[#49786B] flex items-center justify-center border-2 border-white">
                                    <i data-lucide="shield-check" class="w-4 h-4 text-white"></i>
                                </div>
                            </div>
                            <div>
                                <h2 class="text-xl font-semibold text-[#0D1B23]"><?= htmlspecialchars($fullName) ?></h2>
                                <p class="text-sm text-[#7A7A7A] mt-1">Enter your 4-digit PIN to continue</p>
                            </div>
                        </div>
                        
                        <!-- Error Message (PHP-driven) -->
                        <?php if(isset($_POST['pincode_submit']) && $_POST['input'] !== $row['acct_pin']): ?>
                        <div id="php-error" class="bg-[#D55672]/10 border border-[#D55672]/30 rounded-xl p-4">
                            <div class="flex items-center space-x-3">
                                <i data-lucide="alert-circle" class="w-6 h-6 text-[#D55672] flex-shrink-0"></i>
                                <p class="text-sm text-[#D55672] font-medium">
                                    <?= empty($_POST['input']) ? 'Please enter your PIN' : 'Invalid PIN. Please try again.' ?>
                                </p>
                            </div>
                        </div>
                        <?php endif; ?>

                        <!-- JS Error Message -->
                        <div id="js-error" class="hidden bg-[#D55672]/10 border border-[#D55672]/30 rounded-xl p-4">
                            <div class="flex items-center space-x-3">
                                <i data-lucide="alert-circle" class="w-6 h-6 text-[#D55672] flex-shrink-0"></i>
                                <p id="js-error-msg" class="text-sm text-[#D55672] font-medium"></p>
                            </div>
                        </div>
                        
                        <!-- PIN Dots Indicator -->
                        <div class="flex justify-center space-x-4 py-2">
                            <div id="dot1" class="w-4 h-4 rounded-full transition-all duration-200 bg-[#DFE5E5] border-2 border-[#C8D1D1]"></div>
                            <div id="dot2" class="w-4 h-4 rounded-full transition-all duration-200 bg-[#DFE5E5] border-2 border-[#C8D1D1]"></div>
                            <div id="dot3" class="w-4 h-4 rounded-full transition-all duration-200 bg-[#DFE5E5] border-2 border-[#C8D1D1]"></div>
                            <div id="dot4" class="w-4 h-4 rounded-full transition-all duration-200 bg-[#DFE5E5] border-2 border-[#C8D1D1]"></div>
                        </div>
                        
                        <!-- Single form used by both desktop input and mobile keypad -->
                        <form id="pinForm" method="POST" action="">
                            <input type="hidden" name="input" id="pinInput" value="">
                            <!-- Always present so form.submit() (auto-confirm) sends this flag -->
                            <input type="hidden" name="pincode_submit" value="1">
                            
                            <!-- Desktop: text input + submit button -->
                            <div class="desktop-input space-y-4" style="display:none;">
                                <div class="space-y-2">
                                    <label for="pin-input-desktop" class="block text-sm font-semibold text-[#4A4A4A] text-center">
                                        Enter Your PIN
                                    </label>
                                    <input 
                                        id="pin-input-desktop"
                                        type="password"
                                        maxlength="4"
                                        inputmode="numeric"
                                        pattern="[0-9]{4}"
                                        placeholder="••••"
                                        autofocus
                                        autocomplete="off"
                                        class="auth-input w-full px-4 py-4 rounded-xl text-2xl text-center tracking-[1em] font-bold"
                                    />
                                </div>
                                
                                <button 
                                    type="submit"
                                    name="pincode_submit"
                                    id="verifyBtnDesktop"
                                    disabled
                                    class="auth-button w-full py-4 rounded-xl font-semibold text-white text-sm flex items-center justify-center space-x-2 disabled:opacity-50 disabled:cursor-not-allowed group"
                                >
                                    <i data-lucide="shield-check" class="w-5 h-5"></i>
                                    <span>Verify PIN</span>
                                    <i data-lucide="arrow-right" class="w-5 h-5 group-hover:translate-x-1 transition-transform"></i>
                                </button>
                            </div>
                            
                            <!-- Mobile: numeric keypad -->
                            <div class="mobile-keypad grid-cols-3 gap-4" style="display:none;">
                                <?php foreach([1,2,3,4,5,6,7,8,9] as $d): ?>
                                <button type="button"
                                        onclick="addDigit('<?= $d ?>')"
                                        class="aspect-square rounded-xl bg-white hover:bg-[#F9F9F9] border border-[#E0E5E5] hover:border-[#49786B]/50 text-[#0D1B23] text-2xl font-semibold transition-colors active:scale-95">
                                    <?= $d ?>
                                </button>
                                <?php endforeach; ?>
                                
                                <!-- Clear all -->
                                <button type="button"
                                        onclick="clearPin()"
                                        class="aspect-square rounded-xl bg-[#DFE5E5] hover:bg-[#C8D1D1] border border-[#E0E5E5] text-[#4A4A4A] text-lg font-semibold transition-colors active:scale-95 flex items-center justify-center">
                                    <i data-lucide="x" class="w-5 h-5"></i>
                                </button>
                                
                                <!-- Zero -->
                                <button type="button"
                                        onclick="addDigit('0')"
                                        class="aspect-square rounded-xl bg-white hover:bg-[#F9F9F9] border border-[#E0E5E5] hover:border-[#49786B]/50 text-[#0D1B23] text-2xl font-semibold transition-colors active:scale-95">
                                    0
                                </button>
                                
                                <!-- Backspace -->
                                <button type="button"
                                        onclick="backspace()"
                                        class="aspect-square rounded-xl bg-[#D55672]/10 hover:bg-[#D55672]/20 border border-[#D55672]/20 hover:border-[#D55672]/40 text-[#D55672] transition-colors active:scale-95 flex items-center justify-center">
                                    <i data-lucide="delete" class="w-6 h-6"></i>
                                </button>
                                
                                <!-- Mobile submit -->
                                <div class="col-span-3 mt-2">
                                    <button 
                                        type="submit"
                                        name="pincode_submit"
                                        id="verifyBtnMobile"
                                        disabled
                                        class="auth-button w-full py-4 rounded-xl font-semibold text-white text-sm flex items-center justify-center space-x-2 disabled:opacity-50 disabled:cursor-not-allowed"
                                    >
                                        <i data-lucide="shield-check" class="w-5 h-5"></i>
                                        <span>Verify PIN</span>
                                    </button>
                                </div>
                            </div>
                        </form>
                        
                        <!-- Footer -->
                        <div class="pt-4 border-t border-[#E0E5E5]">
                            <div class="flex items-center justify-between text-xs text-[#7A7A7A]">
                                <a href="<?= $web_url ?>"
                                   onclick="event.preventDefault(); document.getElementById('logout-form').submit();"
                                   class="auth-link inline-flex items-center space-x-1">
                                    <i data-lucide="log-out" class="w-4 h-4"></i>
                                    <span>Return Home</span>
                                </a>
                                <span>Secure Connection</span>
                            </div>
                        </div>
                        
                        <!-- Logout Form -->
                        <form id="logout-form" action="<?= $web_url ?>" method="POST" class="hidden"></form>
                        
                    </div>
                </div><!-- /right side -->
                
            </div>
        </div>
    </div>
    
    <!-- Scripts -->
    <script src="https://code.jquery.com/jquery-3.6.1.min.js"></script>
    <script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
    
    <script>
        // ── PIN state ──────────────────────────────────────────────
        let pin = '';
        const MAX = 4;

        function addDigit(digit) {
            if (pin.length < MAX) {
                pin += digit;
                if (navigator.vibrate) navigator.vibrate(10);
                updateDisplay();
                if (pin.length === MAX) {
                    // Brief delay to show fourth dot before submit
                    setTimeout(() => document.getElementById('pinForm').submit(), 300);
                }
            }
        }

        function backspace() {
            pin = pin.slice(0, -1);
            if (navigator.vibrate) navigator.vibrate(10);
            updateDisplay();
        }

        function clearPin() {
            pin = '';
            updateDisplay();
        }

        function updateDisplay() {
            // Update dots
            for (let i = 1; i <= MAX; i++) {
                const dot = document.getElementById('dot' + i);
                if (i <= pin.length) {
                    dot.style.background = '#49786B';
                    dot.style.borderColor = '#49786B';
                    dot.style.transform = 'scale(1.2)';
                } else {
                    dot.style.background = '';
                    dot.style.borderColor = '';
                    dot.style.transform = '';
                }
            }

            // Sync hidden input
            document.getElementById('pinInput').value = pin;

            // Sync desktop input display (read-only reflection)
            const desktopInput = document.getElementById('pin-input-desktop');
            if (desktopInput) desktopInput.value = pin;

            // Toggle submit buttons
            const ready = pin.length === MAX;
            ['verifyBtnDesktop', 'verifyBtnMobile'].forEach(id => {
                const btn = document.getElementById(id);
                if (btn) btn.disabled = !ready;
            });
        }

        // Desktop text input: sync pin variable from direct typing
        document.addEventListener('DOMContentLoaded', () => {
            const desktopInput = document.getElementById('pin-input-desktop');
            if (desktopInput) {
                desktopInput.addEventListener('input', function() {
                    // Keep only digits
                    this.value = this.value.replace(/[^0-9]/g, '').slice(0, MAX);
                    pin = this.value;
                    updateDisplay();
                });
            }

            // Keyboard support (works on all viewports when focused)
            document.addEventListener('keydown', function(e) {
                if (document.activeElement === desktopInput) return; // let native input handle it
                if (e.key >= '0' && e.key <= '9') addDigit(e.key);
                else if (e.key === 'Backspace') backspace();
                else if (e.key === 'Escape') clearPin();
            });

            // Initialize Lucide icons
            if (typeof lucide !== 'undefined') lucide.createIcons();

            // Shake card if PHP reported an error
            <?php if(isset($_POST['pincode_submit']) && $_POST['input'] !== $row['acct_pin']): ?>
            const card = document.getElementById('pin-card');
            card.classList.add('animate-shake');
            setTimeout(() => card.classList.remove('animate-shake'), 500);
            <?php endif; ?>
        });

        // Form validation before submit
        document.getElementById('pinForm').addEventListener('submit', function(e) {
            if (pin.length !== MAX) {
                e.preventDefault();
                showJsError('Please enter a 4-digit PIN');
            }
        });

        function showJsError(msg) {
            const box = document.getElementById('js-error');
            document.getElementById('js-error-msg').textContent = msg;
            box.classList.remove('hidden');
            setTimeout(() => box.classList.add('hidden'), 4000);
        }
    </script>

    <!-- GTranslate -->
    <style>
    .gtranslate_wrapper {
        border-radius: 8px !important;
        padding: 4px 6px !important;
        border: 1px solid rgba(51, 65, 85, 0.6) !important;
        box-shadow: 0 4px 12px rgba(0,0,0,0.3) !important;
        max-width: 160px !important;
        background: rgba(15, 23, 42, 0.95) !important;
        backdrop-filter: blur(8px) !important;
        position: fixed !important;
    }
    @media (max-width: 767px) {
        .gtranslate_wrapper { bottom: 52px !important; left: 12px !important; z-index: 45 !important; }
    }
    @media (min-width: 768px) {
        .gtranslate_wrapper { bottom: 20px !important; left: 20px !important; z-index: 45 !important; }
    }
    .gtranslate_wrapper select { font-size: 10px !important; background: transparent !important; color: #cbd5e1 !important; border: none !important; }
    </style>
    <div class="gtranslate_wrapper"></div>
    <script>
        window.gtranslateSettings = {
            default_language: "en",
            alt_flags: {"en": "usa"},
            wrapper_selector: ".gtranslate_wrapper",
            flag_style: "3d"
        };
    </script>
    <script src="https://cdn.gtranslate.net/widgets/latest/float.js" defer></script>

</body>
</html>