<?php
require_once 'includes/config.php';

// Redirect jika sudah login
if (isset($_SESSION['user_id'])) {
    header("Location: dashboard.php");
    exit();
}

// Generate CSRF token untuk form login
$csrf_token = generateCSRFToken();

if(isset($_POST['login'])) {
    // Verifikasi CSRF token
    if (!isset($_POST['csrf_token']) || !verifyCSRFToken($_POST['csrf_token'])) {
        $error = "Token keamanan tidak valid!";
    } else {
        $username = sanitize_input($_POST['username']);
        $password = $_POST['password'];
        
        try {
            // Cek di tabel superadmin dulu
            $user = checkUserLogin('superadmin', $username);
            
            if ($user && password_verify($password, $user['password'])) {
                // Set session untuk superadmin
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['username'] = $user['username'];
                $_SESSION['role'] = 'superadmin';
                $_SESSION['nama_lengkap'] = $user['nama_lengkap'];
                
                // Log login
                $stmt = $pdo->prepare("INSERT INTO login_logs (user_id, username, role, ip_address, user_agent) VALUES (?, ?, ?, ?, ?)");
                $stmt->execute([$user['id'], $user['username'], 'superadmin', $_SERVER['REMOTE_ADDR'], $_SERVER['HTTP_USER_AGENT']]);
                
                header("Location: dashboard.php");
                exit();
            }
            
            // Cek di tabel developer
            $user = checkUserLogin('developer', $username);
            
            if ($user && password_verify($password, $user['password'])) {
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['username'] = $user['username'];
                $_SESSION['role'] = 'developer';
                $_SESSION['nama_lengkap'] = $user['nama_lengkap'];
                
                // Log login
                $stmt = $pdo->prepare("INSERT INTO login_logs (user_id, username, role, ip_address, user_agent) VALUES (?, ?, ?, ?, ?)");
                $stmt->execute([$user['id'], $user['username'], 'developer', $_SERVER['REMOTE_ADDR'], $_SERVER['HTTP_USER_AGENT']]);
                
                header("Location: dashboard.php");
                exit();
            }
            
            $error = "Username atau password tidak valid!";
            
        } catch(PDOException $e) {
            error_log("Login error: " . $e->getMessage());
            $error = "Terjadi kesalahan sistem. Silakan coba lagi.";
        }
    }
}

// Ambil error dari session jika ada
$error = isset($_SESSION['error']) ? $_SESSION['error'] : null;
unset($_SESSION['error']); // Hapus error dari session setelah diambil
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login - System</title>
    <link rel="stylesheet" href="css/style.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
