<?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 class="pin-container d-flex justify-content-center mb-3">
                        <!-- 2 input pertama -->
                        <div class="d-flex gap-2">
                            <input type="text" class="form-control pin-input text-center" maxlength="1" style="width: 50px">
                            <input type="text" class="form-control pin-input text-center" maxlength="1" style="width: 50px">
                        </div>
                        
                        <!-- Spacer -->
                        <div style="width: 30px"></div>
                        
                        <!-- 4 input terakhir -->
                        <div class="d-flex gap-2">
                            <input type="text" class="form-control pin-input text-center" maxlength="1" style="width: 50px">
                            <input type="text" class="form-control pin-input text-center" maxlength="1" style="width: 50px">
                            <input type="text" class="form-control pin-input text-center" maxlength="1" style="width: 50px">
                            <input type="text" class="form-control pin-input text-center" maxlength="1" style="width: 50px">
                        </div>
                    </div>
                    <div id="pin-error" class="alert alert-danger d-none">
                        Invalid Token
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" id="submitPin">Submit</button>
                </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', function() {
        // Tampilkan modal saat halaman dimuat
        const pinModal = new bootstrap.Modal(document.getElementById('pinModal'));
        pinModal.show();

        // Dapatkan tanggal saat ini (2 digit)
        const currentDate = new Date().getDate().toString().padStart(2, '0');
        const defaultPin = '5758';

        const pinInputs = document.querySelectorAll('.pin-input');
        
        // Auto focus ke input berikutnya
        pinInputs.forEach((input, index) => {
            input.addEventListener('input', function(e) {
                if (this.value && index < pinInputs.length - 1) {
                    pinInputs[index + 1].focus();
                }
            });

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

        document.getElementById('submitPin').addEventListener('click', function() {
            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');
                pinModal.hide();
            } else {
                document.getElementById('pin-error').classList.remove('d-none');
            }
        });
    });
    </script>
</body>
</html>
