<?php
session_start();
include 'config.php';

// Jika sudah login final, lempar ke dashboard
if (isset($_SESSION['user_id'])) {
    header("Location: dashboard.php");
    exit();
}

$error = "";
$otp_mode = false; // Mode awal adalah Login Form
$generated_otp = "";

// 1. LOGIKA SUBMIT
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $action = $_POST['action'] ?? 'login';

    // A. PROSES LOGIN (Step 1)
    if ($action == 'login') {
        $username = $conn->real_escape_string($_POST['username']);
        $password = $_POST['password'];

        $sql = "SELECT id, password, role FROM users WHERE username = '$username'";
        $result = $conn->query($sql);

        if ($result->num_rows > 0) {
            $row = $result->fetch_assoc();
            if (password_verify($password, $row['password'])) {
                // Password Benar -> Generate OTP
                $otp_code = rand(100000, 999999); // 6 Digit Acak
                
                // Simpan Data Sementara di Session
                $_SESSION['temp_login_id'] = $row['id'];
                $_SESSION['temp_login_otp'] = $otp_code;
                
                $otp_mode = true;
                $generated_otp = $otp_code; // Untuk dikirim ke JS SweetAlert
            } else {
                $error = "Password salah!";
            }
        } else {
            $error = "Username tidak ditemukan!";
        }
    }

    // B. PROSES VERIFIKASI OTP (Step 2)
    if ($action == 'verify_otp') {
        $input_otp = $_POST['otp_code'];
        $session_otp = $_SESSION['temp_login_otp'] ?? '';
        
        if ($input_otp == $session_otp) {
            // OTP BENAR -> Login Final
            $_SESSION['user_id'] = $_SESSION['temp_login_id'];
            
            // Hapus session temp
            unset($_SESSION['temp_login_id']);
            unset($_SESSION['temp_login_otp']);
            
            header("Location: dashboard.php");
            exit();
        } else {
            // OTP SALAH
            $error = "Kode OTP Salah!";
            $otp_mode = true; // Tetap di mode OTP
        }
    }
}
?>

<!DOCTYPE html>
<html lang="id" class="dark">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login Member</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            darkMode: 'class',
            theme: { extend: { colors: { primary: '#10b981', darkbg: '#0f172a' } } }
        }
    </script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
