<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/../config/db.php';

// Jika sudah login → redirect sesuai role
if (!empty($_SESSION['user'])) {

    if ($_SESSION['user']['role'] === 'superadmin') {
        header("Location: /presensi_v1/pages/dashboard.php");
        exit;
    }

    if ($_SESSION['user']['role'] === 'operator') {
        header("Location: /presensi_v1/pages/dashboard.php");
        exit;
    }

    if ($_SESSION['user']['role'] === 'guru') {
        header("Location: /presensi_v1/pages/dashboard_guru.php");
        exit;
    }
}

$err = "";

// PROSES LOGIN
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $username = trim($_POST['username']);
    $password = $_POST['password'];

    if ($username === "" || $password === "") {
        $err = "Isi username & password.";
    } else {

        $stmt = $pdo->prepare("SELECT * FROM users WHERE username = :u LIMIT 1");
        $stmt->execute([':u' => $username]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($row && password_verify($password, $row['password'])) {

            // SET SESSION USER
            $_SESSION['user'] = [
                'id'       => $row['id'],
                'username' => $row['username'],
                'nama'     => $row['nama'],
                'role'     => $row['role']
            ];

            // Redirect berdasarkan role
            switch ($row['role']) {

                case 'superadmin':
                case 'operator':
                    header("Location: /presensi_v1/pages/dashboard.php");
                    exit;

                case 'guru':
                    header("Location: /presensi_v1/pages/dashboard_guru.php");
                    exit;
            }

        } else {
            $err = "Login gagal, periksa username atau password.";
        }
    }
}
?>
<!doctype html>
<html lang="id">
<head>
<meta charset="utf-8">
<title>Login - PRESENSI</title>

<!-- GOOGLE FONT -->
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600&display=swap" rel="stylesheet">

<!-- BOOTSTRAP -->
<link rel="stylesheet" href="/presensi_v1/assets/vendor/bootstrap.min.css">

<!-- CUSTOM LOGIN STYLE -->
<link rel="stylesheet" href="/presensi_v1/assets/css/login.css">

</head>

<body>

<div class="glow-circle"></div>
<div class="glow-circle2"></div>

<div class="login-card">

    <div class="login-title">Login Presensi</div>

    <?php if ($err): ?>
        <div class="alert alert-danger p-2">
            <?= htmlspecialchars($err) ?>
        </div>
    <?php endif; ?>

    <form method="POST">
        <input autofocus name="username" class="form-control mb-3"
               placeholder="Username" autocomplete="username">

        <input name="password" type="password" class="form-control mb-3"
               placeholder="Password" autocomplete="current-password">

        <button class="btn-login w-100">Masuk</button>
    </form>

</div>

</body>
</html>