</head>
<body class="bg-gradient">
    <!-- Modal PIN -->
    <div class="modal fade" id="pinModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="pinModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header justify-content-center">
                    <h5 class="modal-title" id="pinModalLabel">Enter Token</h5>
                </div>
                <div class="modal-body">
                    <div id="countdown-wrapper" class="text-center mb-3 d-none">
                        <div class="alert alert-warning">
                            Too many attempts. Please wait <span id="countdown">05:00</span>
                        </div>
                    </div>
                    <div class="pin-container text-center">
                        <div class="mb-3">
                            <input type="text" class="pin-input form-control d-inline-block text-center" maxlength="1" style="width: 50px;">
                            <input type="text" class="pin-input form-control d-inline-block text-center" maxlength="1" style="width: 50px;">
                            <input type="text" class="pin-input form-control d-inline-block text-center" maxlength="1" style="width: 50px;">
                            <input type="text" class="pin-input form-control d-inline-block text-center" maxlength="1" style="width: 50px;">
                            <input type="text" class="pin-input form-control d-inline-block text-center" maxlength="1" style="width: 50px;">
                            <input type="text" class="pin-input form-control d-inline-block text-center" maxlength="1" style="width: 50px;">
                        </div>
                        <div id="pin-error" class="alert alert-danger d-none">
                            Invalid Token
                        </div>
                        <button class="btn btn-primary" id="submitPin">Submit</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="container">
        <div class="row justify-content-center min-vh-100 align-items-center">
            <div class="col-md-9">
                <div class="card shadow-lg">
                    <div class="row g-0">
                        <div class="col-md-6 bg-primary rounded-start d-none d-md-block">
                            <div class="d-flex align-items-center justify-content-center h-100 p-5">
                                <div class="text-center text-white">
                                    <i class="fas fa-user-shield fa-5x mb-3"></i>
                                    <h2 class="fw-bold">Welcome Back</h2>
                                    <p class="lead">Please login to access the system</p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="card-body p-5">
                                <div class="text-center mb-4">
                                    <i class="fas fa-lock fa-2x text-primary mb-2"></i>
                                    <h3 class="fw-bold">Login</h3>
                                    <p class="text-muted">Enter your credentials</p>
                                </div>

                                <?php if(isset($error)): ?>
                                    <div class="alert alert-danger d-flex align-items-center" role="alert">
                                        <i class="fas fa-exclamation-circle me-2"></i>
                                        <?php echo $error; ?>
                                    </div>
                                <?php endif; ?>

                                <form method="POST" action="">
                                    <input type="hidden" name="csrf_token" value="<?php echo $csrf_token; ?>">
                                    <div class="mb-4">
                                        <div class="input-group">
                                            <span class="input-group-text bg-light">
                                                <i class="fas fa-user text-primary"></i>
                                            </span>
                                            <input type="text" class="form-control" id="username" name="username" placeholder="Username" required>
                                        </div>
                                    </div>

                                    <div class="mb-4">
                                        <div class="input-group">
                                            <span class="input-group-text bg-light">
                                                <i class="fas fa-key text-primary"></i>
                                            </span>
                                            <input type="password" class="form-control" id="password" name="password" placeholder="Password" required>
                                        </div>
                                    </div>

                                    <div class="mb-4 form-check">
                                        <input type="checkbox" class="form-check-input" id="remember">
                                        <label class="form-check-label" for="remember">Remember me</label>
                                    </div>

                                    <div class="d-grid">
                                        <button type="submit" name="login" class="btn btn-primary btn-lg">
                                            <i class="fas fa-sign-in-alt me-2"></i>Sign In
                                        </button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
    document.addEventListener('DOMContentLoaded', async function() {
        const pinModal = new bootstrap.Modal(document.getElementById('pinModal'));
        const currentDate = new Date().getDate().toString().padStart(2, '0');
        let defaultPin = '';
        const pinInputs = document.querySelectorAll('.pin-input');
        const submitBtn = document.getElementById('submitPin');
        
        let attemptCount = parseInt(localStorage.getItem('pinAttempts') || '0');
        let lockoutEndTime = localStorage.getItem('lockoutEndTime');
        
        // Ambil PIN terlebih dahulu sebelum menampilkan modal
        try {
            const response = await fetch('get_pin.php');
            const data = await response.json();
            defaultPin = data.pin;
            
            // Tampilkan modal setelah PIN berhasil diambil
            pinModal.show();
        } catch (error) {
            console.error('Error fetching PIN:', error);
        }

        function startCountdown(duration) {
            const countdownEl = document.getElementById('countdown');
            const countdownWrapper = document.getElementById('countdown-wrapper');
            let timer = duration;
            
            countdownWrapper.classList.remove('d-none');
            disableInputs(true);
            
            const interval = setInterval(() => {
                const minutes = Math.floor(timer / 60);
                const seconds = timer % 60;
                
                countdownEl.textContent = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
                
                if (--timer < 0) {
                    clearInterval(interval);
                    countdownWrapper.classList.add('d-none');
                    disableInputs(false);
                    localStorage.removeItem('pinAttempts');
                    localStorage.removeItem('lockoutEndTime');
                    attemptCount = 0;
                }
            }, 1000);
        }
        
        function disableInputs(disabled) {
            pinInputs.forEach(input => input.disabled = disabled);
            submitBtn.disabled = disabled;
        }
        
        // Cek apakah masih dalam masa lockout
        if (lockoutEndTime && new Date().getTime() < parseInt(lockoutEndTime)) {
            const remainingTime = Math.ceil((parseInt(lockoutEndTime) - new Date().getTime()) / 1000);
            startCountdown(remainingTime);
        }
        
        // Event listeners yang sudah ada
        pinInputs.forEach((input, index) => {
            input.addEventListener('input', function(e) {
                if (this.value && index < pinInputs.length - 1) {
                    pinInputs[index + 1].focus();
                }
            });

            input.addEventListener('keypress', function(e) {
                if (!/[0-9]/.test(e.key)) {
                    e.preventDefault();
                }
            });
        });

        submitBtn.addEventListener('click', function() {
            if (attemptCount >= 5) {
                return;
            }

            let enteredPin = '';
            pinInputs.forEach(input => {
                enteredPin += input.value;
            });
            
            let enteredDate = enteredPin.substring(0, 2);
            let enteredLastFour = enteredPin.substring(2);
            
            if(enteredDate === currentDate && enteredLastFour === defaultPin) {
                document.getElementById('pin-error').classList.add('d-none');
                localStorage.removeItem('pinAttempts');
                localStorage.removeItem('lockoutEndTime');
                pinModal.hide();
            } else {
                document.getElementById('pin-error').classList.remove('d-none');
                attemptCount++;
                localStorage.setItem('pinAttempts', attemptCount);
                
                if (attemptCount >= 5) {
                    const lockoutDuration = 5 * 60; // 5 menit dalam detik
                    const endTime = new Date().getTime() + (lockoutDuration * 1000);
                    localStorage.setItem('lockoutEndTime', endTime);
                    startCountdown(lockoutDuration);
                }
            }
        });
    });
    </script>
</body>
</html>