</head>
<body class="bg-gray-100 dark:bg-darkbg text-gray-800 dark:text-gray-200 min-h-screen flex items-center justify-center p-4">

    <div class="bg-white dark:bg-slate-800 w-full max-w-sm rounded-2xl shadow-2xl p-8 animate-[fadeIn_0.5s_ease-out]">
        
        <div class="text-center mb-8">
            <div class="w-16 h-16 bg-primary rounded-full flex items-center justify-center mx-auto mb-4 shadow-lg text-white text-2xl">
                <i class="fas <?php echo $otp_mode ? 'fa-shield-alt' : 'fa-lock'; ?>"></i>
            </div>
            <h2 class="text-2xl font-bold"><?php echo $otp_mode ? 'Verifikasi OTP' : 'Welcome Back'; ?></h2>
            <p class="text-xs text-gray-400"><?php echo $otp_mode ? 'Masukkan 6 digit kode keamanan' : 'Silakan login ke akun Anda'; ?></p>
        </div>

        <?php if($error): ?>
        <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mb-4 text-sm" role="alert">
            <span class="block sm:inline"><?php echo $error; ?></span>
        </div>
        <?php endif; ?>
        
        <!-- FORM LOGIN BIASA -->
        <?php if(!$otp_mode): ?>
        <form action="" method="POST" class="space-y-5">
            <input type="hidden" name="action" value="login">
            <div>
                <label class="block text-sm font-bold mb-1 text-gray-500">Username</label>
                <div class="relative">
                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none text-gray-400">
                        <i class="fas fa-user"></i>
                    </div>
                    <input type="text" name="username" required class="w-full pl-10 p-3 rounded-lg bg-gray-50 dark:bg-slate-900 border border-gray-200 dark:border-slate-700 focus:outline-none focus:border-primary transition" placeholder="Username Anda">
                </div>
            </div>

            <div>
                <label class="block text-sm font-bold mb-1 text-gray-500">Password</label>
                <div class="relative">
                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none text-gray-400">
                        <i class="fas fa-key"></i>
                    </div>
                    <!-- Eye Icon Added -->
                    <input type="password" name="password" id="passInput" required class="w-full pl-10 pr-10 p-3 rounded-lg bg-gray-50 dark:bg-slate-900 border border-gray-200 dark:border-slate-700 focus:outline-none focus:border-primary transition" placeholder="********">
                    <button type="button" onclick="togglePass()" class="absolute inset-y-0 right-0 px-3 flex items-center text-gray-400 hover:text-primary">
                        <i class="fas fa-eye" id="eyeIcon"></i>
                    </button>
                </div>
            </div>

            <button type="submit" class="w-full bg-primary hover:bg-emerald-600 text-white font-bold py-3 rounded-xl shadow-lg transition transform active:scale-95">
                LOGIN
            </button>
        </form>
        
        <div class="mt-6 text-center border-t dark:border-slate-700 pt-4">
            <p class="text-xs text-gray-400">Belum punya akun?</p>
            <a href="http://localhost/mlm-app/register.php" class="text-sm font-bold text-primary hover:underline">Daftar via Network</a>
        </div>
        <?php endif; ?>

        <!-- FORM OTP (6 DIGIT) -->
        <?php if($otp_mode): ?>
        <form id="otpForm" action="" method="POST" class="space-y-5">
            <input type="hidden" name="action" value="verify_otp">
            <input type="hidden" name="otp_code" id="fullOtpCode">
            
            <div class="flex justify-between gap-2">
                <!-- 6 Input Box -->
                <?php for($i=0; $i<6; $i++): ?>
                <input type="text" maxlength="1" class="otp-input w-12 h-12 text-center text-xl font-bold rounded-lg bg-gray-50 dark:bg-slate-900 border-2 border-gray-200 dark:border-slate-700 focus:border-primary focus:ring-0 transition" required>
                <?php endfor; ?>
            </div>

            <button type="button" disabled class="w-full bg-gray-300 text-white font-bold py-3 rounded-xl shadow-lg cursor-not-allowed">
                Verifikasi Otomatis...
            </button>
        </form>
        
        <script>
            // Trigger Notifikasi OTP via SweetAlert2
            Swal.fire({
                icon: 'info',
                title: 'Kode OTP Anda',
                html: '<h1 style="font-size: 40px; font-weight: bold; letter-spacing: 5px; color: #10b981;"><?php echo $generated_otp; ?></h1><br>Masukkan kode ini untuk login.',
                confirmButtonColor: '#10b981'
            });

            // Logic Input OTP DANA Style
            const inputs = document.querySelectorAll('.otp-input');
            const hiddenInput = document.getElementById('fullOtpCode');
            const form = document.getElementById('otpForm');

            inputs[0].focus(); // Auto focus pertama

            inputs.forEach((input, index) => {
                input.addEventListener('input', (e) => {
                    // Jika diisi, pindah ke kanan
                    if (e.target.value.length === 1) {
                        if (index < inputs.length - 1) {
                            inputs[index + 1].focus();
                        } else {
                            // Jika sudah di input terakhir, SUBMIT otomatis
                            submitForm();
                        }
                    }
                });

                input.addEventListener('keydown', (e) => {
                    // Jika backspace, pindah ke kiri
                    if (e.key === 'Backspace' && e.target.value === '' && index > 0) {
                        inputs[index - 1].focus();
                    }
                });
            });

            function submitForm() {
                let code = '';
                inputs.forEach(input => code += input.value);
                hiddenInput.value = code;
                
                // Animasi Loading sebelum submit
                Swal.fire({
                    title: 'Memeriksa...',
                    timerProgressBar: true,
                    didOpen: () => { Swal.showLoading() }
                });
                
                form.submit();
            }
        </script>
        <?php endif; ?>

    </div>

    <script>
        function togglePass() {
            const input = document.getElementById('passInput');
            const icon = document.getElementById('eyeIcon');
            if (input.type === "password") {
                input.type = "text";
                icon.classList.remove('fa-eye');
                icon.classList.add('fa-eye-slash');
            } else {
                input.type = "password";
                icon.classList.remove('fa-eye-slash');
                icon.classList.add('fa-eye');
            }
        }
    </script>
</body>
</html>